diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index 2ab491207..c902acf32 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -1,7 +1,6 @@ name: launcher # Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a -# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme, -# crates/horizon-telemetry), +# push to main that changes the launcher or a crate it builds in (the paths below), # every 10 minutes (a release waiting for merges to settle goes out) and by hand, tools/release_train.py decides as # for the game. # A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull @@ -14,10 +13,15 @@ on: push: branches: [main, launcher, 'launcher-*'] paths: + # Every crate the launcher builds in, as tools/release_train.py's LAUNCHER_PATHS. - 'launcher/**' + - 'crates/horizon-bench/**' + - 'crates/horizon-friends/**' + - 'crates/horizon-mods/**' + - 'crates/horizon-port-pack/**' - 'crates/horizon-prepare/**' - - 'crates/horizon-theme/**' - 'crates/horizon-telemetry/**' + - 'crates/horizon-theme/**' - '.github/workflows/launcher.yml' schedule: - cron: '7-59/10 * * * *' @@ -138,7 +142,8 @@ jobs: echo "::notice::No Metal toolchain on this runner: GPUI compiles its shaders at run time" echo "LAUNCHER_FEATURES=gpui/runtime_shaders" >> "$GITHUB_ENV" fi - - run: cargo test --release --locked --lib ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} + # Every test target (the library, the binary, tests/), on each system the launcher ships for. + - run: cargo test --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} - run: cargo build --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"} - name: The version is the release's run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 27636b0eb..a4780c85b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -174,7 +174,14 @@ jobs: case "${{ matrix.asset }}" in *.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;; *) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null - else ditto -c -k --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}"; fi ;; + else + # Without resource forks and extended attributes: plain ditto adds an + # AppleDouble `._` file beside every file that has any. + ditto -c -k --norsrc --noextattr --noqtn --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}" + if unzip -Z1 "${{ matrix.asset }}" | grep -E '(^|/)(\._|__MACOSX/)'; then + echo "::error::macOS metadata files in ${{ matrix.asset }}"; exit 1 + fi + fi ;; esac ls -l "${{ matrix.asset }}" - uses: actions/upload-artifact@v4 diff --git a/Cargo.lock b/Cargo.lock index ea6681a2c..b4081e7af 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1539,6 +1539,7 @@ dependencies = [ "horizon-world", "serde_json", "sha1", + "sha2", ] [[package]] @@ -1569,10 +1570,12 @@ dependencies = [ name = "horizon-server-files" version = "0.1.0" dependencies = [ + "base64", "horizon-core", "horizon-protocol", "horizon-world", "log", + "ureq", ] [[package]] diff --git a/README.md b/README.md index f4f3094ae..0efae1088 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ Captured in the Rust client itself, with vanilla assets and no mods or shaders. Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, and the last world played and the faint wordmark, over a veiled snowy landscape - The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons + The Singleplayer page: two worlds with their dates and game modes, and Create world and Play buttons The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs @@ -79,17 +79,17 @@ The vanilla menus are one setting away: Options → Interface → Menu style → Sunset over a savanna river valley and a plains village - A plains village with farms, an iron golem and animals - Survival at dusk: a zombie attacks near the village + A plains village among savanna hills, with farms, villagers and an iron golem + Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience A crimson forest in the Nether with a zombified piglin Moonrise over a torch-lit village and river - Salmon swimming in a river + Tropical fish over a warm-ocean coral reef - Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs, the HUD, chat and advancements: everything in these frames is drawn by Horizon. + Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs and the HUD: everything in these frames is drawn by Horizon. diff --git a/benchmarks/server-2026-10-17/README.md b/benchmarks/server-2026-10-17/README.md new file mode 100644 index 000000000..4a3cd3dcc --- /dev/null +++ b/benchmarks/server-2026-10-17/README.md @@ -0,0 +1,174 @@ +# Dedicated server against vanilla 26.3, with bots (2026-10-17) + +`horizon-client --dedicated` (run by `horizon-server`) against the pinned vanilla 26.3 `server.jar`, on `main` +at `7bbbf6e9` (in release v2026.10.17.17). That build has the movement checks and chunk pacing of #586, the +equal-work method of #670, and the server performance PRs #701–#707 and #713. + +This replaces the data first published here, which came from a Mac mini overloaded by other work (load 55–141 on +14 threads). An earlier run of this method, on `main` at `002f14ce`, is kept in `earlier-002f14ce/` and compared +at the end. + +## Setup + +- **Server machine:** ThinkPad, Intel i7-7500U (2 cores, 4 threads), 32 GB, NixOS. Nothing else heavy ran on it: + its load average was 0.4 when idle. Both servers ran under `nice -n 19`. +- **Bots:** `horizon-bots` on another machine (Mac mini M4 Pro), over the tailnet. That machine was shared with + other work (load 36–170 on 14 threads, mean 78). The bots need little CPU, but a busy bot host can answer later. + Both servers saw the same conditions, since they took turns at each bot count. +- **Horizon:** release build of `7bbbf6e9` (`horizon-server`, `horizon-client`). +- **Vanilla:** the pinned 26.3 `server.jar` on OpenJDK 25.0.4.1, with `-Xms4g -Xmx4g`. +- **Properties:** + - `level-seed=12345`, view and simulation distance 10, creative (forced); + - `online-mode=false`, `difficulty=easy`, `max-players=200`; + - default game rules on both (the locator bar is on). +- **Each run:** a fresh server, bots joining one per second, a 60 s warm-up, then 180 s measured. +- **Commands** (on the server machine): + ``` + python3 tools/server_bench.py --servers horizon,vanilla --nice 19 --warmup 60 --seconds 180 \ + --bots-via "ssh " --bots-bin --connect \ + --bots 1,10,25,50,100 --behaviour walk,explore + python3 tools/server_bench.py ...same... --bots 1,10,25,50 --behaviour explore --explore-speed 0.8 + ``` +- **Columns:** + - **MSPT** (mean) and **P95** come from `/tick query`, in ms. **TPS** is the tick rate. + - **RSS** is the mean over the run. **CPU** is the whole process tree, as a percentage of one core. + - **Chunks/s** is what the bots received. **New chunks/s** counts each chunk once per bot. + - **Pulled back** counts the times the server moved a bot back (vanilla's "moved too quickly" and similar). + - **Load** is the mean load average during that run: the server machine (which includes the server's own + threads) and the bot host. + +## Results + +### Equal work: bots explore at the same pace (`--explore-speed 0.8`) + +Each bot flies outwards at 0.8 blocks a second, which both servers keep up with. They send the same chunks, so +the tick times compare the same work. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 3.16 | 5.78 | 20.0 | 0.76 GB | 22 % | 2 | 1.27 | 0 | 2.8 / 63 | +| 1 | Vanilla | 16.82 | 27.3 | 20.0 | 3.37 GB | 69 % | 2 | 1.35 | 0 | 1.8 / 94 | +| 10 | Horizon | 9.83 | 19.01 | 20.0 | 0.86 GB | 77 % | 14 | 12.31 | 1051 | 2.2 / 74 | +| 10 | Vanilla | 24.38 | 39.58 | 20.0 | 3.57 GB | 132 % | 14 | 12.32 | 1027 | 2.5 / 64 | +| 25 | Horizon | 16.87 | 30.88 | 20.0 | 0.89 GB | 111 % | 34 | 29.92 | 3770 | 5.1 / 51 | +| 25 | Vanilla | 30.29 | 43.47 | 20.0 | 3.61 GB | 176 % | 33 | 29.29 | 5139 | 5.2 / 55 | +| 50 | Horizon | 23.57 | 47.53 | 20.0 | 0.92 GB | 127 % | 67 | 59.42 | 7434 | 8.5 / 64 | +| 50 | Vanilla | 42.44 | 54.84 | 20.0 | 3.67 GB | 201 % | 65 | 58.11 | 10604 | 5.1 / 59 | + +### `walk`: bots walk around the spawn + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 4.01 | 8.19 | 20.0 | 0.78 GB | 59 % | 10 | 0.43 | 0 | 1.4 / 70 | +| 1 | Vanilla | 18.22 | 29.34 | 20.0 | 3.43 GB | 69 % | 10 | 0.47 | 0 | 1.9 / 63 | +| 10 | Horizon | 8.79 | 17.35 | 20.0 | 0.78 GB | 119 % | 95 | 3.58 | 0 | 2.9 / 69 | +| 10 | Vanilla | 18.67 | 38.26 | 20.0 | 3.50 GB | 101 % | 101 | 4.38 | 5 | 3.2 / 59 | +| 25 | Horizon | 15.01 | 31.12 | 20.0 | 0.80 GB | 161 % | 234 | 8.49 | 0 | 6.3 / 43 | +| 25 | Vanilla | 18.78 | 28.16 | 20.0 | 3.52 GB | 155 % | 252 | 11.89 | 10 | 6.7 / 57 | +| 50 | Horizon | 22.72 | 60.19 | 20.0 | 0.81 GB | 180 % | 465 | 16.94 | 0 | 14.7 / 50 | +| 50 | Vanilla | 34.3 | 55.55 | 20.0 | 3.58 GB | 267 % | 497 | 26.74 | 39 | 9.5 / 56 | +| 100 | Horizon | 63.33 | 125.04 | 15.79 | 0.87 GB | 246 % | 678 | 31.8 | 0 | 32.9 / 95 | +| 100 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 15.1 / 120 | + +Both servers sent each walking bot the same number of distinct chunks over the whole run (680–690). Horizon's +"new chunks/s" inside the measured window is lower, so compare the totals, not that column. + +### `explore` at full speed: unequal work + +Bots fly outwards as fast as chunks arrive (`horizon-bots`' default, up to 22 blocks a second). Both servers now pull them back ("moved too quickly"), but Horizon sends +more new terrain, so this pass doesn't compare equal work. The server-machine load of Horizon's 1-bot run is +estimated from the time between the runs around it: its log was overwritten before it was read. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | Pulled back | Load (server / bots) | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 9.73 | 20.99 | 20.0 | 0.84 GB | 330 % | 41 | 35.96 | 0 | 4.7 / 129 | +| 1 | Vanilla | 9.71 | 20.37 | 20.0 | 3.61 GB | 247 % | 35 | 33.61 | 0 | 4.3 / 156 | +| 10 | Horizon | 21.27 | 39.15 | 20.0 | 1.18 GB | 322 % | 46 | 46.11 | 9856 | 5.0 / 114 | +| 10 | Vanilla | 16.94 | 30.28 | 20.0 | 3.95 GB | 254 % | 25 | 25.01 | 11123 | 5.5 / 89 | +| 25 | Horizon | 25.76 | 45.01 | 20.0 | 1.17 GB | 314 % | 61 | 60.7 | 31264 | 6.6 / 82 | +| 25 | Vanilla | 24.93 | 37.09 | 20.0 | 4.04 GB | 305 % | 38 | 37.84 | 33467 | 6.1 / 91 | +| 50 | Horizon | 39.31 | 65.33 | 20.0 | 1.25 GB | 325 % | 115 | 112.25 | 64163 | 6.9 / 95 | +| 50 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 7.7 / 86 | +| 100 | Horizon | 52.7 | 85.73 | 18.97 | 1.36 GB | 328 % | 154 | 151.83 | 116161 | 13.4 / 79 | +| 100 | Vanilla | stopped by its watchdog (a 60 s tick) | | | | | | | | 10.0 / 72 | + +Vanilla's watchdog stopped it after a 60-second tick in three runs (walk 100, explore 50 and 100). Each time its +server thread was in entity tracking (`ChunkMap$TrackedEntity.updatePlayer`). + +## What it shows + +- **Same work, 1 to 50 players:** Horizon's mean tick is 44–81 % shorter than vanilla's, its 95th percentile is + lower, and its process uses 32–63 % of vanilla's CPU. +- **Walking, 1 to 50 players:** Horizon's mean tick is shorter at every count (4.0 against 18.2 ms with 1 bot, + 22.7 against 34.3 ms with 50). +- **Where vanilla wins:** + - With 25 and 50 walking bots, vanilla's 95th percentile is lower (28.2 against 31.1 ms, 55.6 against + 60.2 ms). Horizon's slow ticks are spikier. + - In the full-speed explore pass, vanilla's mean tick is shorter with 10 and 25 bots (16.9 against 21.3 ms, + 24.9 against 25.8 ms), while Horizon sends 1.6–1.8 times as many new chunks. + - With 50 walking bots, Horizon makes the server machine busier (load 14.7 against 9.5). Its connection + writer threads compress every packet (below). +- **100 players:** Horizon keeps 15.8 TPS walking and 19.0 TPS exploring at full speed. Vanilla's watchdog + stopped it in both. +- **Memory:** Horizon used 0.76–0.92 GB in every walk and equal-work run, and 1.36 GB at most when 100 bots + explored at full speed. Vanilla used 3.4–4.0 GB with its 4 GB heap. +- **Start:** Horizon's fresh world was ready in 9.2–9.9 s, vanilla's in 14.9–17.2 s. + +## Where Horizon's time goes (50 walking bots) + +`perf record -e cycles:u --call-graph lbr` on the engine for 30 s, during a separate 50-bot `walk` run on the same +build and machine (MSPT 21.7 ms, 178 % CPU). Shares of all the engine's CPU samples: + +| Thread | Share | Mostly | +|---|---:|---| +| Connection writers (`horizon-lan-out`) | 55 % | 53 % in `miniz_oxide` deflate, from `horizon_protocol::frame::encode` | +| World generation workers | 33 % | noise, surface rules, aquifers | +| Server thread (the tick) | 12 % | see below | + +Inside the tick: +- the locator bar (`Waypoints::tick`): a third of the tick; +- `Hub::tick`: a quarter; +- block entities, creatures, chunk encoding (`ChunkEncoder::encode_in`) and `Streaming::update`: 7–10 % each; +- SipHash of `u128` keys (the default `HashMap` hasher): about 10 % of the tick. + +**The next biggest cost is compressing packets.** Every chunk packet is compressed again for each player who gets +it, with `flate2`'s default `miniz_oxide` backend at level 6. On this 4-thread CPU that competes with the tick +and with world generation. Two fixes, which can be combined: +- the `zlib-rs` backend for `flate2`: 2.2–10 times faster than `miniz_oxide` at level 6 in a quick test, with + output about 3 % larger; +- compressing a chunk packet once and sending the same bytes to every player who needs it. + +## Before and after the performance PRs + +The earlier run, on `main` at `002f14ce` with #670's bench changes (build `a9ee56a8`), before #586, #701–#707 and +#713. Same machines and settings. MSPT mean / P95, in ms: + +Walk: + +| Bots | Horizon before | Horizon now | Vanilla before | Vanilla now | +|---:|---|---|---|---| +| 1 | 5.77 / 11.04 | 4.01 / 8.19 | 18.84 / 29.55 | 18.22 / 29.34 | +| 10 | 16.23 / 29.32 | 8.79 / 17.35 | 18.02 / 37.62 | 18.67 / 38.26 | +| 25 | 23.98 / 49.18 | 15.01 / 31.12 | 19.19 / 33.84 | 18.78 / 28.16 | +| 50 | 35.07 / 73.24 | 22.72 / 60.19 | 35.23 / 60.87 | 34.3 / 55.55 | +| 100 | 104.8 / 158.8 | 63.33 / 125.04 | watchdog | watchdog | + +Equal work: + +| Bots | Horizon before | Horizon now | Vanilla before | Vanilla now | +|---:|---|---|---|---| +| 1 | 4.78 / 7.3 | 3.16 / 5.78 | 16.63 / 26.23 | 16.82 / 27.3 | +| 10 | 15.19 / 25.66 | 9.83 / 19.01 | 24.65 / 40.81 | 24.38 / 39.58 | +| 25 | 23.37 / 42.59 | 16.87 / 30.88 | 30.28 / 44.81 | 30.29 / 43.47 | +| 50 | 30.59 / 67.94 | 23.57 / 47.53 | 43.52 / 56.18 | 42.44 / 54.84 | + +Vanilla's numbers repeat within a few percent, so the runs are comparable. In the earlier run, 25 walking bots +were faster on vanilla (19.2 against 24.0 ms). A profile then put a third of the tick in advancement updates, +which #701 fixed. + +## Files + +- `walk-explore.json`: the `walk` and full-speed `explore` passes. `explore-equal-rate.json`: the equal-work pass. +- `load.txt`: both machines' load averages every 30 s during the runs. +- `earlier-002f14ce/`: the same files for the earlier run. +- The server's tailnet address is replaced by `` in the JSON. diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json b/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json new file mode 100644 index 000000000..404f8d032 --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/explore-equal-rate.json @@ -0,0 +1,341 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T15:37:03+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "a9ee56a8b143999c9bc7056850ffcd622a9214aa", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/explore-equal-rate.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 4.78, + "p50": 4.59, + "p95": 7.3, + "p99": 13.53 + }, + "mspt_worst_p99": 36.5, + "tps": 20.0, + "rss_mb": { + "mean": 759.91, + "max": 771.3 + }, + "cpu_percent": 24.49, + "chunks_per_second": 1.64, + "unique_per_second": 1.27, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 841, + "chunks_per_bot": { + "explore": 841.0 + }, + "unique_chunks_per_bot": { + "explore": 781.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 14.35, + "mspt": { + "average": 16.63, + "p50": 16.73, + "p95": 26.23, + "p99": 35.39 + }, + "mspt_worst_p99": 68.5, + "tps": 20.0, + "rss_mb": { + "mean": 3431.12, + "max": 3459.2 + }, + "cpu_percent": 69.76, + "chunks_per_second": 1.66, + "unique_per_second": 1.37, + "forgotten_per_second": 1.67, + "waited_ticks_per_second": 0.0, + "chunks_total": 840, + "chunks_per_bot": { + "explore": 840.0 + }, + "unique_chunks_per_bot": { + "explore": 780.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 15.19, + "p50": 14.45, + "p95": 25.66, + "p99": 38.89 + }, + "mspt_worst_p99": 57.6, + "tps": 20.0, + "rss_mb": { + "mean": 859.86, + "max": 920.2 + }, + "cpu_percent": 84.95, + "chunks_per_second": 14.22, + "unique_per_second": 12.7, + "forgotten_per_second": 14.11, + "waited_ticks_per_second": 0.0, + "chunks_total": 7962, + "chunks_per_bot": { + "explore": 796.2 + }, + "unique_chunks_per_bot": { + "explore": 768.2 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 14.74, + "mspt": { + "average": 24.65, + "p50": 21.82, + "p95": 40.81, + "p99": 70.23 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 3528.77, + "max": 3643.2 + }, + "cpu_percent": 133.1, + "chunks_per_second": 13.62, + "unique_per_second": 12.32, + "forgotten_per_second": 13.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 7746, + "chunks_per_bot": { + "explore": 774.6 + }, + "unique_chunks_per_bot": { + "explore": 748.7 + }, + "resent": 0, + "pulled_back": 1150, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.42, + "mspt": { + "average": 23.37, + "p50": 21.61, + "p95": 42.59, + "p99": 60.21 + }, + "mspt_worst_p99": 102.1, + "tps": 20.0, + "rss_mb": { + "mean": 889.21, + "max": 950.7 + }, + "cpu_percent": 117.59, + "chunks_per_second": 35.34, + "unique_per_second": 31.62, + "forgotten_per_second": 35.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 20137, + "chunks_per_bot": { + "explore": 805.48 + }, + "unique_chunks_per_bot": { + "explore": 774.52 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 15.14, + "mspt": { + "average": 30.28, + "p50": 28.17, + "p95": 44.81, + "p99": 71.77 + }, + "mspt_worst_p99": 158.1, + "tps": 20.0, + "rss_mb": { + "mean": 3574.32, + "max": 3692.7 + }, + "cpu_percent": 173.43, + "chunks_per_second": 32.76, + "unique_per_second": 29.38, + "forgotten_per_second": 33.02, + "waited_ticks_per_second": 0.0, + "chunks_total": 19417, + "chunks_per_bot": { + "explore": 776.68 + }, + "unique_chunks_per_bot": { + "explore": 747.36 + }, + "resent": 0, + "pulled_back": 4728, + "moved_too_quickly": 15, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.11, + "mspt": { + "average": 30.59, + "p50": 25.19, + "p95": 67.94, + "p99": 90.77 + }, + "mspt_worst_p99": 122.1, + "tps": 20.0, + "rss_mb": { + "mean": 915.93, + "max": 978.0 + }, + "cpu_percent": 132.13, + "chunks_per_second": 71.31, + "unique_per_second": 63.56, + "forgotten_per_second": 71.19, + "waited_ticks_per_second": 0.0, + "chunks_total": 41365, + "chunks_per_bot": { + "explore": 827.3 + }, + "unique_chunks_per_bot": { + "explore": 793.14 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.35, + "mspt": { + "average": 43.52, + "p50": 41.69, + "p95": 56.18, + "p99": 84.55 + }, + "mspt_worst_p99": 155.1, + "tps": 20.0, + "rss_mb": { + "mean": 3801.29, + "max": 3920.7 + }, + "cpu_percent": 198.97, + "chunks_per_second": 65.86, + "unique_per_second": 58.63, + "forgotten_per_second": 66.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 39790, + "chunks_per_bot": { + "explore": 795.8 + }, + "unique_chunks_per_bot": { + "explore": 764.48 + }, + "resent": 0, + "pulled_back": 8392, + "moved_too_quickly": 38, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + } + ] +} diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt b/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt new file mode 100644 index 000000000..853252809 --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/load.txt @@ -0,0 +1,278 @@ +2026-10-17T13:17:13Z thinkpad: 2.76 2.26 2.04 | macmini (bots): { 73.08 70.73 75.98 } +2026-10-17T13:17:43Z thinkpad: 2.90 2.33 2.07 | macmini (bots): { 75.66 71.62 76.12 } +2026-10-17T13:18:13Z thinkpad: 3.02 2.43 2.11 | macmini (bots): { 65.77 69.61 75.24 } +2026-10-17T13:18:44Z thinkpad: 2.15 2.27 2.07 | macmini (bots): { 59.85 67.75 74.37 } +2026-10-17T13:19:14Z thinkpad: 1.45 2.09 2.02 | macmini (bots): { 63.86 67.87 74.17 } +2026-10-17T13:19:44Z thinkpad: 1.28 1.98 1.98 | macmini (bots): { 63.51 67.54 73.84 } +2026-10-17T13:20:14Z thinkpad: 1.14 1.89 1.95 | macmini (bots): { 65.82 67.85 73.71 } +2026-10-17T13:20:45Z thinkpad: 0.90 1.77 1.91 | macmini (bots): { 63.62 67.08 73.22 } +2026-10-17T13:21:15Z thinkpad: 0.55 1.60 1.85 | macmini (bots): { 62.45 66.37 72.75 } +2026-10-17T13:21:45Z thinkpad: 0.79 1.54 1.82 | macmini (bots): { 67.04 67.04 72.76 } +2026-10-17T13:22:15Z thinkpad: 1.96 1.75 1.88 | macmini (bots): { 65.53 66.60 72.40 } +2026-10-17T13:22:46Z thinkpad: 1.82 1.75 1.88 | macmini (bots): { 61.52 65.55 71.82 } +2026-10-17T13:23:16Z thinkpad: 1.29 1.63 1.83 | macmini (bots): { 62.36 65.36 71.53 } +2026-10-17T13:23:46Z thinkpad: 0.86 1.49 1.78 | macmini (bots): { 68.76 66.51 71.73 } +2026-10-17T13:24:16Z thinkpad: 1.29 1.52 1.78 | macmini (bots): { 77.68 68.77 72.36 } +2026-10-17T13:24:46Z thinkpad: 1.82 1.62 1.80 | macmini (bots): { 74.03 68.88 72.28 } +2026-10-17T13:25:17Z thinkpad: 1.50 1.56 1.78 | macmini (bots): { 71.53 68.76 72.12 } +2026-10-17T13:25:47Z thinkpad: 0.96 1.42 1.72 | macmini (bots): { 74.46 69.85 72.40 } +2026-10-17T13:26:17Z thinkpad: 0.87 1.35 1.69 | macmini (bots): { 80.85 71.79 73.01 } +2026-10-17T13:26:47Z thinkpad: 3.95 2.02 1.90 | macmini (bots): { 74.77 71.31 72.81 } +2026-10-17T13:27:18Z thinkpad: 2.98 1.97 1.89 | macmini (bots): { 70.52 70.52 72.46 } +2026-10-17T13:27:48Z thinkpad: 3.78 2.26 1.99 | macmini (bots): { 67.62 69.91 72.18 } +2026-10-17T13:28:18Z thinkpad: 3.05 2.23 1.99 | macmini (bots): { 72.51 70.83 72.43 } +2026-10-17T13:28:48Z thinkpad: 2.05 2.07 1.94 | macmini (bots): { 79.07 72.64 73.03 } +2026-10-17T13:29:19Z thinkpad: 2.09 2.11 1.96 | macmini (bots): { 90.42 75.94 74.21 } +2026-10-17T13:29:49Z thinkpad: 1.61 1.99 1.93 | macmini (bots): { 102.68 80.15 75.78 } +2026-10-17T13:30:19Z thinkpad: 2.31 2.12 1.97 | macmini (bots): { 111.15 84.19 77.39 } +2026-10-17T13:30:49Z thinkpad: 4.14 2.61 2.14 | macmini (bots): { 115.67 87.82 78.94 } +2026-10-17T13:31:20Z thinkpad: 4.84 2.92 2.26 | macmini (bots): { 122.95 92.31 80.88 } +2026-10-17T13:31:50Z thinkpad: 6.84 3.60 2.51 | macmini (bots): { 136.25 98.41 83.48 } +2026-10-17T13:32:20Z thinkpad: 4.85 3.43 2.49 | macmini (bots): { 128.59 100.39 84.73 } +2026-10-17T13:32:50Z thinkpad: 3.48 3.25 2.46 | macmini (bots): { 111.05 98.73 84.66 } +2026-10-17T13:33:20Z thinkpad: 3.09 3.15 2.45 | macmini (bots): { 102.40 98.03 84.98 } +2026-10-17T13:33:51Z thinkpad: 2.47 2.99 2.42 | macmini (bots): { 94.57 96.54 84.89 } +2026-10-17T13:34:21Z thinkpad: 2.42 2.94 2.42 | macmini (bots): { 86.26 94.36 84.50 } +2026-10-17T13:34:51Z thinkpad: 2.95 3.04 2.47 | macmini (bots): { 76.90 91.56 83.84 } +2026-10-17T13:35:21Z thinkpad: 2.66 2.96 2.46 | macmini (bots): { 65.57 87.42 82.61 } +2026-10-17T13:35:52Z thinkpad: 2.47 2.88 2.45 | macmini (bots): { 64.13 85.05 81.92 } +2026-10-17T13:36:22Z thinkpad: 3.89 3.17 2.56 | macmini (bots): { 58.65 81.74 80.83 } +2026-10-17T13:36:52Z thinkpad: 6.43 3.83 2.80 | macmini (bots): { 66.32 81.32 80.71 } +2026-10-17T13:37:22Z thinkpad: 8.73 4.60 3.09 | macmini (bots): { 67.30 80.14 80.30 } +2026-10-17T13:37:53Z thinkpad: 9.03 5.10 3.30 | macmini (bots): { 63.66 78.24 79.62 } +2026-10-17T13:38:23Z thinkpad: 9.49 5.57 3.52 | macmini (bots): { 61.25 76.23 78.84 } +2026-10-17T13:38:53Z thinkpad: 7.55 5.50 3.56 | macmini (bots): { 62.30 74.88 78.25 } +2026-10-17T13:39:23Z thinkpad: 8.62 5.99 3.79 | macmini (bots): { 57.34 72.56 77.29 } +2026-10-17T13:39:53Z thinkpad: 6.65 5.81 3.80 | macmini (bots): { 51.24 69.62 76.06 } +2026-10-17T13:40:24Z thinkpad: 5.55 5.62 3.80 | macmini (bots): { 48.87 67.26 74.98 } +2026-10-17T13:40:54Z thinkpad: 6.11 5.71 3.89 | macmini (bots): { 51.16 66.08 74.29 } +2026-10-17T13:41:24Z thinkpad: 8.93 6.43 4.19 | macmini (bots): { 48.67 64.00 73.24 } +2026-10-17T13:41:54Z thinkpad: 9.05 6.74 4.36 | macmini (bots): { 46.47 61.96 72.18 } +2026-10-17T13:42:25Z thinkpad: 7.70 6.65 4.41 | macmini (bots): { 44.24 60.05 71.14 } +2026-10-17T13:42:55Z thinkpad: 5.64 6.24 4.34 | macmini (bots): { 49.30 59.83 70.68 } +2026-10-17T13:43:25Z thinkpad: 4.83 6.02 4.33 | macmini (bots): { 47.39 58.24 69.72 } +2026-10-17T13:43:55Z thinkpad: 3.57 5.61 4.25 | macmini (bots): { 47.32 57.23 68.96 } +2026-10-17T13:44:25Z thinkpad: 3.41 5.40 4.23 | macmini (bots): { 47.86 56.49 68.28 } +2026-10-17T13:44:55Z thinkpad: 3.37 5.21 4.20 | macmini (bots): { 50.10 56.19 67.77 } +2026-10-17T13:45:26Z thinkpad: 3.78 5.16 4.22 | macmini (bots): { 51.91 55.98 67.28 } +2026-10-17T13:45:56Z thinkpad: 4.34 5.12 4.23 | macmini (bots): { 49.16 54.85 66.42 } +2026-10-17T13:46:26Z thinkpad: 10.04 6.46 4.71 | macmini (bots): { 45.01 53.33 65.47 } +2026-10-17T13:46:56Z thinkpad: 18.10 8.73 5.52 | macmini (bots): { 46.41 52.87 64.88 } +2026-10-17T13:47:27Z thinkpad: 14.99 8.91 5.68 | macmini (bots): { 51.12 53.21 64.57 } +2026-10-17T13:47:57Z thinkpad: 13.46 9.27 5.92 | macmini (bots): { 53.84 53.81 64.40 } +2026-10-17T13:48:27Z thinkpad: 12.76 9.41 6.07 | macmini (bots): { 51.94 53.27 63.84 } +2026-10-17T13:48:58Z thinkpad: 10.20 9.11 6.08 | macmini (bots): { 50.70 52.83 63.31 } +2026-10-17T13:49:28Z thinkpad: 9.95 9.25 6.23 | macmini (bots): { 51.51 52.89 62.97 } +2026-10-17T13:49:58Z thinkpad: 11.98 9.87 6.53 | macmini (bots): { 50.98 52.73 62.57 } +2026-10-17T13:50:29Z thinkpad: 14.96 10.76 6.94 | macmini (bots): { 49.68 52.31 62.08 } +2026-10-17T13:50:59Z thinkpad: 10.54 10.09 6.83 | macmini (bots): { 53.34 53.01 62.00 } +2026-10-17T13:51:29Z thinkpad: 10.21 10.01 6.91 | macmini (bots): { 51.61 52.69 61.57 } +2026-10-17T13:52:00Z thinkpad: 11.86 10.42 7.14 | macmini (bots): { 48.94 51.89 60.97 } +2026-10-17T13:52:30Z thinkpad: 10.88 10.33 7.22 | macmini (bots): { 48.46 51.44 60.49 } +2026-10-17T13:53:01Z thinkpad: 10.94 10.41 7.35 | macmini (bots): { 54.27 52.41 60.47 } +2026-10-17T13:53:31Z thinkpad: 10.77 10.42 7.45 | macmini (bots): { 57.13 53.30 60.51 } +2026-10-17T13:54:02Z thinkpad: 10.62 10.40 7.53 | macmini (bots): { 53.78 52.84 60.09 } +2026-10-17T13:54:32Z thinkpad: 10.85 10.48 7.66 | macmini (bots): { 52.01 52.51 59.73 } +2026-10-17T13:55:02Z thinkpad: 10.36 10.39 7.73 | macmini (bots): { 53.44 52.83 59.59 } +2026-10-17T13:55:32Z thinkpad: 8.58 9.95 7.67 | macmini (bots): { 58.66 54.12 59.82 } +2026-10-17T13:56:03Z thinkpad: 7.29 9.52 7.60 | macmini (bots): { 60.98 55.05 59.96 } +2026-10-17T13:56:33Z thinkpad: 5.02 8.75 7.40 | macmini (bots): { 65.14 56.71 60.39 } +2026-10-17T13:57:03Z thinkpad: 5.03 8.38 7.32 | macmini (bots): { 57.51 55.73 59.91 } +2026-10-17T13:57:34Z thinkpad: 7.39 8.66 7.45 | macmini (bots): { 52.57 54.73 59.41 } +2026-10-17T13:58:04Z thinkpad: 10.56 9.45 7.76 | macmini (bots): { 53.11 54.60 59.20 } +2026-10-17T13:58:34Z thinkpad: 28.87 14.20 9.41 | macmini (bots): { 54.53 54.93 59.16 } +2026-10-17T13:59:05Z thinkpad: 39.33 17.79 10.73 | macmini (bots): { 62.67 56.86 59.71 } +2026-10-17T13:59:35Z thinkpad: 34.07 18.33 11.12 | macmini (bots): { 61.78 57.22 59.75 } +2026-10-17T14:00:06Z thinkpad: 34.42 19.72 11.80 | macmini (bots): { 53.10 55.55 59.03 } +2026-10-17T14:00:36Z thinkpad: 33.60 20.94 12.46 | macmini (bots): { 48.70 54.23 58.43 } +2026-10-17T14:01:07Z thinkpad: 29.29 20.99 12.74 | macmini (bots): { 50.25 54.00 58.20 } +2026-10-17T14:01:37Z thinkpad: 20.83 19.79 12.61 | macmini (bots): { 50.48 53.74 57.96 } +2026-10-17T14:02:08Z thinkpad: 21.74 20.44 13.11 | macmini (bots): { 48.65 53.04 57.56 } +2026-10-17T14:02:38Z thinkpad: 17.68 19.67 13.09 | macmini (bots): { 54.17 53.85 57.69 } +2026-10-17T14:03:08Z thinkpad: 13.97 18.55 12.93 | macmini (bots): { 53.39 53.84 57.56 } +2026-10-17T14:03:39Z thinkpad: 14.10 18.17 12.98 | macmini (bots): { 50.71 53.09 57.16 } +2026-10-17T14:04:09Z thinkpad: 13.60 17.65 12.97 | macmini (bots): { 52.30 53.28 57.08 } +2026-10-17T14:04:39Z thinkpad: 12.09 16.91 12.88 | macmini (bots): { 51.52 53.03 56.87 } +2026-10-17T14:05:10Z thinkpad: 10.15 15.98 12.69 | macmini (bots): { 54.53 53.57 56.91 } +2026-10-17T14:05:42Z thinkpad: 7.77 14.86 12.42 | macmini (bots): { 63.58 55.55 57.49 } +2026-10-17T14:06:12Z thinkpad: 6.58 13.89 12.18 | macmini (bots): { 75.29 59.41 58.84 } +2026-10-17T14:06:42Z thinkpad: 5.96 13.02 11.94 | macmini (bots): { 78.06 61.64 59.67 } +2026-10-17T14:07:12Z thinkpad: 4.86 12.08 11.66 | macmini (bots): { 72.26 61.85 59.81 } +2026-10-17T14:07:42Z thinkpad: 4.49 11.18 11.38 | macmini (bots): { 67.84 61.73 59.84 } +2026-10-17T14:08:13Z thinkpad: 4.37 10.51 11.15 | macmini (bots): { 64.25 61.45 59.80 } +2026-10-17T14:08:43Z thinkpad: 4.57 9.97 10.94 | macmini (bots): { 57.86 60.14 59.38 } +2026-10-17T14:09:13Z thinkpad: 4.60 9.46 10.74 | macmini (bots): { 60.21 60.39 59.49 } +2026-10-17T14:09:43Z thinkpad: 4.20 8.89 10.51 | macmini (bots): { 57.11 59.57 59.22 } +2026-10-17T14:10:14Z thinkpad: 3.80 8.36 10.28 | macmini (bots): { 66.05 61.48 59.92 } +2026-10-17T14:10:44Z thinkpad: 4.19 8.00 10.10 | macmini (bots): { 78.51 64.91 61.22 } +2026-10-17T14:11:14Z thinkpad: 4.27 7.65 9.92 | macmini (bots): { 74.15 65.33 61.51 } +2026-10-17T14:11:44Z thinkpad: 4.35 7.35 9.74 | macmini (bots): { 62.47 63.48 60.98 } +2026-10-17T14:12:14Z thinkpad: 4.98 7.22 9.62 | macmini (bots): { 56.73 61.86 60.46 } +2026-10-17T14:12:45Z thinkpad: 4.60 6.91 9.44 | macmini (bots): { 57.78 61.49 60.37 } +2026-10-17T14:13:15Z thinkpad: 4.15 6.57 9.25 | macmini (bots): { 56.21 60.71 60.12 } +2026-10-17T14:13:45Z thinkpad: 3.87 6.25 9.05 | macmini (bots): { 54.75 60.00 59.89 } +2026-10-17T14:14:15Z thinkpad: 3.86 6.02 8.89 | macmini (bots): { 52.21 58.88 59.49 } +2026-10-17T14:14:46Z thinkpad: 3.14 5.64 8.67 | macmini (bots): { 58.81 59.59 59.71 } +2026-10-17T14:15:16Z thinkpad: 3.76 5.54 8.54 | macmini (bots): { 64.13 60.86 60.16 } +2026-10-17T14:15:46Z thinkpad: 3.91 5.41 8.40 | macmini (bots): { 59.02 59.97 59.87 } +2026-10-17T14:16:16Z thinkpad: 4.33 5.35 8.28 | macmini (bots): { 64.48 60.97 60.22 } +2026-10-17T14:16:46Z thinkpad: 5.20 5.44 8.21 | macmini (bots): { 79.56 64.98 61.70 } +2026-10-17T14:17:17Z thinkpad: 4.88 5.36 8.10 | macmini (bots): { 94.21 69.99 63.63 } +2026-10-17T14:17:47Z thinkpad: 4.80 5.30 8.00 | macmini (bots): { 85.75 70.51 64.08 } +2026-10-17T14:18:17Z thinkpad: 4.82 5.25 7.89 | macmini (bots): { 82.33 71.25 64.57 } +2026-10-17T14:18:48Z thinkpad: 4.50 5.12 7.75 | macmini (bots): { 77.67 71.11 64.75 } +2026-10-17T14:19:18Z thinkpad: 3.76 4.88 7.58 | macmini (bots): { 77.29 71.67 65.17 } +2026-10-17T14:19:48Z thinkpad: 3.68 4.75 7.45 | macmini (bots): { 71.16 70.71 65.05 } +2026-10-17T14:20:18Z thinkpad: 4.25 4.82 7.39 | macmini (bots): { 66.97 69.63 64.85 } +2026-10-17T14:20:49Z thinkpad: 4.72 4.89 7.33 | macmini (bots): { 59.23 67.50 64.24 } +2026-10-17T14:21:19Z thinkpad: 5.12 4.98 7.28 | macmini (bots): { 52.38 65.10 63.48 } +2026-10-17T14:21:49Z thinkpad: 5.69 5.13 7.26 | macmini (bots): { 59.43 65.53 63.69 } +2026-10-17T14:22:19Z thinkpad: 5.78 5.19 7.21 | macmini (bots): { 62.28 65.65 63.80 } +2026-10-17T14:22:50Z thinkpad: 5.34 5.14 7.13 | macmini (bots): { 57.40 64.12 63.30 } +2026-10-17T14:23:20Z thinkpad: 4.89 5.04 7.03 | macmini (bots): { 58.39 63.61 63.14 } +2026-10-17T14:23:50Z thinkpad: 5.00 5.07 6.98 | macmini (bots): { 64.88 64.63 63.52 } +2026-10-17T14:24:20Z thinkpad: 3.88 4.80 6.83 | macmini (bots): { 80.70 68.30 64.88 } +2026-10-17T14:24:51Z thinkpad: 2.90 4.47 6.65 | macmini (bots): { 94.09 72.75 66.61 } +2026-10-17T14:25:21Z thinkpad: 2.63 4.25 6.51 | macmini (bots): { 93.13 74.91 67.63 } +2026-10-17T14:25:51Z thinkpad: 6.66 5.07 6.71 | macmini (bots): { 72.87 71.72 66.72 } +2026-10-17T14:26:21Z thinkpad: 7.15 5.34 6.74 | macmini (bots): { 67.03 70.37 66.40 } +2026-10-17T14:26:51Z thinkpad: 6.20 5.29 6.68 | macmini (bots): { 58.68 68.08 65.71 } +2026-10-17T14:27:22Z thinkpad: 6.11 5.35 6.66 | macmini (bots): { 55.26 66.28 65.14 } +2026-10-17T14:27:52Z thinkpad: 5.45 5.26 6.59 | macmini (bots): { 56.51 65.74 64.99 } +2026-10-17T14:28:22Z thinkpad: 6.11 5.45 6.61 | macmini (bots): { 52.24 63.77 64.30 } +2026-10-17T14:28:52Z thinkpad: 6.06 5.50 6.59 | macmini (bots): { 55.56 63.38 64.13 } +2026-10-17T14:29:23Z thinkpad: 6.11 5.58 6.58 | macmini (bots): { 59.66 63.63 64.20 } +2026-10-17T14:29:53Z thinkpad: 5.52 5.54 6.53 | macmini (bots): { 63.71 64.30 64.42 } +2026-10-17T14:30:23Z thinkpad: 4.79 5.35 6.43 | macmini (bots): { 69.84 65.61 64.89 } +2026-10-17T14:30:53Z thinkpad: 6.21 5.63 6.49 | macmini (bots): { 62.76 64.46 64.50 } +2026-10-17T14:31:23Z thinkpad: 8.36 6.21 6.66 | macmini (bots): { 53.51 62.09 63.64 } +2026-10-17T14:31:54Z thinkpad: 8.49 6.45 6.72 | macmini (bots): { 52.80 60.98 63.18 } +2026-10-17T14:32:24Z thinkpad: 8.28 6.59 6.77 | macmini (bots): { 48.98 59.20 62.45 } +2026-10-17T14:32:54Z thinkpad: 8.02 6.70 6.79 | macmini (bots): { 48.95 58.30 62.02 } +2026-10-17T14:33:25Z thinkpad: 7.02 6.59 6.76 | macmini (bots): { 51.06 57.70 61.66 } +2026-10-17T14:33:55Z thinkpad: 7.09 6.62 6.76 | macmini (bots): { 70.89 61.81 63.00 } +2026-10-17T14:34:25Z thinkpad: 6.18 6.44 6.69 | macmini (bots): { 69.38 62.46 63.21 } +2026-10-17T14:34:55Z thinkpad: 6.67 6.52 6.72 | macmini (bots): { 76.87 64.84 64.04 } +2026-10-17T14:35:25Z thinkpad: 4.76 6.08 6.56 | macmini (bots): { 86.19 68.04 65.21 } +2026-10-17T14:35:56Z thinkpad: 3.47 5.64 6.40 | macmini (bots): { 101.03 73.28 67.21 } +2026-10-17T14:36:26Z thinkpad: 2.68 5.24 6.24 | macmini (bots): { 106.05 77.09 68.79 } +2026-10-17T14:36:56Z thinkpad: 2.41 4.91 6.10 | macmini (bots): { 107.57 80.20 70.20 } +2026-10-17T14:37:26Z thinkpad: 3.74 4.99 6.08 | macmini (bots): { 101.16 81.38 70.98 } +2026-10-17T14:37:57Z thinkpad: 5.96 5.39 6.18 | macmini (bots): { 86.51 79.61 70.70 } +2026-10-17T14:38:27Z thinkpad: 7.91 5.98 6.35 | macmini (bots): { 81.13 79.06 70.81 } +2026-10-17T14:38:57Z thinkpad: 8.45 6.25 6.43 | macmini (bots): { 79.56 79.01 71.08 } +2026-10-17T14:39:27Z thinkpad: 8.75 6.52 6.52 | macmini (bots): { 71.92 77.22 70.71 } +2026-10-17T14:39:58Z thinkpad: 8.86 6.76 6.60 | macmini (bots): { 71.38 76.58 70.70 } +2026-10-17T14:40:28Z thinkpad: 8.74 6.98 6.68 | macmini (bots): { 71.25 76.12 70.74 } +2026-10-17T14:40:58Z thinkpad: 7.99 6.96 6.68 | macmini (bots): { 70.49 75.51 70.71 } +2026-10-17T14:41:28Z thinkpad: 7.64 7.01 6.70 | macmini (bots): { 68.93 74.58 70.56 } +2026-10-17T14:41:59Z thinkpad: 6.57 6.84 6.66 | macmini (bots): { 68.35 73.75 70.39 } +2026-10-17T14:42:29Z thinkpad: 5.83 6.62 6.59 | macmini (bots): { 63.57 72.20 69.95 } +2026-10-17T14:42:59Z thinkpad: 7.40 6.91 6.69 | macmini (bots): { 56.77 69.69 69.12 } +2026-10-17T14:43:29Z thinkpad: 9.07 7.37 6.85 | macmini (bots): { 49.53 66.71 68.06 } +2026-10-17T14:44:00Z thinkpad: 9.39 7.63 6.96 | macmini (bots): { 43.53 63.68 66.91 } +2026-10-17T14:44:30Z thinkpad: 9.16 7.73 7.01 | macmini (bots): { 41.12 61.23 65.92 } +2026-10-17T14:45:00Z thinkpad: 7.96 7.57 6.98 | macmini (bots): { 40.62 59.23 65.03 } +2026-10-17T14:45:30Z thinkpad: 6.34 7.24 6.89 | macmini (bots): { 38.17 56.80 63.94 } +2026-10-17T14:46:01Z thinkpad: 6.39 7.18 6.88 | macmini (bots): { 40.35 55.54 63.24 } +2026-10-17T14:46:31Z thinkpad: 5.63 6.95 6.82 | macmini (bots): { 48.66 56.25 63.24 } +2026-10-17T14:47:01Z thinkpad: 4.73 6.60 6.70 | macmini (bots): { 46.68 55.20 62.62 } +2026-10-17T14:47:31Z thinkpad: 9.18 7.55 7.02 | macmini (bots): { 41.45 53.19 61.64 } +2026-10-17T14:48:01Z thinkpad: 10.40 8.02 7.19 | macmini (bots): { 40.76 51.87 60.87 } +2026-10-17T14:48:32Z thinkpad: 8.24 7.73 7.12 | macmini (bots): { 44.46 51.67 60.48 } +2026-10-17T14:49:02Z thinkpad: 9.60 8.09 7.26 | macmini (bots): { 38.75 49.66 59.45 } +2026-10-17T14:49:32Z thinkpad: 8.90 8.10 7.29 | macmini (bots): { 34.93 47.72 58.41 } +2026-10-17T14:50:02Z thinkpad: 11.17 8.66 7.50 | macmini (bots): { 35.70 46.68 57.66 } +2026-10-17T14:50:33Z thinkpad: 12.06 9.19 7.72 | macmini (bots): { 43.94 47.43 57.54 } +2026-10-17T14:51:03Z thinkpad: 12.50 9.49 7.87 | macmini (bots): { 40.76 46.36 56.80 } +2026-10-17T14:51:33Z thinkpad: 10.35 9.24 7.83 | macmini (bots): { 44.81 46.69 56.55 } +2026-10-17T14:52:03Z thinkpad: 9.32 9.09 7.83 | macmini (bots): { 54.94 48.97 57.04 } +2026-10-17T14:52:34Z thinkpad: 7.07 8.58 7.70 | macmini (bots): { 54.59 49.54 56.92 } +2026-10-17T14:53:04Z thinkpad: 5.33 8.01 7.54 | macmini (bots): { 67.48 53.27 58.02 } +2026-10-17T14:53:34Z thinkpad: 7.22 8.20 7.62 | macmini (bots): { 57.82 52.33 57.52 } +2026-10-17T14:54:04Z thinkpad: 9.69 8.73 7.81 | macmini (bots): { 46.67 50.20 56.57 } +2026-10-17T14:54:35Z thinkpad: 9.14 8.66 7.82 | macmini (bots): { 49.88 50.61 56.49 } +2026-10-17T14:55:05Z thinkpad: 9.75 8.87 7.91 | macmini (bots): { 46.88 49.95 56.06 } +2026-10-17T14:55:35Z thinkpad: 8.51 8.67 7.88 | macmini (bots): { 42.90 48.80 55.43 } +2026-10-17T14:56:06Z thinkpad: 8.46 8.62 7.89 | macmini (bots): { 49.23 49.72 55.53 } +2026-10-17T14:56:36Z thinkpad: 6.19 8.07 7.73 | macmini (bots): { 54.41 50.86 55.74 } +2026-10-17T14:57:06Z thinkpad: 4.69 7.53 7.56 | macmini (bots): { 60.26 52.69 56.24 } +2026-10-17T14:57:36Z thinkpad: 3.21 6.90 7.35 | macmini (bots): { 67.66 55.21 57.03 } +2026-10-17T14:58:06Z thinkpad: 1.94 6.24 7.11 | macmini (bots): { 75.73 58.41 58.13 } +2026-10-17T14:58:37Z thinkpad: 1.18 5.64 6.89 | macmini (bots): { 74.69 59.90 58.68 } +2026-10-17T14:59:07Z thinkpad: 0.78 5.12 6.67 | macmini (bots): { 77.10 61.82 59.42 } +2026-10-17T14:59:37Z thinkpad: 0.88 4.72 6.49 | macmini (bots): { 87.05 65.59 60.86 } +2026-10-17T15:00:07Z thinkpad: 0.53 4.27 6.28 | macmini (bots): { 78.18 65.51 60.99 } +2026-10-17T15:00:38Z thinkpad: 0.38 3.88 6.09 | macmini (bots): { 79.38 67.00 61.69 } +2026-10-17T15:01:08Z thinkpad: 1.50 3.80 5.99 | macmini (bots): { 78.36 67.86 62.18 } +2026-10-17T15:01:38Z thinkpad: 2.97 3.93 5.95 | macmini (bots): { 74.18 67.90 62.39 } +2026-10-17T15:02:08Z thinkpad: 2.61 3.77 5.83 | macmini (bots): { 68.63 67.00 62.25 } +2026-10-17T15:02:39Z thinkpad: 2.10 3.55 5.69 | macmini (bots): { 69.84 67.50 62.60 } +2026-10-17T15:03:09Z thinkpad: 1.44 3.25 5.53 | macmini (bots): { 67.10 67.06 62.61 } +2026-10-17T15:03:39Z thinkpad: 1.39 3.08 5.40 | macmini (bots): { 60.83 65.50 62.19 } +2026-10-17T15:04:09Z thinkpad: 1.28 2.88 5.26 | macmini (bots): { 75.40 68.61 63.46 } +2026-10-17T15:04:40Z thinkpad: 2.30 2.99 5.22 | macmini (bots): { 106.08 76.54 66.50 } +2026-10-17T15:05:10Z thinkpad: 2.65 3.02 5.15 | macmini (bots): { 111.96 81.09 68.52 } +2026-10-17T15:05:40Z thinkpad: 2.41 2.92 5.05 | macmini (bots): { 104.19 82.08 69.31 } +2026-10-17T15:06:10Z thinkpad: 2.71 2.95 4.99 | macmini (bots): { 116.20 87.04 71.54 } +2026-10-17T15:06:40Z thinkpad: 2.51 2.87 4.90 | macmini (bots): { 136.68 94.24 74.66 } +2026-10-17T15:07:11Z thinkpad: 3.68 3.11 4.91 | macmini (bots): { 132.76 97.43 76.50 } +2026-10-17T15:07:41Z thinkpad: 3.77 3.19 4.88 | macmini (bots): { 132.73 100.97 78.51 } +2026-10-17T15:08:11Z thinkpad: 3.00 3.06 4.79 | macmini (bots): { 116.92 100.33 79.07 } +2026-10-17T15:08:41Z thinkpad: 2.40 2.91 4.68 | macmini (bots): { 109.83 100.07 79.70 } +2026-10-17T15:09:12Z thinkpad: 2.18 2.81 4.59 | macmini (bots): { 113.21 101.71 81.00 } +2026-10-17T15:09:42Z thinkpad: 1.67 2.62 4.47 | macmini (bots): { 131.87 107.11 83.66 } +2026-10-17T15:10:12Z thinkpad: 1.90 2.58 4.39 | macmini (bots): { 133.45 109.92 85.49 } +2026-10-17T15:10:42Z thinkpad: 4.00 3.02 4.48 | macmini (bots): { 130.14 111.67 86.99 } +2026-10-17T15:11:13Z thinkpad: 4.77 3.32 4.54 | macmini (bots): { 118.78 110.28 87.32 } +2026-10-17T15:11:43Z thinkpad: 3.86 3.24 4.47 | macmini (bots): { 124.01 112.36 88.87 } +2026-10-17T15:12:13Z thinkpad: 3.61 3.26 4.44 | macmini (bots): { 122.21 112.94 89.88 } +2026-10-17T15:12:43Z thinkpad: 3.12 3.17 4.36 | macmini (bots): { 111.62 111.10 90.00 } +2026-10-17T15:13:14Z thinkpad: 3.07 3.14 4.31 | macmini (bots): { 122.97 113.95 91.77 } +2026-10-17T15:13:44Z thinkpad: 3.33 3.20 4.30 | macmini (bots): { 102.64 109.89 91.07 } +2026-10-17T15:14:14Z thinkpad: 2.85 3.10 4.23 | macmini (bots): { 94.46 107.15 90.72 } +2026-10-17T15:14:44Z thinkpad: 2.66 3.03 4.17 | macmini (bots): { 94.94 106.07 90.90 } +2026-10-17T15:15:14Z thinkpad: 2.54 2.96 4.11 | macmini (bots): { 94.52 104.93 91.01 } +2026-10-17T15:15:45Z thinkpad: 3.20 3.08 4.11 | macmini (bots): { 84.00 101.47 90.25 } +2026-10-17T15:16:15Z thinkpad: 5.56 3.61 4.25 | macmini (bots): { 83.16 99.76 90.02 } +2026-10-17T15:16:45Z thinkpad: 5.66 3.84 4.30 | macmini (bots): { 69.71 94.66 88.56 } +2026-10-17T15:17:15Z thinkpad: 5.04 3.90 4.31 | macmini (bots): { 59.31 89.78 87.00 } +2026-10-17T15:17:46Z thinkpad: 4.29 3.87 4.29 | macmini (bots): { 58.57 86.47 85.89 } +2026-10-17T15:18:16Z thinkpad: 4.16 3.91 4.29 | macmini (bots): { 56.43 83.29 84.75 } +2026-10-17T15:18:46Z thinkpad: 2.80 3.60 4.18 | macmini (bots): { 50.60 79.22 83.22 } +2026-10-17T15:19:16Z thinkpad: 1.85 3.28 4.05 | macmini (bots): { 54.97 77.50 82.46 } +2026-10-17T15:19:47Z thinkpad: 1.82 3.14 3.98 | macmini (bots): { 56.82 75.80 81.67 } +2026-10-17T15:20:17Z thinkpad: 2.19 3.10 3.94 | macmini (bots): { 59.30 74.46 80.97 } +2026-10-17T15:20:47Z thinkpad: 4.44 3.54 4.06 | macmini (bots): { 55.22 72.11 79.90 } +2026-10-17T15:21:17Z thinkpad: 5.99 4.03 4.21 | macmini (bots): { 49.41 69.01 78.50 } +2026-10-17T15:21:48Z thinkpad: 4.85 3.95 4.18 | macmini (bots): { 46.89 66.58 77.29 } +2026-10-17T15:22:18Z thinkpad: 4.31 3.92 4.16 | macmini (bots): { 45.13 64.31 76.10 } +2026-10-17T15:22:48Z thinkpad: 4.28 3.95 4.16 | macmini (bots): { 51.82 63.98 75.56 } +2026-10-17T15:23:18Z thinkpad: 4.75 4.11 4.21 | macmini (bots): { 50.35 62.51 74.63 } +2026-10-17T15:23:48Z thinkpad: 4.08 4.02 4.17 | macmini (bots): { 44.62 60.01 73.31 } +2026-10-17T15:24:19Z thinkpad: 3.93 4.00 4.16 | macmini (bots): { 46.02 58.72 72.37 } +2026-10-17T15:24:49Z thinkpad: 3.67 3.92 4.13 | macmini (bots): { 47.23 57.90 71.60 } +2026-10-17T15:25:19Z thinkpad: 2.79 3.68 4.04 | macmini (bots): { 50.80 57.78 71.09 } +2026-10-17T15:25:49Z thinkpad: 2.79 3.58 3.99 | macmini (bots): { 47.66 56.35 70.11 } +2026-10-17T15:26:19Z thinkpad: 5.04 3.97 4.11 | macmini (bots): { 45.15 54.84 69.08 } +2026-10-17T15:26:50Z thinkpad: 8.46 4.86 4.40 | macmini (bots): { 43.59 53.51 68.10 } +2026-10-17T15:27:20Z thinkpad: 6.84 4.81 4.39 | macmini (bots): { 42.38 52.39 67.19 } +2026-10-17T15:27:50Z thinkpad: 8.24 5.33 4.58 | macmini (bots): { 49.87 53.02 66.82 } +2026-10-17T15:28:21Z thinkpad: 7.11 5.34 4.61 | macmini (bots): { 61.30 55.60 67.28 } +2026-10-17T15:28:51Z thinkpad: 6.11 5.27 4.61 | macmini (bots): { 67.60 57.74 67.66 } +2026-10-17T15:29:21Z thinkpad: 5.33 5.17 4.59 | macmini (bots): { 63.72 57.79 67.33 } +2026-10-17T15:29:51Z thinkpad: 3.57 4.75 4.47 | macmini (bots): { 60.80 57.62 66.94 } +2026-10-17T15:30:22Z thinkpad: 4.74 4.88 4.52 | macmini (bots): { 59.69 57.64 66.62 } +2026-10-17T15:30:52Z thinkpad: 3.44 4.54 4.42 | macmini (bots): { 66.89 59.49 66.97 } +2026-10-17T15:31:22Z thinkpad: 4.57 4.69 4.47 | macmini (bots): { 83.43 64.16 68.40 } +2026-10-17T15:31:52Z thinkpad: 7.17 5.30 4.68 | macmini (bots): { 77.62 64.77 68.49 } +2026-10-17T15:32:23Z thinkpad: 8.55 5.82 4.88 | macmini (bots): { 74.20 65.09 68.47 } +2026-10-17T15:32:53Z thinkpad: 7.49 5.85 4.92 | macmini (bots): { 82.07 67.70 69.29 } +2026-10-17T15:33:23Z thinkpad: 5.65 5.59 4.86 | macmini (bots): { 79.44 68.47 69.51 } +2026-10-17T15:33:54Z thinkpad: 5.73 5.64 4.91 | macmini (bots): { 78.94 69.26 69.76 } +2026-10-17T15:34:24Z thinkpad: 6.84 5.92 5.02 | macmini (bots): { 76.33 69.71 69.91 } +2026-10-17T15:34:54Z thinkpad: 5.11 5.59 4.94 | macmini (bots): { 86.09 72.63 70.95 } +2026-10-17T15:35:24Z thinkpad: 6.68 5.93 5.08 | macmini (bots): { 72.77 70.70 70.31 } +2026-10-17T15:35:55Z thinkpad: 5.75 5.75 5.04 | macmini (bots): { 71.50 70.49 70.24 } +2026-10-17T15:36:25Z thinkpad: 4.31 5.41 4.95 | macmini (bots): { 80.75 72.67 71.03 } +2026-10-17T15:36:55Z thinkpad: 3.15 5.02 4.83 | macmini (bots): { 89.83 75.59 72.14 } diff --git a/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json b/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json new file mode 100644 index 000000000..39dcd268c --- /dev/null +++ b/benchmarks/server-2026-10-17/earlier-002f14ce/walk-explore.json @@ -0,0 +1,695 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T14:56:24+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "a9ee56a8b143999c9bc7056850ffcd622a9214aa", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/walk-explore.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 9.51, + "mspt": { + "average": 5.77, + "p50": 5.15, + "p95": 11.04, + "p99": 28.99 + }, + "mspt_worst_p99": 45.9, + "tps": 20.0, + "rss_mb": { + "mean": 777.78, + "max": 779.8 + }, + "cpu_percent": 59.02, + "chunks_per_second": 9.94, + "unique_per_second": 0.45, + "forgotten_per_second": 9.99, + "waited_ticks_per_second": 0.0, + "chunks_total": 2763, + "chunks_per_bot": { + "walk": 2763.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.35, + "mspt": { + "average": 18.84, + "p50": 18.87, + "p95": 29.55, + "p99": 51.32 + }, + "mspt_worst_p99": 456.4, + "tps": 20.0, + "rss_mb": { + "mean": 3442.06, + "max": 3462.1 + }, + "cpu_percent": 70.63, + "chunks_per_second": 10.47, + "unique_per_second": 0.47, + "forgotten_per_second": 10.53, + "waited_ticks_per_second": 0.0, + "chunks_total": 2763, + "chunks_per_bot": { + "walk": 2763.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 9.31, + "mspt": { + "average": 16.23, + "p50": 15.6, + "p95": 29.32, + "p99": 44.43 + }, + "mspt_worst_p99": 100.6, + "tps": 20.0, + "rss_mb": { + "mean": 781.84, + "max": 782.6 + }, + "cpu_percent": 136.59, + "chunks_per_second": 93.82, + "unique_per_second": 3.33, + "forgotten_per_second": 93.61, + "waited_ticks_per_second": 0.0, + "chunks_total": 26481, + "chunks_per_bot": { + "walk": 2648.1 + }, + "unique_chunks_per_bot": { + "walk": 679.5 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.65, + "mspt": { + "average": 18.02, + "p50": 15.22, + "p95": 37.62, + "p99": 54.5 + }, + "mspt_worst_p99": 73.8, + "tps": 20.0, + "rss_mb": { + "mean": 3408.62, + "max": 3423.6 + }, + "cpu_percent": 100.57, + "chunks_per_second": 101.12, + "unique_per_second": 4.25, + "forgotten_per_second": 101.17, + "waited_ticks_per_second": 0.0, + "chunks_total": 26763, + "chunks_per_bot": { + "walk": 2676.3 + }, + "unique_chunks_per_bot": { + "walk": 687.8 + }, + "resent": 0, + "pulled_back": 7, + "moved_too_quickly": 7, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 9.31, + "mspt": { + "average": 23.98, + "p50": 20.89, + "p95": 49.18, + "p99": 65.87 + }, + "mspt_worst_p99": 109.8, + "tps": 20.0, + "rss_mb": { + "mean": 786.18, + "max": 786.5 + }, + "cpu_percent": 159.81, + "chunks_per_second": 235.75, + "unique_per_second": 7.84, + "forgotten_per_second": 235.72, + "waited_ticks_per_second": 0.0, + "chunks_total": 67251, + "chunks_per_bot": { + "walk": 2690.04 + }, + "unique_chunks_per_bot": { + "walk": 683.92 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.95, + "mspt": { + "average": 19.19, + "p50": 17.34, + "p95": 33.84, + "p99": 56.21 + }, + "mspt_worst_p99": 79.2, + "tps": 20.0, + "rss_mb": { + "mean": 3531.46, + "max": 3582.1 + }, + "cpu_percent": 153.78, + "chunks_per_second": 252.35, + "unique_per_second": 11.73, + "forgotten_per_second": 251.58, + "waited_ticks_per_second": 0.0, + "chunks_total": 66759, + "chunks_per_bot": { + "walk": 2670.36 + }, + "unique_chunks_per_bot": { + "walk": 689.76 + }, + "resent": 0, + "pulled_back": 12, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 35.07, + "p50": 30.55, + "p95": 73.24, + "p99": 99.38 + }, + "mspt_worst_p99": 117.2, + "tps": 20.0, + "rss_mb": { + "mean": 816.58, + "max": 818.5 + }, + "cpu_percent": 187.42, + "chunks_per_second": 469.11, + "unique_per_second": 15.92, + "forgotten_per_second": 468.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 136962, + "chunks_per_bot": { + "walk": 2739.24 + }, + "unique_chunks_per_bot": { + "walk": 685.68 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 15.95, + "mspt": { + "average": 35.23, + "p50": 31.39, + "p95": 60.87, + "p99": 104.2 + }, + "mspt_worst_p99": 443.7, + "tps": 20.0, + "rss_mb": { + "mean": 3562.57, + "max": 3598.9 + }, + "cpu_percent": 263.27, + "chunks_per_second": 497.51, + "unique_per_second": 30.67, + "forgotten_per_second": 495.7, + "waited_ticks_per_second": 0.0, + "chunks_total": 131116, + "chunks_per_bot": { + "walk": 2622.32 + }, + "unique_chunks_per_bot": { + "walk": 687.78 + }, + "resent": 0, + "pulled_back": 96, + "moved_too_quickly": 96, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 104.8, + "p50": 100.6, + "p95": 158.8, + "p99": 198.61 + }, + "mspt_worst_p99": 259.8, + "tps": 9.54, + "rss_mb": { + "mean": 850.05, + "max": 851.2 + }, + "cpu_percent": 198.95, + "chunks_per_second": 371.72, + "unique_per_second": 26.27, + "forgotten_per_second": 365.57, + "waited_ticks_per_second": 0.0, + "chunks_total": 144465, + "chunks_per_bot": { + "walk": 1444.65 + }, + "unique_chunks_per_bot": { + "walk": 571.76 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 34 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.25, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 11.42, + "p50": 10.15, + "p95": 24.66, + "p99": 37.27 + }, + "mspt_worst_p99": 60.3, + "tps": 20.0, + "rss_mb": { + "mean": 838.61, + "max": 888.0 + }, + "cpu_percent": 326.85, + "chunks_per_second": 41.83, + "unique_per_second": 36.39, + "forgotten_per_second": 41.75, + "waited_ticks_per_second": 0.0, + "chunks_total": 9845, + "chunks_per_bot": { + "explore": 9845.0 + }, + "unique_chunks_per_bot": { + "explore": 8718.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.44, + "mspt": { + "average": 9.83, + "p50": 7.72, + "p95": 20.36, + "p99": 84.65 + }, + "mspt_worst_p99": 385.9, + "tps": 20.0, + "rss_mb": { + "mean": 3598.02, + "max": 3658.9 + }, + "cpu_percent": 244.86, + "chunks_per_second": 35.28, + "unique_per_second": 33.34, + "forgotten_per_second": 35.13, + "waited_ticks_per_second": 0.0, + "chunks_total": 7881, + "chunks_per_bot": { + "explore": 7881.0 + }, + "unique_chunks_per_bot": { + "explore": 7540.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.52, + "mspt": { + "average": 23.54, + "p50": 21.18, + "p95": 43.4, + "p99": 60.85 + }, + "mspt_worst_p99": 109.1, + "tps": 20.0, + "rss_mb": { + "mean": 1139.51, + "max": 1301.0 + }, + "cpu_percent": 331.74, + "chunks_per_second": 43.86, + "unique_per_second": 43.09, + "forgotten_per_second": 43.82, + "waited_ticks_per_second": 172.35, + "chunks_total": 14140, + "chunks_per_bot": { + "explore": 1414.0 + }, + "unique_chunks_per_bot": { + "explore": 1395.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.78, + "mspt": { + "average": 16.42, + "p50": 14.01, + "p95": 30.29, + "p99": 96.17 + }, + "mspt_worst_p99": 1144.3, + "tps": 20.0, + "rss_mb": { + "mean": 3964.49, + "max": 4248.3 + }, + "cpu_percent": 256.86, + "chunks_per_second": 25.43, + "unique_per_second": 25.33, + "forgotten_per_second": 25.96, + "waited_ticks_per_second": 76.05, + "chunks_total": 7991, + "chunks_per_bot": { + "explore": 799.1 + }, + "unique_chunks_per_bot": { + "explore": 797.7 + }, + "resent": 0, + "pulled_back": 11028, + "moved_too_quickly": 17, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 36.87, + "p50": 33.92, + "p95": 63.19, + "p99": 84.17 + }, + "mspt_worst_p99": 124.2, + "tps": 20.0, + "rss_mb": { + "mean": 1236.2, + "max": 1438.4 + }, + "cpu_percent": 345.03, + "chunks_per_second": 91.07, + "unique_per_second": 88.7, + "forgotten_per_second": 92.51, + "waited_ticks_per_second": 443.88, + "chunks_total": 30035, + "chunks_per_bot": { + "explore": 1201.4 + }, + "unique_chunks_per_bot": { + "explore": 1176.84 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.55, + "mspt": { + "average": 24.31, + "p50": 21.76, + "p95": 36.55, + "p99": 155.88 + }, + "mspt_worst_p99": 1535.8, + "tps": 20.0, + "rss_mb": { + "mean": 4047.76, + "max": 4459.2 + }, + "cpu_percent": 305.24, + "chunks_per_second": 37.94, + "unique_per_second": 37.82, + "forgotten_per_second": 38.87, + "waited_ticks_per_second": 261.79, + "chunks_total": 16604, + "chunks_per_bot": { + "explore": 664.16 + }, + "unique_chunks_per_bot": { + "explore": 660.92 + }, + "resent": 0, + "pulled_back": 33246, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 60.06, + "p50": 57.31, + "p95": 88.38, + "p99": 112.89 + }, + "mspt_worst_p99": 172.4, + "tps": 16.65, + "rss_mb": { + "mean": 1192.47, + "max": 1372.5 + }, + "cpu_percent": 362.42, + "chunks_per_second": 157.28, + "unique_per_second": 154.2, + "forgotten_per_second": 156.07, + "waited_ticks_per_second": 890.09, + "chunks_total": 54551, + "chunks_per_bot": { + "explore": 1091.02 + }, + "unique_chunks_per_bot": { + "explore": 1078.5 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.64, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 9.21, + "mspt": { + "average": 124.25, + "p50": 120.1, + "p95": 168.33, + "p99": 204.64 + }, + "mspt_worst_p99": 262.2, + "tps": 8.05, + "rss_mb": { + "mean": 1283.26, + "max": 1418.6 + }, + "cpu_percent": 334.14, + "chunks_per_second": 185.47, + "unique_per_second": 184.54, + "forgotten_per_second": 179.79, + "waited_ticks_per_second": 1864.45, + "chunks_total": 78556, + "chunks_per_bot": { + "explore": 785.56 + }, + "unique_chunks_per_bot": { + "explore": 784.88 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 15.44, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-2026-10-17/explore-equal-rate.json b/benchmarks/server-2026-10-17/explore-equal-rate.json new file mode 100644 index 000000000..1356529e3 --- /dev/null +++ b/benchmarks/server-2026-10-17/explore-equal-rate.json @@ -0,0 +1,341 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T18:12:19+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "7bbbf6e97fb53683eae0a01ce2c134e53cb649a7", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/explore-equal-rate.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.42, + "mspt": { + "average": 3.16, + "p50": 2.98, + "p95": 5.78, + "p99": 12.17 + }, + "mspt_worst_p99": 38.1, + "tps": 20.0, + "rss_mb": { + "mean": 759.26, + "max": 769.5 + }, + "cpu_percent": 21.74, + "chunks_per_second": 1.64, + "unique_per_second": 1.27, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 841, + "chunks_per_bot": { + "explore": 841.0 + }, + "unique_chunks_per_bot": { + "explore": 781.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 17.17, + "mspt": { + "average": 16.82, + "p50": 16.67, + "p95": 27.3, + "p99": 52.16 + }, + "mspt_worst_p99": 453.4, + "tps": 20.0, + "rss_mb": { + "mean": 3373.16, + "max": 3405.9 + }, + "cpu_percent": 69.22, + "chunks_per_second": 1.66, + "unique_per_second": 1.35, + "forgotten_per_second": 1.54, + "waited_ticks_per_second": 0.0, + "chunks_total": 838, + "chunks_per_bot": { + "explore": 838.0 + }, + "unique_chunks_per_bot": { + "explore": 779.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.82, + "mspt": { + "average": 9.83, + "p50": 8.65, + "p95": 19.01, + "p99": 32.9 + }, + "mspt_worst_p99": 64.0, + "tps": 20.0, + "rss_mb": { + "mean": 861.49, + "max": 922.2 + }, + "cpu_percent": 77.43, + "chunks_per_second": 13.71, + "unique_per_second": 12.31, + "forgotten_per_second": 13.59, + "waited_ticks_per_second": 0.0, + "chunks_total": 7831, + "chunks_per_bot": { + "explore": 783.1 + }, + "unique_chunks_per_bot": { + "explore": 757.1 + }, + "resent": 0, + "pulled_back": 1051, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.06, + "mspt": { + "average": 24.38, + "p50": 21.55, + "p95": 39.58, + "p99": 66.64 + }, + "mspt_worst_p99": 107.1, + "tps": 20.0, + "rss_mb": { + "mean": 3569.41, + "max": 3685.1 + }, + "cpu_percent": 132.09, + "chunks_per_second": 13.54, + "unique_per_second": 12.32, + "forgotten_per_second": 13.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 7753, + "chunks_per_bot": { + "explore": 775.3 + }, + "unique_chunks_per_bot": { + "explore": 749.2 + }, + "resent": 0, + "pulled_back": 1027, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 16.87, + "p50": 15.4, + "p95": 30.88, + "p99": 46.73 + }, + "mspt_worst_p99": 84.9, + "tps": 20.0, + "rss_mb": { + "mean": 887.11, + "max": 945.5 + }, + "cpu_percent": 111.2, + "chunks_per_second": 33.51, + "unique_per_second": 29.92, + "forgotten_per_second": 33.33, + "waited_ticks_per_second": 0.0, + "chunks_total": 19718, + "chunks_per_bot": { + "explore": 788.72 + }, + "unique_chunks_per_bot": { + "explore": 759.08 + }, + "resent": 0, + "pulled_back": 3770, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.94, + "mspt": { + "average": 30.29, + "p50": 28.25, + "p95": 43.47, + "p99": 68.56 + }, + "mspt_worst_p99": 165.2, + "tps": 20.0, + "rss_mb": { + "mean": 3608.97, + "max": 3732.0 + }, + "cpu_percent": 176.28, + "chunks_per_second": 32.98, + "unique_per_second": 29.29, + "forgotten_per_second": 32.84, + "waited_ticks_per_second": 0.0, + "chunks_total": 19442, + "chunks_per_bot": { + "explore": 777.68 + }, + "unique_chunks_per_bot": { + "explore": 748.24 + }, + "resent": 0, + "pulled_back": 5139, + "moved_too_quickly": 11, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 23.57, + "p50": 20.43, + "p95": 47.53, + "p99": 67.23 + }, + "mspt_worst_p99": 106.2, + "tps": 20.0, + "rss_mb": { + "mean": 924.41, + "max": 984.3 + }, + "cpu_percent": 127.14, + "chunks_per_second": 66.56, + "unique_per_second": 59.42, + "forgotten_per_second": 66.43, + "waited_ticks_per_second": 0.0, + "chunks_total": 39950, + "chunks_per_bot": { + "explore": 799.0 + }, + "unique_chunks_per_bot": { + "explore": 767.56 + }, + "resent": 0, + "pulled_back": 7434, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 15.04, + "mspt": { + "average": 42.44, + "p50": 40.71, + "p95": 54.84, + "p99": 94.23 + }, + "mspt_worst_p99": 212.3, + "tps": 20.0, + "rss_mb": { + "mean": 3667.85, + "max": 3780.8 + }, + "cpu_percent": 200.85, + "chunks_per_second": 65.17, + "unique_per_second": 58.11, + "forgotten_per_second": 65.22, + "waited_ticks_per_second": 0.0, + "chunks_total": 39772, + "chunks_per_bot": { + "explore": 795.44 + }, + "unique_chunks_per_bot": { + "explore": 764.02 + }, + "resent": 0, + "pulled_back": 10604, + "moved_too_quickly": 38, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + } + ] +} diff --git a/benchmarks/server-2026-10-17/load.txt b/benchmarks/server-2026-10-17/load.txt new file mode 100644 index 000000000..33d8b191f --- /dev/null +++ b/benchmarks/server-2026-10-17/load.txt @@ -0,0 +1,279 @@ +2026-10-17T15:51:54Z thinkpad: 1.30 2.47 3.85 | macmini (bots): { 67.44 76.34 77.44 } +2026-10-17T15:52:25Z thinkpad: 2.07 2.54 3.83 | macmini (bots): { 64.78 74.76 76.82 } +2026-10-17T15:52:55Z thinkpad: 2.08 2.51 3.78 | macmini (bots): { 62.50 73.29 76.22 } +2026-10-17T15:53:25Z thinkpad: 1.46 2.31 3.67 | macmini (bots): { 63.70 72.67 75.90 } +2026-10-17T15:53:55Z thinkpad: 1.12 2.15 3.58 | macmini (bots): { 69.06 73.27 76.01 } +2026-10-17T15:54:26Z thinkpad: 1.34 2.09 3.51 | macmini (bots): { 72.55 73.63 76.04 } +2026-10-17T15:54:56Z thinkpad: 1.11 1.97 3.42 | macmini (bots): { 77.53 74.77 76.37 } +2026-10-17T15:55:26Z thinkpad: 1.02 1.87 3.34 | macmini (bots): { 77.61 74.90 76.36 } +2026-10-17T15:55:56Z thinkpad: 1.09 1.81 3.27 | macmini (bots): { 71.56 73.69 75.86 } +2026-10-17T15:56:26Z thinkpad: 2.23 1.99 3.29 | macmini (bots): { 65.21 71.93 75.15 } +2026-10-17T15:56:57Z thinkpad: 2.60 2.12 3.29 | macmini (bots): { 58.16 69.40 74.10 } +2026-10-17T15:57:27Z thinkpad: 2.57 2.18 3.27 | macmini (bots): { 57.54 68.26 73.52 } +2026-10-17T15:57:57Z thinkpad: 2.37 2.17 3.23 | macmini (bots): { 56.15 66.85 72.83 } +2026-10-17T15:58:27Z thinkpad: 1.90 2.08 3.17 | macmini (bots): { 59.28 66.57 72.52 } +2026-10-17T15:58:58Z thinkpad: 1.71 2.02 3.11 | macmini (bots): { 55.64 64.94 71.72 } +2026-10-17T15:59:28Z thinkpad: 1.66 1.97 3.06 | macmini (bots): { 66.06 66.49 72.04 } +2026-10-17T15:59:58Z thinkpad: 1.18 1.83 2.98 | macmini (bots): { 78.15 69.43 72.92 } +2026-10-17T16:00:28Z thinkpad: 0.83 1.68 2.89 | macmini (bots): { 70.77 68.57 72.49 } +2026-10-17T16:00:58Z thinkpad: 1.27 1.70 2.86 | macmini (bots): { 71.95 68.97 72.49 } +2026-10-17T16:01:29Z thinkpad: 1.85 1.79 2.85 | macmini (bots): { 83.43 72.22 73.56 } +2026-10-17T16:01:59Z thinkpad: 2.51 1.95 2.86 | macmini (bots): { 70.49 70.18 72.77 } +2026-10-17T16:02:29Z thinkpad: 1.98 1.87 2.81 | macmini (bots): { 64.00 68.64 72.12 } +2026-10-17T16:02:59Z thinkpad: 1.77 1.84 2.77 | macmini (bots): { 59.65 67.09 71.44 } +2026-10-17T16:03:30Z thinkpad: 4.04 2.35 2.91 | macmini (bots): { 62.67 67.15 71.31 } +2026-10-17T16:04:00Z thinkpad: 4.94 2.72 3.01 | macmini (bots): { 67.63 67.82 71.40 } +2026-10-17T16:04:30Z thinkpad: 4.22 2.78 3.02 | macmini (bots): { 70.41 68.39 71.48 } +2026-10-17T16:05:00Z thinkpad: 3.81 2.80 3.02 | macmini (bots): { 66.59 67.83 71.18 } +2026-10-17T16:05:31Z thinkpad: 3.20 2.75 3.00 | macmini (bots): { 72.53 69.01 71.48 } +2026-10-17T16:06:01Z thinkpad: 4.22 3.04 3.08 | macmini (bots): { 71.30 69.27 71.50 } +2026-10-17T16:06:31Z thinkpad: 5.43 3.47 3.23 | macmini (bots): { 68.37 68.63 71.19 } +2026-10-17T16:07:01Z thinkpad: 4.35 3.42 3.22 | macmini (bots): { 60.20 66.68 70.39 } +2026-10-17T16:07:31Z thinkpad: 3.47 3.31 3.19 | macmini (bots): { 58.03 65.51 69.84 } +2026-10-17T16:08:02Z thinkpad: 2.30 3.04 3.11 | macmini (bots): { 59.05 65.13 69.55 } +2026-10-17T16:08:32Z thinkpad: 1.88 2.86 3.04 | macmini (bots): { 51.77 62.75 68.53 } +2026-10-17T16:09:02Z thinkpad: 1.38 2.65 2.97 | macmini (bots): { 49.05 61.01 67.70 } +2026-10-17T16:09:32Z thinkpad: 3.10 2.95 3.06 | macmini (bots): { 48.91 59.82 67.03 } +2026-10-17T16:10:02Z thinkpad: 2.91 2.91 3.04 | macmini (bots): { 47.56 58.44 66.25 } +2026-10-17T16:10:33Z thinkpad: 2.58 2.83 3.01 | macmini (bots): { 49.23 57.69 65.70 } +2026-10-17T16:11:03Z thinkpad: 8.38 4.15 3.44 | macmini (bots): { 44.16 55.72 64.71 } +2026-10-17T16:11:33Z thinkpad: 9.94 4.92 3.72 | macmini (bots): { 44.50 54.71 64.03 } +2026-10-17T16:12:03Z thinkpad: 10.08 5.42 3.92 | macmini (bots): { 42.15 53.21 63.17 } +2026-10-17T16:12:33Z thinkpad: 6.79 5.06 3.85 | macmini (bots): { 36.13 50.73 61.92 } +2026-10-17T16:13:04Z thinkpad: 4.61 4.72 3.77 | macmini (bots): { 41.28 50.64 61.51 } +2026-10-17T16:13:34Z thinkpad: 3.81 4.50 3.73 | macmini (bots): { 42.92 50.15 60.95 } +2026-10-17T16:14:04Z thinkpad: 3.39 4.35 3.71 | macmini (bots): { 41.56 49.16 60.22 } +2026-10-17T16:14:35Z thinkpad: 7.53 5.17 4.00 | macmini (bots): { 47.48 49.82 60.07 } +2026-10-17T16:15:05Z thinkpad: 9.73 6.01 4.32 | macmini (bots): { 51.43 50.41 59.92 } +2026-10-17T16:15:35Z thinkpad: 8.07 5.94 4.35 | macmini (bots): { 69.31 54.81 61.18 } +2026-10-17T16:16:05Z thinkpad: 9.27 6.45 4.57 | macmini (bots): { 71.85 56.92 61.73 } +2026-10-17T16:16:35Z thinkpad: 8.69 6.59 4.68 | macmini (bots): { 64.77 56.72 61.50 } +2026-10-17T16:17:06Z thinkpad: 6.11 6.17 4.60 | macmini (bots): { 57.92 55.86 61.02 } +2026-10-17T16:17:36Z thinkpad: 6.79 6.33 4.70 | macmini (bots): { 51.44 54.51 60.36 } +2026-10-17T16:18:06Z thinkpad: 5.16 5.99 4.64 | macmini (bots): { 51.33 54.23 60.05 } +2026-10-17T16:18:36Z thinkpad: 5.30 5.93 4.66 | macmini (bots): { 55.22 54.87 60.08 } +2026-10-17T16:19:07Z thinkpad: 4.78 5.72 4.63 | macmini (bots): { 51.62 53.94 59.56 } +2026-10-17T16:19:37Z thinkpad: 5.25 5.78 4.69 | macmini (bots): { 48.77 53.04 59.04 } +2026-10-17T16:20:07Z thinkpad: 4.63 5.60 4.67 | macmini (bots): { 54.59 53.92 59.14 } +2026-10-17T16:20:37Z thinkpad: 5.46 5.67 4.72 | macmini (bots): { 59.07 55.03 59.36 } +2026-10-17T16:21:07Z thinkpad: 8.07 6.19 4.91 | macmini (bots): { 52.53 53.83 58.77 } +2026-10-17T16:21:38Z thinkpad: 15.01 8.05 5.57 | macmini (bots): { 48.85 52.78 58.19 } +2026-10-17T16:22:08Z thinkpad: 19.08 9.69 6.20 | macmini (bots): { 54.73 53.61 58.29 } +2026-10-17T16:22:39Z thinkpad: 27.72 12.63 7.29 | macmini (bots): { 54.23 53.61 58.13 } +2026-10-17T16:23:09Z thinkpad: 23.10 12.88 7.53 | macmini (bots): { 51.63 53.06 57.77 } +2026-10-17T16:23:39Z thinkpad: 20.51 13.53 7.96 | macmini (bots): { 45.29 51.38 57.00 } +2026-10-17T16:24:10Z thinkpad: 12.70 12.30 7.72 | macmini (bots): { 45.61 50.91 56.63 } +2026-10-17T16:24:40Z thinkpad: 8.67 11.35 7.55 | macmini (bots): { 45.18 50.35 56.23 } +2026-10-17T16:25:10Z thinkpad: 6.35 10.53 7.40 | macmini (bots): { 41.10 48.88 55.50 } +2026-10-17T16:25:40Z thinkpad: 6.26 10.16 7.38 | macmini (bots): { 49.86 50.24 55.76 } +2026-10-17T16:26:11Z thinkpad: 7.71 10.11 7.45 | macmini (bots): { 53.93 51.11 55.88 } +2026-10-17T16:26:41Z thinkpad: 9.50 10.32 7.61 | macmini (bots): { 47.61 49.86 55.26 } +2026-10-17T16:27:11Z thinkpad: 10.26 10.39 7.72 | macmini (bots): { 46.43 49.36 54.89 } +2026-10-17T16:27:42Z thinkpad: 10.61 10.48 7.83 | macmini (bots): { 48.88 49.66 54.80 } +2026-10-17T16:28:12Z thinkpad: 10.39 10.45 7.91 | macmini (bots): { 58.42 51.74 55.37 } +2026-10-17T16:28:42Z thinkpad: 10.36 10.44 7.99 | macmini (bots): { 59.59 52.67 55.58 } +2026-10-17T16:29:13Z thinkpad: 9.63 10.25 8.00 | macmini (bots): { 55.30 52.38 55.38 } +2026-10-17T16:29:43Z thinkpad: 10.33 10.37 8.12 | macmini (bots): { 57.79 53.13 55.52 } +2026-10-17T16:30:13Z thinkpad: 9.68 10.18 8.12 | macmini (bots): { 57.83 53.60 55.61 } +2026-10-17T16:30:43Z thinkpad: 9.72 10.17 8.19 | macmini (bots): { 78.94 59.18 57.56 } +2026-10-17T16:31:14Z thinkpad: 6.60 9.36 7.98 | macmini (bots): { 87.29 62.98 58.99 } +2026-10-17T16:31:44Z thinkpad: 6.77 9.08 7.93 | macmini (bots): { 81.82 64.16 59.57 } +2026-10-17T16:32:14Z thinkpad: 13.15 10.41 8.41 | macmini (bots): { 81.20 65.92 60.37 } +2026-10-17T16:32:45Z thinkpad: 27.80 14.12 9.71 | macmini (bots): { 75.41 66.22 60.69 } +2026-10-17T16:33:15Z thinkpad: 44.59 19.25 11.54 | macmini (bots): { 66.92 65.08 60.47 } +2026-10-17T16:33:46Z thinkpad: 44.87 21.89 12.67 | macmini (bots): { 61.47 63.94 60.22 } +2026-10-17T16:34:16Z thinkpad: 38.98 22.67 13.23 | macmini (bots): { 62.13 63.78 60.28 } +2026-10-17T16:34:47Z thinkpad: 47.64 26.08 14.65 | macmini (bots): { 81.23 68.06 61.94 } +2026-10-17T16:35:17Z thinkpad: 47.83 28.02 15.65 | macmini (bots): { 116.14 78.43 65.98 } +2026-10-17T16:35:48Z thinkpad: 40.43 28.18 16.10 | macmini (bots): { 125.61 84.41 68.58 } +2026-10-17T16:36:19Z thinkpad: 41.34 29.71 17.00 | macmini (bots): { 143.61 92.86 72.20 } +2026-10-17T16:36:49Z thinkpad: 34.40 29.19 17.29 | macmini (bots): { 156.05 100.88 75.83 } +2026-10-17T16:37:20Z thinkpad: 25.34 27.65 17.17 | macmini (bots): { 151.90 105.26 78.29 } +2026-10-17T16:37:50Z thinkpad: 18.36 25.71 16.85 | macmini (bots): { 141.10 107.25 79.96 } +2026-10-17T16:38:20Z thinkpad: 16.19 24.47 16.72 | macmini (bots): { 131.21 107.92 81.13 } +2026-10-17T16:38:51Z thinkpad: 13.36 23.00 16.48 | macmini (bots): { 122.08 107.78 82.00 } +2026-10-17T16:39:21Z thinkpad: 11.27 21.57 16.21 | macmini (bots): { 107.07 105.50 82.07 } +2026-10-17T16:39:51Z thinkpad: 11.19 20.56 16.04 | macmini (bots): { 96.38 103.12 82.02 } +2026-10-17T16:40:22Z thinkpad: 10.06 19.37 15.79 | macmini (bots): { 89.06 100.79 81.91 } +2026-10-17T16:40:52Z thinkpad: 7.38 17.86 15.40 | macmini (bots): { 79.35 97.41 81.34 } +2026-10-17T16:41:23Z thinkpad: 6.18 16.57 15.05 | macmini (bots): { 81.70 96.20 81.46 } +2026-10-17T16:41:53Z thinkpad: 5.56 15.44 14.72 | macmini (bots): { 86.51 95.88 81.84 } +2026-10-17T16:42:23Z thinkpad: 4.90 14.33 14.37 | macmini (bots): { 99.20 97.69 83.05 } +2026-10-17T16:42:53Z thinkpad: 5.01 13.47 14.08 | macmini (bots): { 116.29 101.87 85.07 } +2026-10-17T16:43:24Z thinkpad: 4.34 12.50 13.74 | macmini (bots): { 131.32 106.77 87.42 } +2026-10-17T16:43:54Z thinkpad: 4.08 11.65 13.42 | macmini (bots): { 155.44 114.77 90.98 } +2026-10-17T16:44:24Z thinkpad: 4.00 10.90 13.11 | macmini (bots): { 167.86 121.62 94.28 } +2026-10-17T16:44:54Z thinkpad: 3.98 10.13 12.77 | macmini (bots): { 160.36 124.31 96.20 } +2026-10-17T16:45:25Z thinkpad: 4.20 9.59 12.50 | macmini (bots): { 163.23 128.59 98.74 } +2026-10-17T16:45:55Z thinkpad: 4.54 9.15 12.27 | macmini (bots): { 169.93 133.73 101.65 } +2026-10-17T16:46:25Z thinkpad: 4.44 8.69 12.01 | macmini (bots): { 162.40 135.22 103.29 } +2026-10-17T16:46:55Z thinkpad: 4.06 8.20 11.74 | macmini (bots): { 164.16 138.31 105.52 } +2026-10-17T16:47:26Z thinkpad: 3.96 7.78 11.49 | macmini (bots): { 157.92 139.31 107.02 } +2026-10-17T16:47:56Z thinkpad: 3.71 7.35 11.23 | macmini (bots): { 155.72 140.55 108.59 } +2026-10-17T16:48:26Z thinkpad: 4.93 7.32 11.09 | macmini (bots): { 153.39 141.52 110.05 } +2026-10-17T16:48:56Z thinkpad: 4.61 7.03 10.88 | macmini (bots): { 137.54 138.87 110.18 } +2026-10-17T16:49:27Z thinkpad: 4.01 6.65 10.63 | macmini (bots): { 136.53 138.36 110.98 } +2026-10-17T16:49:57Z thinkpad: 3.19 6.19 10.35 | macmini (bots): { 141.12 139.18 112.22 } +2026-10-17T16:50:27Z thinkpad: 5.31 6.43 10.30 | macmini (bots): { 122.76 135.27 111.75 } +2026-10-17T16:50:57Z thinkpad: 5.95 6.48 10.19 | macmini (bots): { 114.26 132.02 111.39 } +2026-10-17T16:51:28Z thinkpad: 5.76 6.41 10.05 | macmini (bots): { 116.04 130.87 111.69 } +2026-10-17T16:51:58Z thinkpad: 5.11 6.18 9.86 | macmini (bots): { 115.06 129.17 111.74 } +2026-10-17T16:52:28Z thinkpad: 5.09 6.07 9.70 | macmini (bots): { 109.91 126.59 111.41 } +2026-10-17T16:52:58Z thinkpad: 4.74 5.90 9.53 | macmini (bots): { 101.90 123.11 110.67 } +2026-10-17T16:53:29Z thinkpad: 4.89 5.84 9.39 | macmini (bots): { 83.29 116.38 108.74 } +2026-10-17T16:53:59Z thinkpad: 5.10 5.82 9.27 | macmini (bots): { 119.16 122.10 111.09 } +2026-10-17T16:54:29Z thinkpad: 4.57 5.67 9.10 | macmini (bots): { 114.87 120.76 110.98 } +2026-10-17T16:55:00Z thinkpad: 4.74 5.58 8.96 | macmini (bots): { 129.84 123.74 112.39 } +2026-10-17T16:55:30Z thinkpad: 6.40 5.90 8.96 | macmini (bots): { 100.10 117.29 110.46 } +2026-10-17T16:56:00Z thinkpad: 6.96 6.08 8.92 | macmini (bots): { 80.18 110.75 108.32 } +2026-10-17T16:56:30Z thinkpad: 6.07 5.95 8.79 | macmini (bots): { 74.41 106.39 106.82 } +2026-10-17T16:57:01Z thinkpad: 6.63 6.13 8.75 | macmini (bots): { 81.71 104.99 106.29 } +2026-10-17T16:57:31Z thinkpad: 6.39 6.14 8.68 | macmini (bots): { 101.10 107.55 107.18 } +2026-10-17T16:58:01Z thinkpad: 6.32 6.16 8.60 | macmini (bots): { 94.45 105.66 106.52 } +2026-10-17T16:58:31Z thinkpad: 5.19 5.90 8.44 | macmini (bots): { 78.76 100.83 104.75 } +2026-10-17T16:59:02Z thinkpad: 5.24 5.83 8.33 | macmini (bots): { 78.19 98.42 103.73 } +2026-10-17T16:59:32Z thinkpad: 3.95 5.48 8.13 | macmini (bots): { 77.57 96.42 102.82 } +2026-10-17T17:00:02Z thinkpad: 3.12 5.13 7.93 | macmini (bots): { 85.23 96.29 102.54 } +2026-10-17T17:00:32Z thinkpad: 3.17 4.93 7.77 | macmini (bots): { 99.84 99.07 103.35 } +2026-10-17T17:01:02Z thinkpad: 6.09 5.50 7.88 | macmini (bots): { 80.56 94.49 101.54 } +2026-10-17T17:01:33Z thinkpad: 9.23 6.29 8.06 | macmini (bots): { 79.70 93.03 100.77 } +2026-10-17T17:02:03Z thinkpad: 9.09 6.54 8.09 | macmini (bots): { 76.63 90.94 99.74 } +2026-10-17T17:02:33Z thinkpad: 7.86 6.52 8.04 | macmini (bots): { 93.08 93.50 100.36 } +2026-10-17T17:03:03Z thinkpad: 7.81 6.67 8.04 | macmini (bots): { 83.14 91.09 99.25 } +2026-10-17T17:03:34Z thinkpad: 6.69 6.51 7.94 | macmini (bots): { 79.37 89.64 98.45 } +2026-10-17T17:04:04Z thinkpad: 5.63 6.27 7.81 | macmini (bots): { 73.68 87.23 97.27 } +2026-10-17T17:04:34Z thinkpad: 5.75 6.21 7.75 | macmini (bots): { 75.89 86.23 96.54 } +2026-10-17T17:05:04Z thinkpad: 5.05 6.01 7.63 | macmini (bots): { 79.29 86.13 96.10 } +2026-10-17T17:05:35Z thinkpad: 3.88 5.62 7.44 | macmini (bots): { 76.07 84.79 95.28 } +2026-10-17T17:06:05Z thinkpad: 6.47 6.07 7.53 | macmini (bots): { 70.59 82.62 94.13 } +2026-10-17T17:06:35Z thinkpad: 8.20 6.53 7.63 | macmini (bots): { 69.09 81.18 93.21 } +2026-10-17T17:07:05Z thinkpad: 7.59 6.54 7.60 | macmini (bots): { 77.55 82.11 93.13 } +2026-10-17T17:07:36Z thinkpad: 6.93 6.49 7.55 | macmini (bots): { 84.23 83.41 93.22 } +2026-10-17T17:08:06Z thinkpad: 7.21 6.61 7.56 | macmini (bots): { 84.31 83.68 92.99 } +2026-10-17T17:08:36Z thinkpad: 6.73 6.57 7.51 | macmini (bots): { 81.04 82.99 92.42 } +2026-10-17T17:09:06Z thinkpad: 6.12 6.43 7.44 | macmini (bots): { 86.55 83.77 92.35 } +2026-10-17T17:09:36Z thinkpad: 6.77 6.58 7.46 | macmini (bots): { 95.19 86.31 92.99 } +2026-10-17T17:10:07Z thinkpad: 7.13 6.68 7.46 | macmini (bots): { 111.30 91.11 94.50 } +2026-10-17T17:10:37Z thinkpad: 5.09 6.23 7.29 | macmini (bots): { 118.51 95.17 95.87 } +2026-10-17T17:11:07Z thinkpad: 4.00 5.86 7.13 | macmini (bots): { 121.12 98.01 96.88 } +2026-10-17T17:11:38Z thinkpad: 3.50 5.57 6.99 | macmini (bots): { 109.57 97.67 96.81 } +2026-10-17T17:12:08Z thinkpad: 2.92 5.22 6.83 | macmini (bots): { 108.43 98.44 97.11 } +2026-10-17T17:12:38Z thinkpad: 3.42 5.12 6.74 | macmini (bots): { 101.61 97.86 96.95 } +2026-10-17T17:13:09Z thinkpad: 5.64 5.51 6.82 | macmini (bots): { 101.66 98.17 97.09 } +2026-10-17T17:13:39Z thinkpad: 7.06 5.89 6.91 | macmini (bots): { 88.43 95.36 96.11 } +2026-10-17T17:14:09Z thinkpad: 7.61 6.13 6.96 | macmini (bots): { 79.03 92.54 95.07 } +2026-10-17T17:14:39Z thinkpad: 9.06 6.68 7.12 | macmini (bots): { 92.55 94.57 95.72 } +2026-10-17T17:15:10Z thinkpad: 9.81 7.06 7.22 | macmini (bots): { 93.71 94.49 95.64 } +2026-10-17T17:15:40Z thinkpad: 9.98 7.41 7.34 | macmini (bots): { 92.26 93.86 95.35 } +2026-10-17T17:16:10Z thinkpad: 7.60 7.08 7.23 | macmini (bots): { 88.61 92.91 94.96 } +2026-10-17T17:16:40Z thinkpad: 6.81 6.93 7.17 | macmini (bots): { 96.96 94.47 95.45 } +2026-10-17T17:17:11Z thinkpad: 6.31 6.81 7.12 | macmini (bots): { 102.92 96.14 96.02 } +2026-10-17T17:17:41Z thinkpad: 4.81 6.38 6.97 | macmini (bots): { 91.20 94.16 95.32 } +2026-10-17T17:18:11Z thinkpad: 7.36 6.81 7.09 | macmini (bots): { 93.60 94.31 95.32 } +2026-10-17T17:18:41Z thinkpad: 9.42 7.38 7.27 | macmini (bots): { 90.86 93.57 95.02 } +2026-10-17T17:19:11Z thinkpad: 9.95 7.72 7.39 | macmini (bots): { 88.94 92.94 94.75 } +2026-10-17T17:19:42Z thinkpad: 9.51 7.85 7.45 | macmini (bots): { 94.97 93.93 95.03 } +2026-10-17T17:20:12Z thinkpad: 8.97 7.90 7.48 | macmini (bots): { 80.46 90.39 93.71 } +2026-10-17T17:20:42Z thinkpad: 7.56 7.65 7.41 | macmini (bots): { 74.38 87.95 92.71 } +2026-10-17T17:21:12Z thinkpad: 6.39 7.36 7.32 | macmini (bots): { 77.48 87.26 92.28 } +2026-10-17T17:21:43Z thinkpad: 5.21 6.98 7.19 | macmini (bots): { 82.05 87.48 92.19 } +2026-10-17T17:22:13Z thinkpad: 3.87 6.49 7.02 | macmini (bots): { 88.15 88.45 92.38 } +2026-10-17T17:22:43Z thinkpad: 3.86 6.22 6.91 | macmini (bots): { 100.23 91.12 93.19 } +2026-10-17T17:23:13Z thinkpad: 8.32 7.05 7.16 | macmini (bots): { 84.55 88.39 92.15 } +2026-10-17T17:23:43Z thinkpad: 13.84 8.37 7.59 | macmini (bots): { 73.74 85.38 90.92 } +2026-10-17T17:24:14Z thinkpad: 21.02 10.71 8.40 | macmini (bots): { 71.36 83.72 90.13 } +2026-10-17T17:24:44Z thinkpad: 20.73 11.82 8.85 | macmini (bots): { 82.27 85.04 90.38 } +2026-10-17T17:25:14Z thinkpad: 16.80 11.77 8.94 | macmini (bots): { 78.63 83.92 89.78 } +2026-10-17T17:25:44Z thinkpad: 14.62 11.68 8.99 | macmini (bots): { 82.33 84.06 89.61 } +2026-10-17T17:26:15Z thinkpad: 14.51 11.94 9.17 | macmini (bots): { 74.13 81.89 88.63 } +2026-10-17T17:26:45Z thinkpad: 12.48 11.74 9.20 | macmini (bots): { 75.65 81.46 88.24 } +2026-10-17T17:27:15Z thinkpad: 15.24 12.56 9.56 | macmini (bots): { 71.35 79.78 87.35 } +2026-10-17T17:27:45Z thinkpad: 15.70 12.87 9.76 | macmini (bots): { 68.21 78.17 86.51 } +2026-10-17T17:28:16Z thinkpad: 12.80 12.47 9.72 | macmini (bots): { 79.74 80.10 86.92 } +2026-10-17T17:28:46Z thinkpad: 9.05 11.58 9.51 | macmini (bots): { 101.01 85.27 88.56 } +2026-10-17T17:29:16Z thinkpad: 9.38 11.41 9.53 | macmini (bots): { 93.76 85.18 88.43 } +2026-10-17T17:29:46Z thinkpad: 11.08 11.62 9.65 | macmini (bots): { 74.91 81.56 87.01 } +2026-10-17T17:30:17Z thinkpad: 10.98 11.53 9.69 | macmini (bots): { 61.10 77.50 85.34 } +2026-10-17T17:30:47Z thinkpad: 9.83 11.21 9.64 | macmini (bots): { 51.19 73.56 83.64 } +2026-10-17T17:31:18Z thinkpad: 9.65 11.03 9.63 | macmini (bots): { 49.64 71.03 82.37 } +2026-10-17T17:31:48Z thinkpad: 7.22 10.33 9.44 | macmini (bots): { 53.62 69.90 81.56 } +2026-10-17T17:32:18Z thinkpad: 5.79 9.68 9.25 | macmini (bots): { 61.07 70.36 81.34 } +2026-10-17T17:32:48Z thinkpad: 3.70 8.80 8.97 | macmini (bots): { 60.39 69.24 80.55 } +2026-10-17T17:33:19Z thinkpad: 2.72 8.08 8.73 | macmini (bots): { 57.06 67.51 79.53 } +2026-10-17T17:33:49Z thinkpad: 1.97 7.37 8.47 | macmini (bots): { 65.72 68.41 79.42 } +2026-10-17T17:34:19Z thinkpad: 1.25 6.68 8.20 | macmini (bots): { 62.60 67.40 78.67 } +2026-10-17T17:34:49Z thinkpad: 0.94 6.09 7.96 | macmini (bots): { 71.83 69.24 78.95 } +2026-10-17T17:35:20Z thinkpad: 0.72 5.54 7.71 | macmini (bots): { 66.16 68.07 78.19 } +2026-10-17T17:35:50Z thinkpad: 0.44 5.01 7.47 | macmini (bots): { 70.96 68.91 78.13 } +2026-10-17T17:36:20Z thinkpad: 1.70 4.79 7.30 | macmini (bots): { 79.74 71.45 78.74 } +2026-10-17T17:36:50Z thinkpad: 3.03 4.80 7.22 | macmini (bots): { 79.71 72.75 78.95 } +2026-10-17T17:37:21Z thinkpad: 3.07 4.67 7.10 | macmini (bots): { 85.13 74.60 79.40 } +2026-10-17T17:37:51Z thinkpad: 2.32 4.33 6.91 | macmini (bots): { 84.85 75.70 79.64 } +2026-10-17T17:38:21Z thinkpad: 1.83 4.03 6.73 | macmini (bots): { 86.47 76.79 79.88 } +2026-10-17T17:38:51Z thinkpad: 1.11 3.64 6.51 | macmini (bots): { 106.96 82.74 81.94 } +2026-10-17T17:39:22Z thinkpad: 1.03 3.37 6.33 | macmini (bots): { 114.52 87.01 83.52 } +2026-10-17T17:39:52Z thinkpad: 1.11 3.16 6.16 | macmini (bots): { 103.99 87.05 83.65 } +2026-10-17T17:40:22Z thinkpad: 1.31 3.02 6.02 | macmini (bots): { 100.27 87.59 83.95 } +2026-10-17T17:40:52Z thinkpad: 1.36 2.87 5.87 | macmini (bots): { 98.17 88.44 84.40 } +2026-10-17T17:41:22Z thinkpad: 2.01 2.88 5.78 | macmini (bots): { 96.27 88.67 84.60 } +2026-10-17T17:41:53Z thinkpad: 1.96 2.77 5.65 | macmini (bots): { 96.31 89.44 85.03 } +2026-10-17T17:42:23Z thinkpad: 3.06 2.97 5.62 | macmini (bots): { 80.49 86.30 84.04 } +2026-10-17T17:42:53Z thinkpad: 2.38 2.81 5.49 | macmini (bots): { 66.40 82.24 82.64 } +2026-10-17T17:43:24Z thinkpad: 2.44 2.81 5.40 | macmini (bots): { 56.70 78.37 81.22 } +2026-10-17T17:43:54Z thinkpad: 1.93 2.65 5.26 | macmini (bots): { 61.56 77.39 80.77 } +2026-10-17T17:44:24Z thinkpad: 1.96 2.59 5.16 | macmini (bots): { 58.25 75.14 79.83 } +2026-10-17T17:44:54Z thinkpad: 2.25 2.60 5.08 | macmini (bots): { 56.32 73.21 78.98 } +2026-10-17T17:45:24Z thinkpad: 1.79 2.46 4.95 | macmini (bots): { 62.87 73.14 78.75 } +2026-10-17T17:45:55Z thinkpad: 2.78 2.64 4.93 | macmini (bots): { 62.58 72.22 78.23 } +2026-10-17T17:46:25Z thinkpad: 4.82 3.14 5.03 | macmini (bots): { 58.89 70.44 77.38 } +2026-10-17T17:46:55Z thinkpad: 3.10 2.90 4.88 | macmini (bots): { 61.68 70.08 77.01 } +2026-10-17T17:47:25Z thinkpad: 2.27 2.71 4.75 | macmini (bots): { 70.43 71.40 77.25 } +2026-10-17T17:47:56Z thinkpad: 1.71 2.53 4.62 | macmini (bots): { 70.51 71.56 77.12 } +2026-10-17T17:48:26Z thinkpad: 1.59 2.42 4.52 | macmini (bots): { 68.98 70.98 76.71 } +2026-10-17T17:48:56Z thinkpad: 2.09 2.47 4.47 | macmini (bots): { 67.75 70.60 76.38 } +2026-10-17T17:49:26Z thinkpad: 2.14 2.44 4.39 | macmini (bots): { 61.53 69.01 75.58 } +2026-10-17T17:49:56Z thinkpad: 2.22 2.43 4.33 | macmini (bots): { 58.49 67.45 74.78 } +2026-10-17T17:50:27Z thinkpad: 1.98 2.36 4.24 | macmini (bots): { 66.15 68.33 74.84 } +2026-10-17T17:50:57Z thinkpad: 2.38 2.42 4.20 | macmini (bots): { 61.65 67.22 74.22 } +2026-10-17T17:51:27Z thinkpad: 3.62 2.72 4.24 | macmini (bots): { 54.05 64.88 73.13 } +2026-10-17T17:51:57Z thinkpad: 3.25 2.70 4.19 | macmini (bots): { 49.14 62.62 72.02 } +2026-10-17T17:52:28Z thinkpad: 2.45 2.55 4.09 | macmini (bots): { 43.72 60.06 70.77 } +2026-10-17T17:52:58Z thinkpad: 2.85 2.62 4.06 | macmini (bots): { 42.53 58.22 69.73 } +2026-10-17T17:53:28Z thinkpad: 8.44 3.97 4.46 | macmini (bots): { 45.21 57.34 69.01 } +2026-10-17T17:53:58Z thinkpad: 10.75 4.91 4.76 | macmini (bots): { 44.86 56.01 68.11 } +2026-10-17T17:54:29Z thinkpad: 8.36 4.90 4.76 | macmini (bots): { 51.73 56.60 67.91 } +2026-10-17T17:54:59Z thinkpad: 7.41 4.98 4.79 | macmini (bots): { 55.80 57.05 67.67 } +2026-10-17T17:55:29Z thinkpad: 5.45 4.73 4.71 | macmini (bots): { 50.40 55.67 66.81 } +2026-10-17T17:55:59Z thinkpad: 6.26 4.97 4.79 | macmini (bots): { 57.22 56.88 66.87 } +2026-10-17T17:56:30Z thinkpad: 8.22 5.52 4.98 | macmini (bots): { 48.94 54.86 65.78 } +2026-10-17T17:57:00Z thinkpad: 6.71 5.42 4.96 | macmini (bots): { 50.54 54.70 65.35 } +2026-10-17T17:57:30Z thinkpad: 4.94 5.14 4.89 | macmini (bots): { 58.02 56.25 65.55 } +2026-10-17T17:58:01Z thinkpad: 4.54 5.04 4.86 | macmini (bots): { 53.98 55.38 64.90 } +2026-10-17T17:58:31Z thinkpad: 4.65 5.04 4.87 | macmini (bots): { 49.96 54.23 64.16 } +2026-10-17T17:59:01Z thinkpad: 5.29 5.16 4.92 | macmini (bots): { 49.63 53.68 63.61 } +2026-10-17T17:59:31Z thinkpad: 4.23 4.94 4.85 | macmini (bots): { 57.15 55.10 63.78 } +2026-10-17T18:00:01Z thinkpad: 3.57 4.72 4.78 | macmini (bots): { 61.70 56.26 63.89 } +2026-10-17T18:00:32Z thinkpad: 3.16 4.52 4.71 | macmini (bots): { 62.10 56.86 63.79 } +2026-10-17T18:01:02Z thinkpad: 2.81 4.29 4.63 | macmini (bots): { 76.29 60.79 64.98 } +2026-10-17T18:01:32Z thinkpad: 7.77 5.26 4.93 | macmini (bots): { 75.36 62.16 65.34 } +2026-10-17T18:02:02Z thinkpad: 11.60 6.45 5.34 | macmini (bots): { 70.83 62.28 65.27 } +2026-10-17T18:02:33Z thinkpad: 11.54 6.97 5.56 | macmini (bots): { 65.66 61.87 65.01 } +2026-10-17T18:03:03Z thinkpad: 10.80 7.33 5.73 | macmini (bots): { 63.09 61.54 64.78 } +2026-10-17T18:03:33Z thinkpad: 10.52 7.56 5.85 | macmini (bots): { 60.31 61.12 64.52 } +2026-10-17T18:04:04Z thinkpad: 10.27 7.76 5.97 | macmini (bots): { 60.99 61.21 64.44 } +2026-10-17T18:04:34Z thinkpad: 8.77 7.69 6.01 | macmini (bots): { 56.72 60.19 63.96 } +2026-10-17T18:05:05Z thinkpad: 5.77 7.06 5.85 | macmini (bots): { 56.14 59.70 63.65 } +2026-10-17T18:05:35Z thinkpad: 5.16 6.79 5.80 | macmini (bots): { 51.25 58.17 62.95 } +2026-10-17T18:06:05Z thinkpad: 4.16 6.36 5.69 | macmini (bots): { 52.03 57.64 62.59 } +2026-10-17T18:06:35Z thinkpad: 4.28 6.18 5.65 | macmini (bots): { 64.66 60.00 63.27 } +2026-10-17T18:07:06Z thinkpad: 7.47 6.76 5.86 | macmini (bots): { 56.20 58.45 62.59 } +2026-10-17T18:07:36Z thinkpad: 6.95 6.74 5.89 | macmini (bots): { 51.92 57.20 62.00 } +2026-10-17T18:08:06Z thinkpad: 7.70 6.99 6.00 | macmini (bots): { 51.14 56.65 61.64 } +2026-10-17T18:08:36Z thinkpad: 5.83 6.60 5.90 | macmini (bots): { 48.08 55.33 60.98 } +2026-10-17T18:09:07Z thinkpad: 4.89 6.30 5.82 | macmini (bots): { 53.80 56.00 61.00 } +2026-10-17T18:09:37Z thinkpad: 4.93 6.19 5.80 | macmini (bots): { 60.49 57.24 61.27 } +2026-10-17T18:10:07Z thinkpad: 4.61 5.98 5.74 | macmini (bots): { 58.95 57.21 61.12 } +2026-10-17T18:10:37Z thinkpad: 4.74 5.91 5.73 | macmini (bots): { 60.84 57.65 61.13 } +2026-10-17T18:11:07Z thinkpad: 3.96 5.61 5.63 | macmini (bots): { 64.23 58.82 61.43 } +2026-10-17T18:11:38Z thinkpad: 4.16 5.53 5.61 | macmini (bots): { 75.59 62.26 62.60 } +2026-10-17T18:12:08Z thinkpad: 2.97 5.11 5.46 | macmini (bots): { 75.25 63.65 63.10 } diff --git a/benchmarks/server-2026-10-17/walk-explore.json b/benchmarks/server-2026-10-17/walk-explore.json new file mode 100644 index 000000000..a9479f455 --- /dev/null +++ b/benchmarks/server-2026-10-17/walk-explore.json @@ -0,0 +1,695 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T17:31:40+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "7bbbf6e97fb53683eae0a01ce2c134e53cb649a7", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 180, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "/home/ludovic/code/horizon/.claude/worktrees/server-host-4/.local/bench-out/walk-explore.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "/Users/ludovicmarie/code/horizon/.claude/worktrees/server-host-4/target/release/horizon-bots", + "connect": "", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 9.62, + "mspt": { + "average": 4.01, + "p50": 3.54, + "p95": 8.19, + "p99": 25.59 + }, + "mspt_worst_p99": 47.5, + "tps": 20.0, + "rss_mb": { + "mean": 782.52, + "max": 785.3 + }, + "cpu_percent": 58.87, + "chunks_per_second": 9.6, + "unique_per_second": 0.43, + "forgotten_per_second": 9.65, + "waited_ticks_per_second": 0.0, + "chunks_total": 2697, + "chunks_per_bot": { + "walk": 2697.0 + }, + "unique_chunks_per_bot": { + "walk": 693.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 14.85, + "mspt": { + "average": 18.22, + "p50": 17.99, + "p95": 29.34, + "p99": 50.06 + }, + "mspt_worst_p99": 395.5, + "tps": 20.0, + "rss_mb": { + "mean": 3429.06, + "max": 3446.3 + }, + "cpu_percent": 68.81, + "chunks_per_second": 10.47, + "unique_per_second": 0.47, + "forgotten_per_second": 10.53, + "waited_ticks_per_second": 0.0, + "chunks_total": 2755, + "chunks_per_bot": { + "walk": 2755.0 + }, + "unique_chunks_per_bot": { + "walk": 697.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 9.21, + "mspt": { + "average": 8.79, + "p50": 8.05, + "p95": 17.35, + "p99": 30.47 + }, + "mspt_worst_p99": 48.8, + "tps": 20.0, + "rss_mb": { + "mean": 781.88, + "max": 782.8 + }, + "cpu_percent": 119.16, + "chunks_per_second": 94.63, + "unique_per_second": 3.58, + "forgotten_per_second": 94.31, + "waited_ticks_per_second": 0.0, + "chunks_total": 26003, + "chunks_per_bot": { + "walk": 2600.3 + }, + "unique_chunks_per_bot": { + "walk": 679.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 15.14, + "mspt": { + "average": 18.67, + "p50": 15.8, + "p95": 38.26, + "p99": 55.93 + }, + "mspt_worst_p99": 101.8, + "tps": 20.0, + "rss_mb": { + "mean": 3497.35, + "max": 3499.4 + }, + "cpu_percent": 100.8, + "chunks_per_second": 101.1, + "unique_per_second": 4.38, + "forgotten_per_second": 101.15, + "waited_ticks_per_second": 0.0, + "chunks_total": 26537, + "chunks_per_bot": { + "walk": 2653.7 + }, + "unique_chunks_per_bot": { + "walk": 687.5 + }, + "resent": 0, + "pulled_back": 5, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 9.82, + "mspt": { + "average": 15.01, + "p50": 13.12, + "p95": 31.12, + "p99": 50.62 + }, + "mspt_worst_p99": 101.6, + "tps": 20.0, + "rss_mb": { + "mean": 799.52, + "max": 799.7 + }, + "cpu_percent": 161.02, + "chunks_per_second": 234.3, + "unique_per_second": 8.49, + "forgotten_per_second": 234.35, + "waited_ticks_per_second": 0.0, + "chunks_total": 65926, + "chunks_per_bot": { + "walk": 2637.04 + }, + "unique_chunks_per_bot": { + "walk": 683.96 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.95, + "mspt": { + "average": 18.78, + "p50": 17.47, + "p95": 28.16, + "p99": 51.03 + }, + "mspt_worst_p99": 107.6, + "tps": 20.0, + "rss_mb": { + "mean": 3520.17, + "max": 3573.8 + }, + "cpu_percent": 154.9, + "chunks_per_second": 252.39, + "unique_per_second": 11.89, + "forgotten_per_second": 251.75, + "waited_ticks_per_second": 0.0, + "chunks_total": 66469, + "chunks_per_bot": { + "walk": 2658.76 + }, + "unique_chunks_per_bot": { + "walk": 689.68 + }, + "resent": 0, + "pulled_back": 10, + "moved_too_quickly": 10, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 9.52, + "mspt": { + "average": 22.72, + "p50": 16.98, + "p95": 60.19, + "p99": 84.16 + }, + "mspt_worst_p99": 105.4, + "tps": 20.0, + "rss_mb": { + "mean": 813.5, + "max": 815.8 + }, + "cpu_percent": 179.85, + "chunks_per_second": 464.75, + "unique_per_second": 16.94, + "forgotten_per_second": 464.69, + "waited_ticks_per_second": 0.0, + "chunks_total": 134839, + "chunks_per_bot": { + "walk": 2696.78 + }, + "unique_chunks_per_bot": { + "walk": 685.48 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 16.36, + "mspt": { + "average": 34.3, + "p50": 31.07, + "p95": 55.55, + "p99": 92.32 + }, + "mspt_worst_p99": 452.1, + "tps": 20.0, + "rss_mb": { + "mean": 3577.02, + "max": 3611.2 + }, + "cpu_percent": 267.05, + "chunks_per_second": 496.77, + "unique_per_second": 26.74, + "forgotten_per_second": 496.2, + "waited_ticks_per_second": 0.0, + "chunks_total": 133505, + "chunks_per_bot": { + "walk": 2670.1 + }, + "unique_chunks_per_bot": { + "walk": 688.8 + }, + "resent": 0, + "pulled_back": 39, + "moved_too_quickly": 39, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 9.51, + "mspt": { + "average": 63.33, + "p50": 58.89, + "p95": 125.04, + "p99": 175.12 + }, + "mspt_worst_p99": 261.5, + "tps": 15.79, + "rss_mb": { + "mean": 868.12, + "max": 869.9 + }, + "cpu_percent": 245.64, + "chunks_per_second": 678.18, + "unique_per_second": 31.8, + "forgotten_per_second": 676.4, + "waited_ticks_per_second": 0.0, + "chunks_total": 219787, + "chunks_per_bot": { + "walk": 2197.87 + }, + "unique_chunks_per_bot": { + "walk": 637.91 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 34 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.14, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 9.72, + "mspt": { + "average": 9.73, + "p50": 8.75, + "p95": 20.99, + "p99": 34.17 + }, + "mspt_worst_p99": 73.9, + "tps": 20.0, + "rss_mb": { + "mean": 836.18, + "max": 891.0 + }, + "cpu_percent": 329.64, + "chunks_per_second": 41.11, + "unique_per_second": 35.96, + "forgotten_per_second": 41.08, + "waited_ticks_per_second": 0.16, + "chunks_total": 9460, + "chunks_per_bot": { + "explore": 9460.0 + }, + "unique_chunks_per_bot": { + "explore": 8479.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.54, + "mspt": { + "average": 9.71, + "p50": 7.86, + "p95": 20.37, + "p99": 76.15 + }, + "mspt_worst_p99": 388.6, + "tps": 20.0, + "rss_mb": { + "mean": 3614.97, + "max": 3688.5 + }, + "cpu_percent": 247.15, + "chunks_per_second": 35.47, + "unique_per_second": 33.61, + "forgotten_per_second": 35.45, + "waited_ticks_per_second": 0.0, + "chunks_total": 7912, + "chunks_per_bot": { + "explore": 7912.0 + }, + "unique_chunks_per_bot": { + "explore": 7580.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 21.27, + "p50": 19.5, + "p95": 39.15, + "p99": 54.23 + }, + "mspt_worst_p99": 105.5, + "tps": 20.0, + "rss_mb": { + "mean": 1177.66, + "max": 1392.9 + }, + "cpu_percent": 321.97, + "chunks_per_second": 46.47, + "unique_per_second": 46.11, + "forgotten_per_second": 43.12, + "waited_ticks_per_second": 111.25, + "chunks_total": 14103, + "chunks_per_bot": { + "explore": 1410.3 + }, + "unique_chunks_per_bot": { + "explore": 1402.4 + }, + "resent": 0, + "pulled_back": 9856, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.24, + "mspt": { + "average": 16.94, + "p50": 14.24, + "p95": 30.28, + "p99": 109.7 + }, + "mspt_worst_p99": 1861.2, + "tps": 20.0, + "rss_mb": { + "mean": 3953.29, + "max": 4232.0 + }, + "cpu_percent": 254.11, + "chunks_per_second": 24.99, + "unique_per_second": 25.01, + "forgotten_per_second": 25.33, + "waited_ticks_per_second": 77.93, + "chunks_total": 7707, + "chunks_per_bot": { + "explore": 770.7 + }, + "unique_chunks_per_bot": { + "explore": 769.5 + }, + "resent": 0, + "pulled_back": 11123, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 9.92, + "mspt": { + "average": 25.76, + "p50": 23.58, + "p95": 45.01, + "p99": 61.43 + }, + "mspt_worst_p99": 108.8, + "tps": 20.0, + "rss_mb": { + "mean": 1172.1, + "max": 1482.3 + }, + "cpu_percent": 314.47, + "chunks_per_second": 61.38, + "unique_per_second": 60.7, + "forgotten_per_second": 55.11, + "waited_ticks_per_second": 304.54, + "chunks_total": 24085, + "chunks_per_bot": { + "explore": 963.4 + }, + "unique_chunks_per_bot": { + "explore": 954.76 + }, + "resent": 0, + "pulled_back": 31264, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 15.76, + "mspt": { + "average": 24.93, + "p50": 22.04, + "p95": 37.09, + "p99": 168.46 + }, + "mspt_worst_p99": 1724.8, + "tps": 20.0, + "rss_mb": { + "mean": 4040.42, + "max": 4447.6 + }, + "cpu_percent": 305.47, + "chunks_per_second": 37.91, + "unique_per_second": 37.84, + "forgotten_per_second": 38.39, + "waited_ticks_per_second": 258.66, + "chunks_total": 16865, + "chunks_per_bot": { + "explore": 674.6 + }, + "unique_chunks_per_bot": { + "explore": 671.28 + }, + "resent": 0, + "pulled_back": 33467, + "moved_too_quickly": 23, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 9.41, + "mspt": { + "average": 39.31, + "p50": 36.98, + "p95": 65.33, + "p99": 88.36 + }, + "mspt_worst_p99": 157.6, + "tps": 20.0, + "rss_mb": { + "mean": 1250.32, + "max": 1517.1 + }, + "cpu_percent": 324.77, + "chunks_per_second": 114.99, + "unique_per_second": 112.25, + "forgotten_per_second": 104.41, + "waited_ticks_per_second": 543.77, + "chunks_total": 50402, + "chunks_per_bot": { + "explore": 1008.04 + }, + "unique_chunks_per_bot": { + "explore": 997.42 + }, + "resent": 0, + "pulled_back": 64163, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.55, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 9.31, + "mspt": { + "average": 52.7, + "p50": 49.49, + "p95": 85.73, + "p99": 115.34 + }, + "mspt_worst_p99": 219.0, + "tps": 18.97, + "rss_mb": { + "mean": 1358.32, + "max": 3047.2 + }, + "cpu_percent": 327.95, + "chunks_per_second": 154.2, + "unique_per_second": 151.83, + "forgotten_per_second": 141.65, + "waited_ticks_per_second": 1132.9, + "chunks_total": 84433, + "chunks_per_bot": { + "explore": 844.33 + }, + "unique_chunks_per_bot": { + "explore": 839.47 + }, + "resent": 0, + "pulled_back": 116161, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 35 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 16.47, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/README.md b/benchmarks/server-equal-work-2026-10-17/README.md new file mode 100644 index 000000000..737b05858 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/README.md @@ -0,0 +1,168 @@ +# Horizon's server against vanilla 26.3, equal work (2026-10-17) + +The same bots on Horizon's dedicated server and on vanilla 26.3's, one server at a time, on the same +machine, with the work each server does made the same before the numbers are compared. This replaces the +first run in docs/server.md section 9, where the work wasn't equal. + +## What was made equal + +The first run (PR #556) had three differences that made the comparison unfair. Each is fixed in the code +that ran here: + +- **Refused moves.** Vanilla pulls a player back when a move is too fast ("moved too quickly") or ends + inside a block ("moved wrongly"). Horizon now runs both checks the way vanilla does (PR #586), so a bot + that flies too fast is pulled back on both servers. +- **Chunk sending.** Vanilla paces chunks by the client's acknowledgements (PlayerChunkSender: one + unacknowledged batch at first, then ten, each at most the client's desired chunks per tick). Horizon used + to send twice as many per batch; it now paces them the same way (PR #586), and the bots acknowledge + batches and ask for a rate the way vanilla's client does, so both servers send at the pace the client + asks for. Chunks sent again while the bot still held + them (`resent`) are counted: 0 on both servers in every run. +- **Movement gated on chunks.** A bot doesn't move while the chunk it stands in hasn't arrived (vanilla's + client waits the same way), so a slower server isn't asked to teleport bots into terrain it hasn't sent. + +One difference isn't in Horizon yet: vanilla 26.3's locator bar (waypoints), which costs vanilla O(players²) +work per move. Every vanilla run here sets `gamerule locator_bar false`, so neither server does it. + +## Method + +`tools/server_bench.py` runs each configuration on a fresh server: + +- the same `server.properties` on both (seed 12345, view and simulation distance 10, offline, creative, + difficulty easy, `sync-chunk-writes=true`), and `gamerule respawn_radius 0`; +- the server waits for `Done`, the bots join one a second, a 60-second warm-up, then 300 seconds of + measurement; +- MSPT (average, P50, P95, P99) comes from each server's own `/tick query`, asked every 5 seconds on the + console, so both measure themselves the same way (vanilla's ServerTickRateManager numbers, which Horizon + reproduces); TPS is 20 while the average fits in 50 ms, else 1000 / MSPT; +- RSS and CPU are the server's whole process tree, once a second (100 % is one core); +- chunk counts come from the bots: chunks received per second, chunks no bot had before (new terrain), and + pull-backs (position packets that move a bot back). + +The bots are `horizon-bots` (creative, flying 24 blocks above spawn, 20 moves a second): + +- `walk`: flies to random points within 48 blocks of spawn at sprint speed (5.6 blocks a second); +- `explore`: flies straight outwards, by default at about 22 blocks a second, as fast as the server sends + chunks. + +Machine: the ThinkPad (Intel Core i7-7500U, 2 cores / 4 threads, 32 GB, NixOS), servers under `nice -n 19` +because it also runs other services; vanilla on OpenJDK 25.0.4.1 with a 4 GB heap (`-Xms4g -Xmx4g`). The +bots ran on the Mac mini and reached the ThinkPad over the tailnet, so they took none of the server's CPU. + +What ran: Horizon from `origin/main` at bf851bfe with #586 (move checks and chunk pacing), the bots and +`server_bench.py` from this PR, #623 (sections encoded once, its first commit) and #649 (a tick's packets +handed to each connection together). The ThinkPad copy wasn't a git checkout, so the JSON reports have an +empty `commit`. Vanilla: the pinned 26.3 server jar. + +## Results + +MSPT is the average milliseconds per tick (50 is the limit for 20 TPS); P95 is the 95th percentile. CPU is +the whole process tree. "New chunks/s" are chunks no bot had before. + +### Walk (the same work on both servers) + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 5.5 | 12.1 | 20.0 | 1.37 GB | 57 % | 9 | 0.3 | +| 1 | Vanilla | 18.3 | 27.3 | 20.0 | 3.35 GB | 66 % | 10 | 0.3 | +| 10 | Horizon | 11.5 | 22.1 | 20.0 | 1.41 GB | 124 % | 94 | 2.4 | +| 10 | Vanilla | 16.8 | 30.5 | 20.0 | 3.41 GB | 84 % | 100 | 2.8 | +| 25 | Horizon | 20.7 | 40.4 | 20.0 | 1.45 GB | 170 % | 236 | 5.7 | +| 25 | Vanilla | 16.0 | 26.4 | 20.0 | 3.47 GB | 115 % | 252 | 6.7 | +| 50 | Horizon | 31.4 | 79.0 | 20.0 | 1.52 GB | 173 % | 451 | 10.3 | +| 50 | Vanilla | 20.5 | 29.7 | 20.0 | 3.55 GB | 194 % | 502 | 12.2 | +| 100 | Horizon | 114.5 | 256.2 | 8.7 | 1.33 GB | 181 % | 484 | 30.8 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Both servers sent the same chunks (about 10 a second per bot, the churn of flying around) and sent none +twice. Vanilla pulled back a few bots for moving too quickly when a tick ran long (5 to 33 per run); +Horizon none. At 100 bots vanilla's watchdog stopped the server (a tick ran over 60 s, in +`ChunkMap$TrackedEntity.updatePlayer`); Horizon kept running at 8.7 TPS. + +### Explore at a rate both servers keep up with (equal work) + +The bots fly outwards at 0.8 blocks a second (`--explore-speed 0.8`), slow enough that neither server makes +them wait for terrain, so both generate and send the same new chunks. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 4.0 | 6.6 | 20.0 | 1.36 GB | 25 % | 2 | 1.3 | +| 1 | Vanilla | 18.1 | 27.1 | 20.0 | 3.32 GB | 73 % | 2 | 1.4 | +| 10 | Horizon | 13.5 | 24.8 | 20.0 | 1.64 GB | 89 % | 13 | 11.8 | +| 10 | Vanilla | 29.2 | 43.0 | 20.0 | 3.52 GB | 143 % | 13 | 11.9 | +| 25 | Horizon | 20.2 | 36.8 | 20.0 | 1.74 GB | 121 % | 32 | 28.9 | +| 25 | Vanilla | 37.0 | 49.4 | 20.0 | 3.73 GB | 169 % | 32 | 28.9 | + +### Explore as fast as each server sends chunks (not equal work) + +The default 22 blocks a second is faster than either server can generate, so each server sets the pace and +a faster server is given more work: from 10 bots Horizon generated 1.5 to 2 times vanilla's new chunks a +second. Read it as throughput, not as a like-for-like tick time. + +| Bots | Server | MSPT | P95 | TPS | RSS | CPU | Chunks/s | New chunks/s | +|---:|---|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | 10.6 | 24.6 | 20.0 | 1.34 GB | 322 % | 39 | 34.6 | +| 1 | Vanilla | 9.9 | 21.3 | 20.0 | 3.48 GB | 245 % | 36 | 33.4 | +| 10 | Horizon | 30.4 | 52.3 | 20.0 | 2.18 GB | 345 % | 47 | 46.7 | +| 10 | Vanilla | 17.0 | 29.6 | 20.0 | 4.04 GB | 242 % | 22 | 22.4 | +| 25 | Horizon | 50.7 | 89.3 | 19.7 | 2.30 GB | 286 % | 50 | 49.7 | +| 25 | Vanilla | 24.2 | 36.5 | 20.0 | 4.40 GB | 320 % | 34 | 33.7 | +| 50 | Horizon | 50.7 | 102.7 | 19.7 | 1.72 GB | 213 % | 97 | 96.5 | +| 50 | Vanilla | stopped by its watchdog | | | | | | | +| 100 | Horizon | 92.9 | 139.6 | 10.8 | 1.70 GB | 322 % | 114 | 113.6 | +| 100 | Vanilla | stopped by its watchdog | | | | | | | + +Vanilla's watchdog stopped it at 50 bots (in `ClientboundLightUpdatePacketData`, copying light for a chunk +packet) and at 100 (in `Entity.move` from a move packet). + +## Findings + +- Horizon's RSS is 1.9 to 2.6 times smaller in every run, and it starts in 11 s against vanilla's 15 s. + Vanilla's heap is fixed at 4 GB (`-Xms4g`), so part of its RSS is that setting rather than need. +- With 1 bot Horizon's tick is 3.3 times shorter walking and 4.5 times shorter exploring at equal work; + at 10 bots it is still shorter in both. +- At equal exploring work Horizon's tick is about half of vanilla's at 10 and 25 bots. +- When the bots only fly around spawn (`walk`), vanilla's tick hardly grows with players (16 to 20 ms from + 1 to 50 bots) while Horizon's grows by about 0.5 ms per bot, so vanilla is ahead from about 20 bots: 16.0 + against 20.7 ms at 25 and 20.5 against 31.4 ms at 50. Both keep 20 TPS up to 50. +- With 100 bots vanilla's watchdog stops it in every pass, and Horizon keeps running at 9 to 11 TPS. + +### Where Horizon's walk tick goes at 25 bots + +Profiled on the ThinkPad with `perf` (the server thread, 20 s, self time): + +| Share | What | Whose | +|---:|---|---| +| 18 % | `Streaming::update`: every tick it walks all loaded columns and proto chunks and tests each against every player's area (unloading, dropping protos, finishing and decoration candidates), so the cost grows with players times chunks | streaming / engine tick | +| 20 % | `PalettedContainer::get` and `World::block`, mostly from block entity ticks: on the Mac profile `tick_hoppers` looks up the block under every block entity in the loaded world each tick and compares names as strings, and spawners rebuild their display id | engine tick | +| 8 % | `light_data` when a chunk is sent: the light layers were built twice per chunk; a follow-up commit on #623 builds them once and keeps each section's packed layers | server (this work) | +| 7 % | encoding chunk sections and heightmaps for the chunks each bot newly sees | server | +| 4 % | `Hub::tick` (moves, tracking) | server | +| 2 % | the moved-wrongly collision check | server | + +The first two grow with the number of players but aren't specific to the server: they are the +engine's tick and streaming, reported to perf-server-2. Before #623 and #649, encoding every chunk section +once per player and waking each connection's writer thread once per packet cost more than everything above +(at 50 walking bots the tick was 281 ms; see the earlier runs). + +## Earlier runs (same machine and method) + +- `run-1-before-chunk-cache.json`: before #623, with vanilla's locator bar on. Horizon's walk tick was + 27.5, 40.7, 281 and 467 ms at 10, 25, 50 and 100 bots, and vanilla's 33.2 ms at 50 (the locator bar). +- `run-2-chunk-cache.json`: Horizon with #623 only: 13.2, 23.5, 31.4 and 84.4 ms walking at 10 to 100 + bots. + +## Files + +- `horizon.json`, `vanilla.json`: the walk and explore passes (vanilla with `locator_bar=false`). +- `explore-equal-rate.json`: the explore pass at 0.8 blocks a second, both servers. +- `run-1-before-chunk-cache.json`, `run-2-chunk-cache.json`: the earlier runs. + +To run it again (bots on another machine reached at `--connect`): + + cargo build --release -p horizon-client --bin horizon-client -p horizon-server -p horizon-bots + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50,100 --behaviour walk,explore \ + --gamerule locator_bar=false --nice 19 --bots-via 'ssh macmini' --bots-bin /path/to/horizon-bots \ + --connect --out results.json + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25 --behaviour explore \ + --explore-speed 0.8 --gamerule locator_bar=false --nice 19 ... --out explore-equal-rate.json diff --git a/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json new file mode 100644 index 000000000..bd097e43a --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/explore-equal-rate.json @@ -0,0 +1,267 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:47:12+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25", + "behaviour": "explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench5.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 10.91, + "mspt": { + "average": 4.02, + "p50": 3.75, + "p95": 6.63, + "p99": 14.55 + }, + "mspt_worst_p99": 63.3, + "tps": 20.0, + "rss_mb": { + "mean": 1392.42, + "max": 1746.1 + }, + "cpu_percent": 24.52, + "chunks_per_second": 1.69, + "unique_per_second": 1.34, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.13, + "mspt": { + "average": 18.12, + "p50": 18.78, + "p95": 27.07, + "p99": 60.81 + }, + "mspt_worst_p99": 1397.6, + "tps": 20.0, + "rss_mb": { + "mean": 3397.31, + "max": 3430.2 + }, + "cpu_percent": 72.99, + "chunks_per_second": 1.69, + "unique_per_second": 1.38, + "forgotten_per_second": 1.62, + "waited_ticks_per_second": 0.0, + "chunks_total": 1048, + "chunks_per_bot": { + "explore": 1048.0 + }, + "unique_chunks_per_bot": { + "explore": 952.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 13.49, + "p50": 12.09, + "p95": 24.81, + "p99": 40.9 + }, + "mspt_worst_p99": 101.4, + "tps": 20.0, + "rss_mb": { + "mean": 1684.04, + "max": 2660.6 + }, + "cpu_percent": 89.04, + "chunks_per_second": 13.08, + "unique_per_second": 11.84, + "forgotten_per_second": 13.02, + "waited_ticks_per_second": 0.0, + "chunks_total": 9277, + "chunks_per_bot": { + "explore": 927.7 + }, + "unique_chunks_per_bot": { + "explore": 889.9 + }, + "resent": 0, + "pulled_back": 3381, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 29.18, + "p50": 26.76, + "p95": 43.02, + "p99": 80.16 + }, + "mspt_worst_p99": 425.5, + "tps": 20.0, + "rss_mb": { + "mean": 3609.51, + "max": 3791.6 + }, + "cpu_percent": 142.79, + "chunks_per_second": 13.1, + "unique_per_second": 11.88, + "forgotten_per_second": 13.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 9245, + "chunks_per_bot": { + "explore": 924.5 + }, + "unique_chunks_per_bot": { + "explore": 885.3 + }, + "resent": 0, + "pulled_back": 3388, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 20.25, + "p50": 18.73, + "p95": 36.78, + "p99": 55.76 + }, + "mspt_worst_p99": 92.3, + "tps": 20.0, + "rss_mb": { + "mean": 1782.26, + "max": 2741.9 + }, + "cpu_percent": 120.8, + "chunks_per_second": 32.22, + "unique_per_second": 28.89, + "forgotten_per_second": 32.19, + "waited_ticks_per_second": 0.0, + "chunks_total": 23357, + "chunks_per_bot": { + "explore": 934.28 + }, + "unique_chunks_per_bot": { + "explore": 890.32 + }, + "resent": 0, + "pulled_back": 11580, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.54, + "mspt": { + "average": 37.04, + "p50": 34.77, + "p95": 49.42, + "p99": 101.67 + }, + "mspt_worst_p99": 735.2, + "tps": 20.0, + "rss_mb": { + "mean": 3815.46, + "max": 4202.0 + }, + "cpu_percent": 169.15, + "chunks_per_second": 32.34, + "unique_per_second": 28.93, + "forgotten_per_second": 32.31, + "waited_ticks_per_second": 0.0, + "chunks_total": 23306, + "chunks_per_bot": { + "explore": 932.24 + }, + "unique_chunks_per_bot": { + "explore": 886.96 + }, + "resent": 0, + "pulled_back": 11539, + "moved_too_quickly": 6, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/horizon.json b/benchmarks/server-equal-work-2026-10-17/horizon.json new file mode 100644 index 000000000..d0b162c44 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/horizon.json @@ -0,0 +1,415 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T05:04:57+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench4.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 5.45, + "p50": 4.63, + "p95": 12.14, + "p99": 30.63 + }, + "mspt_worst_p99": 91.5, + "tps": 20.0, + "rss_mb": { + "mean": 1398.5, + "max": 1708.4 + }, + "cpu_percent": 57.03, + "chunks_per_second": 9.17, + "unique_per_second": 0.26, + "forgotten_per_second": 9.2, + "waited_ticks_per_second": 0.0, + "chunks_total": 3708, + "chunks_per_bot": { + "walk": 3708.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 11.51, + "p50": 10.6, + "p95": 22.13, + "p99": 36.92 + }, + "mspt_worst_p99": 71.9, + "tps": 20.0, + "rss_mb": { + "mean": 1440.2, + "max": 1832.4 + }, + "cpu_percent": 124.19, + "chunks_per_second": 94.04, + "unique_per_second": 2.38, + "forgotten_per_second": 93.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 37269, + "chunks_per_bot": { + "walk": 3726.9 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 20.74, + "p50": 19.27, + "p95": 40.42, + "p99": 57.12 + }, + "mspt_worst_p99": 102.0, + "tps": 20.0, + "rss_mb": { + "mean": 1485.4, + "max": 1871.9 + }, + "cpu_percent": 169.52, + "chunks_per_second": 235.81, + "unique_per_second": 5.68, + "forgotten_per_second": 235.83, + "waited_ticks_per_second": 0.0, + "chunks_total": 94456, + "chunks_per_bot": { + "walk": 3778.24 + }, + "unique_chunks_per_bot": { + "walk": 692.96 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 31.41, + "p50": 25.39, + "p95": 78.97, + "p99": 110.73 + }, + "mspt_worst_p99": 192.9, + "tps": 20.0, + "rss_mb": { + "mean": 1558.34, + "max": 1915.3 + }, + "cpu_percent": 173.27, + "chunks_per_second": 450.85, + "unique_per_second": 10.3, + "forgotten_per_second": 451.86, + "waited_ticks_per_second": 0.0, + "chunks_total": 186885, + "chunks_per_bot": { + "walk": 3737.7 + }, + "unique_chunks_per_bot": { + "walk": 688.9 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 18.16, + "mspt": { + "average": 114.55, + "p50": 101.37, + "p95": 256.19, + "p99": 338.64 + }, + "mspt_worst_p99": 442.6, + "tps": 8.73, + "rss_mb": { + "mean": 1357.65, + "max": 1358.4 + }, + "cpu_percent": 181.21, + "chunks_per_second": 484.16, + "unique_per_second": 30.76, + "forgotten_per_second": 478.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 212947, + "chunks_per_bot": { + "walk": 2129.47 + }, + "unique_chunks_per_bot": { + "walk": 583.02 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 17.45, + "mspt": { + "average": 10.62, + "p50": 9.2, + "p95": 24.61, + "p99": 38.18 + }, + "mspt_worst_p99": 81.1, + "tps": 20.0, + "rss_mb": { + "mean": 1372.73, + "max": 1568.7 + }, + "cpu_percent": 322.38, + "chunks_per_second": 39.21, + "unique_per_second": 34.6, + "forgotten_per_second": 38.55, + "waited_ticks_per_second": 0.51, + "chunks_total": 12549, + "chunks_per_bot": { + "explore": 12549.0 + }, + "unique_chunks_per_bot": { + "explore": 11168.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 30.38, + "p50": 27.84, + "p95": 52.31, + "p99": 77.89 + }, + "mspt_worst_p99": 158.3, + "tps": 20.0, + "rss_mb": { + "mean": 2231.56, + "max": 4022.6 + }, + "cpu_percent": 344.99, + "chunks_per_second": 47.34, + "unique_per_second": 46.73, + "forgotten_per_second": 44.57, + "waited_ticks_per_second": 112.27, + "chunks_total": 19870, + "chunks_per_bot": { + "explore": 1987.0 + }, + "unique_chunks_per_bot": { + "explore": 1966.5 + }, + "resent": 0, + "pulled_back": 16130, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 50.67, + "p50": 47.61, + "p95": 89.3, + "p99": 119.15 + }, + "mspt_worst_p99": 222.3, + "tps": 19.73, + "rss_mb": { + "mean": 2358.4, + "max": 4273.7 + }, + "cpu_percent": 286.32, + "chunks_per_second": 50.39, + "unique_per_second": 49.67, + "forgotten_per_second": 47.45, + "waited_ticks_per_second": 311.85, + "chunks_total": 28954, + "chunks_per_bot": { + "explore": 1158.16 + }, + "unique_chunks_per_bot": { + "explore": 1147.56 + }, + "resent": 0, + "pulled_back": 36319, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 20.06, + "mspt": { + "average": 50.69, + "p50": 47.48, + "p95": 102.67, + "p99": 133.27 + }, + "mspt_worst_p99": 274.4, + "tps": 19.73, + "rss_mb": { + "mean": 1764.01, + "max": 2542.0 + }, + "cpu_percent": 212.83, + "chunks_per_second": 97.33, + "unique_per_second": 96.47, + "forgotten_per_second": 76.74, + "waited_ticks_per_second": 750.49, + "chunks_total": 38538, + "chunks_per_bot": { + "explore": 770.76 + }, + "unique_chunks_per_bot": { + "explore": 763.84 + }, + "resent": 0, + "pulled_back": 39880, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 92.93, + "p50": 87.84, + "p95": 139.6, + "p99": 178.38 + }, + "mspt_worst_p99": 272.9, + "tps": 10.76, + "rss_mb": { + "mean": 1736.38, + "max": 1855.7 + }, + "cpu_percent": 321.53, + "chunks_per_second": 113.89, + "unique_per_second": 113.56, + "forgotten_per_second": 101.68, + "waited_ticks_per_second": 1179.4, + "chunks_total": 84617, + "chunks_per_bot": { + "explore": 846.17 + }, + "unique_chunks_per_bot": { + "explore": 845.01 + }, + "resent": 0, + "pulled_back": 128104, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json new file mode 100644 index 000000000..d79b3f179 --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-1-before-chunk-cache.json @@ -0,0 +1,693 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T00:37:35+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 7.63, + "p50": 5.51, + "p95": 17.46, + "p99": 36.79 + }, + "mspt_worst_p99": 79.6, + "tps": 20.0, + "rss_mb": { + "mean": 1391.94, + "max": 1700.7 + }, + "cpu_percent": 60.18, + "chunks_per_second": 9.15, + "unique_per_second": 0.29, + "forgotten_per_second": 9.18, + "waited_ticks_per_second": 0.0, + "chunks_total": 3682, + "chunks_per_bot": { + "walk": 3682.0 + }, + "unique_chunks_per_bot": { + "walk": 692.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.35, + "mspt": { + "average": 18.08, + "p50": 18.66, + "p95": 28.05, + "p99": 46.94 + }, + "mspt_worst_p99": 456.4, + "tps": 20.0, + "rss_mb": { + "mean": 3455.72, + "max": 3471.7 + }, + "cpu_percent": 65.67, + "chunks_per_second": 9.89, + "unique_per_second": 0.29, + "forgotten_per_second": 9.92, + "waited_ticks_per_second": 0.0, + "chunks_total": 3827, + "chunks_per_bot": { + "walk": 3827.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 27.53, + "p50": 24.93, + "p95": 53.93, + "p99": 77.03 + }, + "mspt_worst_p99": 111.4, + "tps": 20.0, + "rss_mb": { + "mean": 1433.85, + "max": 1831.9 + }, + "cpu_percent": 138.65, + "chunks_per_second": 95.98, + "unique_per_second": 2.38, + "forgotten_per_second": 95.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 38041, + "chunks_per_bot": { + "walk": 3804.1 + }, + "unique_chunks_per_bot": { + "walk": 690.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.83, + "mspt": { + "average": 18.92, + "p50": 16.02, + "p95": 39.0, + "p99": 56.13 + }, + "mspt_worst_p99": 180.3, + "tps": 20.0, + "rss_mb": { + "mean": 3479.45, + "max": 3535.7 + }, + "cpu_percent": 99.39, + "chunks_per_second": 99.93, + "unique_per_second": 2.94, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38411, + "chunks_per_bot": { + "walk": 3841.1 + }, + "unique_chunks_per_bot": { + "walk": 697.1 + }, + "resent": 0, + "pulled_back": 7, + "moved_too_quickly": 7, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 11.52, + "mspt": { + "average": 40.69, + "p50": 37.28, + "p95": 81.16, + "p99": 108.42 + }, + "mspt_worst_p99": 149.9, + "tps": 20.0, + "rss_mb": { + "mean": 1444.12, + "max": 1882.6 + }, + "cpu_percent": 176.94, + "chunks_per_second": 244.11, + "unique_per_second": 6.51, + "forgotten_per_second": 243.96, + "waited_ticks_per_second": 0.0, + "chunks_total": 95219, + "chunks_per_bot": { + "walk": 3808.76 + }, + "unique_chunks_per_bot": { + "walk": 695.64 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 15.23, + "mspt": { + "average": 18.81, + "p50": 17.26, + "p95": 30.16, + "p99": 53.9 + }, + "mspt_worst_p99": 390.0, + "tps": 20.0, + "rss_mb": { + "mean": 3517.36, + "max": 3555.7 + }, + "cpu_percent": 148.52, + "chunks_per_second": 252.34, + "unique_per_second": 7.75, + "forgotten_per_second": 251.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 96645, + "chunks_per_bot": { + "walk": 3865.8 + }, + "unique_chunks_per_bot": { + "walk": 698.4 + }, + "resent": 0, + "pulled_back": 11, + "moved_too_quickly": 11, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 12.72, + "mspt": { + "average": 281.42, + "p50": 278.28, + "p95": 343.64, + "p99": 384.23 + }, + "mspt_worst_p99": 475.1, + "tps": 3.55, + "rss_mb": { + "mean": 1334.32, + "max": 1335.4 + }, + "cpu_percent": 197.11, + "chunks_per_second": 391.5, + "unique_per_second": 21.24, + "forgotten_per_second": 388.33, + "waited_ticks_per_second": 0.0, + "chunks_total": 153136, + "chunks_per_bot": { + "walk": 3062.72 + }, + "unique_chunks_per_bot": { + "walk": 661.82 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 15.74, + "mspt": { + "average": 33.21, + "p50": 29.9, + "p95": 53.37, + "p99": 109.14 + }, + "mspt_worst_p99": 833.3, + "tps": 20.0, + "rss_mb": { + "mean": 3568.07, + "max": 3594.9 + }, + "cpu_percent": 266.59, + "chunks_per_second": 496.3, + "unique_per_second": 18.64, + "forgotten_per_second": 495.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 191965, + "chunks_per_bot": { + "walk": 3839.3 + }, + "unique_chunks_per_bot": { + "walk": 696.22 + }, + "resent": 0, + "pulled_back": 184, + "moved_too_quickly": 183, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.22, + "mspt": { + "average": 467.37, + "p50": 464.62, + "p95": 524.07, + "p99": 548.77 + }, + "mspt_worst_p99": 581.1, + "tps": 2.14, + "rss_mb": { + "mean": 1353.68, + "max": 1354.9 + }, + "cpu_percent": 191.96, + "chunks_per_second": 377.62, + "unique_per_second": 55.8, + "forgotten_per_second": 348.88, + "waited_ticks_per_second": 0.0, + "chunks_total": 165719, + "chunks_per_bot": { + "walk": 1657.19 + }, + "unique_chunks_per_bot": { + "walk": 549.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 56 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 14.84, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 17.07, + "p50": 16.6, + "p95": 32.82, + "p99": 50.3 + }, + "mspt_worst_p99": 113.9, + "tps": 20.0, + "rss_mb": { + "mean": 1391.72, + "max": 1566.6 + }, + "cpu_percent": 333.8, + "chunks_per_second": 39.42, + "unique_per_second": 34.77, + "forgotten_per_second": 39.34, + "waited_ticks_per_second": 0.0, + "chunks_total": 13860, + "chunks_per_bot": { + "explore": 13860.0 + }, + "unique_chunks_per_bot": { + "explore": 12379.0 + }, + "resent": 0, + "pulled_back": 192, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 16.03, + "mspt": { + "average": 9.9, + "p50": 8.04, + "p95": 20.41, + "p99": 63.62 + }, + "mspt_worst_p99": 351.1, + "tps": 20.0, + "rss_mb": { + "mean": 3709.92, + "max": 3776.2 + }, + "cpu_percent": 246.64, + "chunks_per_second": 36.06, + "unique_per_second": 33.33, + "forgotten_per_second": 35.73, + "waited_ticks_per_second": 0.0, + "chunks_total": 12369, + "chunks_per_bot": { + "explore": 12369.0 + }, + "unique_chunks_per_bot": { + "explore": 11559.0 + }, + "resent": 0, + "pulled_back": 222, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.42, + "mspt": { + "average": 33.72, + "p50": 31.08, + "p95": 61.07, + "p99": 89.09 + }, + "mspt_worst_p99": 142.6, + "tps": 20.0, + "rss_mb": { + "mean": 2239.97, + "max": 4108.8 + }, + "cpu_percent": 350.83, + "chunks_per_second": 46.49, + "unique_per_second": 46.08, + "forgotten_per_second": 44.33, + "waited_ticks_per_second": 111.28, + "chunks_total": 19915, + "chunks_per_bot": { + "explore": 1991.5 + }, + "unique_chunks_per_bot": { + "explore": 1974.4 + }, + "resent": 0, + "pulled_back": 17516, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.15, + "mspt": { + "average": 16.25, + "p50": 13.67, + "p95": 28.92, + "p99": 115.9 + }, + "mspt_worst_p99": 1202.1, + "tps": 20.0, + "rss_mb": { + "mean": 4202.72, + "max": 4502.7 + }, + "cpu_percent": 247.47, + "chunks_per_second": 22.3, + "unique_per_second": 22.25, + "forgotten_per_second": 22.64, + "waited_ticks_per_second": 78.89, + "chunks_total": 10092, + "chunks_per_bot": { + "explore": 1009.2 + }, + "unique_chunks_per_bot": { + "explore": 1007.4 + }, + "resent": 0, + "pulled_back": 16286, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.82, + "mspt": { + "average": 48.03, + "p50": 44.99, + "p95": 83.06, + "p99": 109.63 + }, + "mspt_worst_p99": 191.8, + "tps": 20.0, + "rss_mb": { + "mean": 2214.16, + "max": 4598.6 + }, + "cpu_percent": 356.03, + "chunks_per_second": 64.2, + "unique_per_second": 63.5, + "forgotten_per_second": 60.9, + "waited_ticks_per_second": 301.65, + "chunks_total": 32247, + "chunks_per_bot": { + "explore": 1289.88 + }, + "unique_chunks_per_bot": { + "explore": 1279.4 + }, + "resent": 0, + "pulled_back": 42159, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.73, + "mspt": { + "average": 25.73, + "p50": 22.75, + "p95": 37.72, + "p99": 201.98 + }, + "mspt_worst_p99": 4051.5, + "tps": 20.0, + "rss_mb": { + "mean": 4355.9, + "max": 4983.2 + }, + "cpu_percent": 309.3, + "chunks_per_second": 33.33, + "unique_per_second": 33.21, + "forgotten_per_second": 34.22, + "waited_ticks_per_second": 258.68, + "chunks_total": 19426, + "chunks_per_bot": { + "explore": 777.04 + }, + "unique_chunks_per_bot": { + "explore": 772.92 + }, + "resent": 0, + "pulled_back": 53918, + "moved_too_quickly": 93, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.01, + "mspt": { + "average": 108.61, + "p50": 107.37, + "p95": 151.96, + "p99": 177.41 + }, + "mspt_worst_p99": 271.6, + "tps": 9.21, + "rss_mb": { + "mean": 1775.98, + "max": 1956.9 + }, + "cpu_percent": 359.7, + "chunks_per_second": 100.32, + "unique_per_second": 98.91, + "forgotten_per_second": 95.42, + "waited_ticks_per_second": 518.15, + "chunks_total": 55956, + "chunks_per_bot": { + "explore": 1119.12 + }, + "unique_chunks_per_bot": { + "explore": 1111.42 + }, + "resent": 0, + "pulled_back": 69967, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.74, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 244.43, + "p50": 243.58, + "p95": 308.39, + "p99": 360.12 + }, + "mspt_worst_p99": 470.2, + "tps": 4.09, + "rss_mb": { + "mean": 1806.85, + "max": 2084.5 + }, + "cpu_percent": 310.46, + "chunks_per_second": 186.87, + "unique_per_second": 182.99, + "forgotten_per_second": 161.75, + "waited_ticks_per_second": 1131.65, + "chunks_total": 100389, + "chunks_per_bot": { + "explore": 1003.89 + }, + "unique_chunks_per_bot": { + "explore": 991.9 + }, + "resent": 0, + "pulled_back": 56791, + "moved_too_quickly": 344, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.83, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json new file mode 100644 index 000000000..4c182395c --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/run-2-chunk-cache.json @@ -0,0 +1,413 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T02:22:59+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench2.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "walk", + "start_seconds": 11.12, + "mspt": { + "average": 5.41, + "p50": 4.63, + "p95": 11.61, + "p99": 30.5 + }, + "mspt_worst_p99": 64.6, + "tps": 20.0, + "rss_mb": { + "mean": 1398.84, + "max": 1708.5 + }, + "cpu_percent": 56.84, + "chunks_per_second": 9.19, + "unique_per_second": 0.27, + "forgotten_per_second": 9.22, + "waited_ticks_per_second": 0.0, + "chunks_total": 3713, + "chunks_per_bot": { + "walk": 3713.0 + }, + "unique_chunks_per_bot": { + "walk": 694.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 13.18, + "p50": 11.74, + "p95": 26.5, + "p99": 44.82 + }, + "mspt_worst_p99": 87.6, + "tps": 20.0, + "rss_mb": { + "mean": 1439.83, + "max": 1831.6 + }, + "cpu_percent": 132.94, + "chunks_per_second": 93.87, + "unique_per_second": 2.38, + "forgotten_per_second": 93.77, + "waited_ticks_per_second": 0.0, + "chunks_total": 37240, + "chunks_per_bot": { + "walk": 3724.0 + }, + "unique_chunks_per_bot": { + "walk": 688.7 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "walk", + "start_seconds": 10.92, + "mspt": { + "average": 23.52, + "p50": 21.92, + "p95": 44.7, + "p99": 63.12 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 1485.82, + "max": 1872.0 + }, + "cpu_percent": 173.82, + "chunks_per_second": 235.63, + "unique_per_second": 5.64, + "forgotten_per_second": 235.72, + "waited_ticks_per_second": 0.0, + "chunks_total": 94549, + "chunks_per_bot": { + "walk": 3781.96 + }, + "unique_chunks_per_bot": { + "walk": 692.8 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "walk", + "start_seconds": 10.91, + "mspt": { + "average": 31.36, + "p50": 26.08, + "p95": 70.6, + "p99": 92.83 + }, + "mspt_worst_p99": 125.5, + "tps": 20.0, + "rss_mb": { + "mean": 1556.81, + "max": 1913.0 + }, + "cpu_percent": 192.16, + "chunks_per_second": 468.69, + "unique_per_second": 10.43, + "forgotten_per_second": 468.78, + "waited_ticks_per_second": 0.0, + "chunks_total": 193547, + "chunks_per_bot": { + "walk": 3870.94 + }, + "unique_chunks_per_bot": { + "walk": 692.84 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "walk", + "start_seconds": 11.02, + "mspt": { + "average": 84.38, + "p50": 81.5, + "p95": 132.92, + "p99": 168.38 + }, + "mspt_worst_p99": 245.5, + "tps": 11.85, + "rss_mb": { + "mean": 1395.64, + "max": 1941.3 + }, + "cpu_percent": 271.28, + "chunks_per_second": 850.05, + "unique_per_second": 21.79, + "forgotten_per_second": 851.1, + "waited_ticks_per_second": 0.0, + "chunks_total": 368464, + "chunks_per_bot": { + "walk": 3684.64 + }, + "unique_chunks_per_bot": { + "walk": 680.58 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 1, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 11.63, + "p50": 10.27, + "p95": 24.52, + "p99": 40.53 + }, + "mspt_worst_p99": 99.9, + "tps": 20.0, + "rss_mb": { + "mean": 1413.81, + "max": 1596.1 + }, + "cpu_percent": 329.84, + "chunks_per_second": 39.47, + "unique_per_second": 34.81, + "forgotten_per_second": 39.42, + "waited_ticks_per_second": 0.0, + "chunks_total": 13798, + "chunks_per_bot": { + "explore": 13798.0 + }, + "unique_chunks_per_bot": { + "explore": 12330.0 + }, + "resent": 0, + "pulled_back": 185, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "explore", + "start_seconds": 11.02, + "mspt": { + "average": 28.49, + "p50": 26.2, + "p95": 48.58, + "p99": 72.04 + }, + "mspt_worst_p99": 125.7, + "tps": 20.0, + "rss_mb": { + "mean": 2231.06, + "max": 4077.8 + }, + "cpu_percent": 344.95, + "chunks_per_second": 46.31, + "unique_per_second": 45.88, + "forgotten_per_second": 44.14, + "waited_ticks_per_second": 111.95, + "chunks_total": 19722, + "chunks_per_bot": { + "explore": 1972.2 + }, + "unique_chunks_per_bot": { + "explore": 1957.0 + }, + "resent": 0, + "pulled_back": 18533, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "explore", + "start_seconds": 11.12, + "mspt": { + "average": 40.04, + "p50": 37.61, + "p95": 62.39, + "p99": 83.64 + }, + "mspt_worst_p99": 147.0, + "tps": 20.0, + "rss_mb": { + "mean": 2466.85, + "max": 4504.5 + }, + "cpu_percent": 340.13, + "chunks_per_second": 60.61, + "unique_per_second": 59.62, + "forgotten_per_second": 56.28, + "waited_ticks_per_second": 299.57, + "chunks_total": 32877, + "chunks_per_bot": { + "explore": 1315.08 + }, + "unique_chunks_per_bot": { + "explore": 1300.72 + }, + "resent": 0, + "pulled_back": 46272, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "explore", + "start_seconds": 11.32, + "mspt": { + "average": 61.82, + "p50": 59.21, + "p95": 90.46, + "p99": 115.58 + }, + "mspt_worst_p99": 320.9, + "tps": 16.18, + "rss_mb": { + "mean": 2634.54, + "max": 4883.1 + }, + "cpu_percent": 356.96, + "chunks_per_second": 95.26, + "unique_per_second": 94.31, + "forgotten_per_second": 85.86, + "waited_ticks_per_second": 528.08, + "chunks_total": 59251, + "chunks_per_bot": { + "explore": 1185.02 + }, + "unique_chunks_per_bot": { + "explore": 1173.96 + }, + "resent": 0, + "pulled_back": 99493, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 100, + "behaviour": "explore", + "start_seconds": 10.81, + "mspt": { + "average": 103.24, + "p50": 100.03, + "p95": 144.77, + "p99": 178.8 + }, + "mspt_worst_p99": 258.6, + "tps": 9.69, + "rss_mb": { + "mean": 1784.48, + "max": 1922.0 + }, + "cpu_percent": 336.94, + "chunks_per_second": 115.06, + "unique_per_second": 114.86, + "forgotten_per_second": 109.43, + "waited_ticks_per_second": 1127.57, + "chunks_total": 93839, + "chunks_per_bot": { + "explore": 938.39 + }, + "unique_chunks_per_bot": { + "explore": 935.28 + }, + "resent": 0, + "pulled_back": 133404, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 100, + "bots_failed": [], + "tick_queries": 58 + } + ] +} diff --git a/benchmarks/server-equal-work-2026-10-17/vanilla.json b/benchmarks/server-equal-work-2026-10-17/vanilla.json new file mode 100644 index 000000000..014554cee --- /dev/null +++ b/benchmarks/server-equal-work-2026-10-17/vanilla.json @@ -0,0 +1,324 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-17T03:29:30+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4 + }, + "commit": "", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "vanilla", + "bots": "1,10,25,50,100", + "behaviour": "walk,explore", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "gamerule": "locator_bar=false", + "heap": "4g", + "out": "/home/ludovic/scratch/sh2-bench3.json", + "nice": 19, + "bots_via": "ssh -o BatchMode=yes macmini", + "bots_bin": "/tmp/sh2-horizon-bots", + "connect": "100.72.51.8", + "properties": { + "level-seed": "12345", + "view-distance": "10", + "simulation-distance": "10", + "online-mode": "false", + "white-list": "false", + "gamemode": "creative", + "force-gamemode": "true", + "spawn-protection": "0", + "max-players": "200", + "difficulty": "easy", + "sync-chunk-writes": "true" + } + }, + "runs": [ + { + "server": "vanilla", + "bots": 1, + "behaviour": "walk", + "start_seconds": 15.43, + "mspt": { + "average": 18.32, + "p50": 19.26, + "p95": 27.34, + "p99": 45.48 + }, + "mspt_worst_p99": 393.3, + "tps": 20.0, + "rss_mb": { + "mean": 3428.43, + "max": 3437.7 + }, + "cpu_percent": 66.47, + "chunks_per_second": 9.92, + "unique_per_second": 0.29, + "forgotten_per_second": 9.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 3850, + "chunks_per_bot": { + "walk": 3850.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0 + }, + "resent": 0, + "pulled_back": 0, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "walk", + "start_seconds": 14.76, + "mspt": { + "average": 16.8, + "p50": 14.55, + "p95": 30.52, + "p99": 50.01 + }, + "mspt_worst_p99": 205.2, + "tps": 20.0, + "rss_mb": { + "mean": 3490.15, + "max": 3580.7 + }, + "cpu_percent": 83.7, + "chunks_per_second": 100.01, + "unique_per_second": 2.83, + "forgotten_per_second": 100.04, + "waited_ticks_per_second": 0.0, + "chunks_total": 38623, + "chunks_per_bot": { + "walk": 3862.3 + }, + "unique_chunks_per_bot": { + "walk": 697.2 + }, + "resent": 0, + "pulled_back": 5, + "moved_too_quickly": 5, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "walk", + "start_seconds": 14.84, + "mspt": { + "average": 16.01, + "p50": 14.55, + "p95": 26.39, + "p99": 51.26 + }, + "mspt_worst_p99": 397.8, + "tps": 20.0, + "rss_mb": { + "mean": 3550.02, + "max": 3593.5 + }, + "cpu_percent": 114.96, + "chunks_per_second": 251.62, + "unique_per_second": 6.72, + "forgotten_per_second": 251.16, + "waited_ticks_per_second": 0.0, + "chunks_total": 98701, + "chunks_per_bot": { + "walk": 3948.04 + }, + "unique_chunks_per_bot": { + "walk": 698.84 + }, + "resent": 0, + "pulled_back": 10, + "moved_too_quickly": 10, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "walk", + "start_seconds": 14.43, + "mspt": { + "average": 20.52, + "p50": 19.55, + "p95": 29.72, + "p99": 49.04 + }, + "mspt_worst_p99": 600.4, + "tps": 20.0, + "rss_mb": { + "mean": 3633.12, + "max": 3658.7 + }, + "cpu_percent": 193.84, + "chunks_per_second": 501.86, + "unique_per_second": 12.15, + "forgotten_per_second": 501.8, + "waited_ticks_per_second": 0.0, + "chunks_total": 203429, + "chunks_per_bot": { + "walk": 4068.58 + }, + "unique_chunks_per_bot": { + "walk": 698.66 + }, + "resent": 0, + "pulled_back": 33, + "moved_too_quickly": 32, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "walk", + "start_seconds": 15.34, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 1, + "behaviour": "explore", + "start_seconds": 15.55, + "mspt": { + "average": 9.93, + "p50": 8.12, + "p95": 21.33, + "p99": 60.19 + }, + "mspt_worst_p99": 373.0, + "tps": 20.0, + "rss_mb": { + "mean": 3564.11, + "max": 3655.0 + }, + "cpu_percent": 245.18, + "chunks_per_second": 35.93, + "unique_per_second": 33.35, + "forgotten_per_second": 35.64, + "waited_ticks_per_second": 0.0, + "chunks_total": 12340, + "chunks_per_bot": { + "explore": 12340.0 + }, + "unique_chunks_per_bot": { + "explore": 11569.0 + }, + "resent": 0, + "pulled_back": 261, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 1, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "explore", + "start_seconds": 15.03, + "mspt": { + "average": 16.99, + "p50": 14.46, + "p95": 29.61, + "p99": 132.18 + }, + "mspt_worst_p99": 1244.0, + "tps": 20.0, + "rss_mb": { + "mean": 4135.2, + "max": 4453.1 + }, + "cpu_percent": 242.32, + "chunks_per_second": 22.39, + "unique_per_second": 22.41, + "forgotten_per_second": 22.78, + "waited_ticks_per_second": 78.78, + "chunks_total": 10177, + "chunks_per_bot": { + "explore": 1017.7 + }, + "unique_chunks_per_bot": { + "explore": 1016.2 + }, + "resent": 0, + "pulled_back": 17314, + "moved_too_quickly": 19, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 59 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "explore", + "start_seconds": 14.84, + "mspt": { + "average": 24.19, + "p50": 21.22, + "p95": 36.51, + "p99": 174.82 + }, + "mspt_worst_p99": 1532.8, + "tps": 20.0, + "rss_mb": { + "mean": 4504.55, + "max": 4988.9 + }, + "cpu_percent": 319.55, + "chunks_per_second": 33.78, + "unique_per_second": 33.66, + "forgotten_per_second": 34.64, + "waited_ticks_per_second": 269.22, + "chunks_total": 20522, + "chunks_per_bot": { + "explore": 820.88 + }, + "unique_chunks_per_bot": { + "explore": 815.76 + }, + "resent": 0, + "pulled_back": 46246, + "moved_too_quickly": 28, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "explore", + "start_seconds": 14.73, + "error": "[Errno 32] Broken pipe" + }, + { + "server": "vanilla", + "bots": 100, + "behaviour": "explore", + "start_seconds": 14.54, + "error": "[Errno 32] Broken pipe" + } + ] +} diff --git a/crates/horizon-bots/src/main.rs b/crates/horizon-bots/src/main.rs index d76da5e84..090daeb4e 100644 --- a/crates/horizon-bots/src/main.rs +++ b/crates/horizon-bots/src/main.rs @@ -9,6 +9,11 @@ //! horizon-bots --server 127.0.0.1:25565 --bots 25 --behaviour mixed --seconds 360 --report bots.json //! //! It prints one JSON line a second (bots online, chunks received) and writes a summary with `--report`. +//! A bot moves only while it holds the chunk it stands in: vanilla's client stops ticking its player in a chunk +//! it hasn't received, so a player can't outrun the server's chunk sending, on any server. +//! Each bot also keeps the chunks it holds, as a client's chunk cache does, so the report tells chunks that +//! entered the view apart from chunks sent again while the bot still held them (`resent`), and counts the +//! times the server pulled a bot back (`pulled_back`: a teleport after the first, as for "moved too quickly"). use horizon_protocol::{ PROTOCOL_VERSION, @@ -25,6 +30,7 @@ use horizon_protocol::{ }; use serde_json::json; use std::{ + collections::HashSet, sync::{ Arc, Mutex, atomic::{AtomicBool, AtomicU64, Ordering}, @@ -43,8 +49,9 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m --seconds N how long to run after the first bot joins; default 60 --view-distance N what the bots ask for; default 10 --seed N default 12345 + --explore-speed B blocks a second an explore bot flies; default 22 (as fast as chunks come) --name PREFIX bot names: PREFIX0, PREFIX1...; default Bot - --report FILE a JSON summary at the end + --report FILE a JSON summary at the end (- prints it after the per-second lines) "; #[derive(Clone, Copy, Debug, PartialEq)] @@ -73,6 +80,7 @@ struct Options { seconds: u64, view_distance: i8, seed: u64, + explore_speed: f64, name: String, report: Option, } @@ -87,6 +95,7 @@ fn options() -> Result { seconds: 60, view_distance: 10, seed: 12345, + explore_speed: 22.0, name: "Bot".into(), report: None, }; @@ -110,6 +119,9 @@ fn options() -> Result { "--seconds" => o.seconds = value.parse().map_err(|_| number("seconds"))?, "--view-distance" => o.view_distance = value.parse().map_err(|_| number("2 to 32"))?, "--seed" => o.seed = value.parse().map_err(|_| number("a number"))?, + "--explore-speed" => { + o.explore_speed = value.parse().map_err(|_| number("blocks a second"))?; + } "--name" => o.name = value, "--report" => o.report = Some(value), _ => return Err(format!("unknown option {arg}; --help lists them")), @@ -129,6 +141,17 @@ fn options() -> Result { struct Bot { online: AtomicBool, chunks: AtomicU64, + /// Chunks received while the bot already held them (no ForgetLevelChunk in between). + resent: AtomicU64, + /// Different chunks received over the run. + unique: AtomicU64, + forgotten: AtomicU64, + /// Teleports after the spawn one: the server refused a move. + pulled_back: AtomicU64, + /// Ticks the bot couldn't move because it didn't hold its chunk yet. + waited: AtomicU64, + /// The chunks the bot holds (ClientChunkCache). + held: Mutex>, /// Where the server last put the bot (a teleport), to start from. teleport: Mutex>, error: Mutex>, @@ -268,6 +291,36 @@ fn join(o: &Options, name: &str) -> Result { } } +/// ChunkBatchSizeCalculator: the chunks per tick a vanilla client asks for, from how long its batches take +/// to arrive. +struct BatchSize { + nanos_per_chunk: f64, + old_samples_weight: u32, + started: Instant, +} + +impl BatchSize { + fn new() -> Self { + Self { + nanos_per_chunk: 2_000_000.0, + old_samples_weight: 1, + started: Instant::now(), + } + } + fn finished(&mut self, size: i32) { + if size > 0 { + let per_chunk = self.started.elapsed().as_nanos() as f64 / f64::from(size); + let clamped = per_chunk.clamp(self.nanos_per_chunk / 3.0, self.nanos_per_chunk * 3.0); + let weight = f64::from(self.old_samples_weight); + self.nanos_per_chunk = (self.nanos_per_chunk * weight + clamped) / (weight + 1.0); + self.old_samples_weight = (self.old_samples_weight + 1).min(49); + } + } + fn desired_chunks_per_tick(&self) -> f32 { + (7_000_000.0 / self.nanos_per_chunk) as f32 + } +} + /// Reads the play state: answers what a client must answer, counts chunks, records teleports. fn read( mut reader: horizon_protocol::connection::ConnReader, @@ -277,6 +330,9 @@ fn read( use ids::play::clientbound as cb; use ids::play::serverbound as sb; let send = |body: Vec| writer.lock().unwrap().send(&body); + let mut seen = HashSet::new(); + let mut batch = BatchSize::new(); + let mut teleports = 0u64; loop { let (id, body) = match reader.recv() { Ok(packet) => packet, @@ -299,14 +355,38 @@ fn read( }, cb::LEVEL_CHUNK_WITH_LIGHT => { bot.chunks.fetch_add(1, Ordering::Relaxed); + if let (Ok(x), Ok(z)) = (r.i32(), r.i32()) { + if !bot.held.lock().unwrap().insert((x, z)) { + bot.resent.fetch_add(1, Ordering::Relaxed); + } + if seen.insert((x, z)) { + bot.unique.fetch_add(1, Ordering::Relaxed); + } + } Ok(()) } - cb::CHUNK_BATCH_FINISHED => send( - play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { - chunks_per_tick: 25.0, - }) - .encode(), - ), + cb::FORGET_LEVEL_CHUNK => { + if let Ok(play::Clientbound::ForgetLevelChunk(p)) = + play::Clientbound::decode(id, &body) + && bot.held.lock().unwrap().remove(&(p.pos[0], p.pos[1])) + { + bot.forgotten.fetch_add(1, Ordering::Relaxed); + } + Ok(()) + } + cb::CHUNK_BATCH_START => { + batch.started = Instant::now(); + Ok(()) + } + cb::CHUNK_BATCH_FINISHED => { + batch.finished(r.varint().unwrap_or(0)); + send( + play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived { + chunks_per_tick: batch.desired_chunks_per_tick(), + }) + .encode(), + ) + } cb::PLAYER_POSITION => match play::Clientbound::decode(id, &body) { Ok(play::Clientbound::PlayerPosition(p)) => { let mut at = bot.teleport.lock().unwrap(); @@ -320,6 +400,10 @@ fn read( } }); *at = Some(pos); + teleports += 1; + if teleports > 1 { + bot.pulled_back.fetch_add(1, Ordering::Relaxed); + } send( play::Serverbound::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, @@ -416,7 +500,10 @@ fn run_bot( if let Some(at) = bot.teleport.lock().unwrap().take() { pos = at; } - if pos[1] < cruise { + let here = ((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4); + if !bot.held.lock().unwrap().contains(&here) { + bot.waited.fetch_add(1, Ordering::Relaxed); + } else if pos[1] < cruise { pos[1] = (pos[1] + 0.5).min(cruise); } else { match behaviour { @@ -440,9 +527,11 @@ fn run_bot( } } Behaviour::Explore => { - // Flying fast in creative: about 22 blocks a second, which keeps new chunks coming. - pos[0] += heading.cos() * 1.1; - pos[2] += heading.sin() * 1.1; + // Flying in creative, by default about 22 blocks a second, which keeps new + // chunks coming as fast as the server sends them. + let step = o.explore_speed / 20.0; + pos[0] += heading.cos() * step; + pos[2] += heading.sin() * step; } } } @@ -520,6 +609,9 @@ fn main() { .filter(|b| b.online.load(Ordering::SeqCst)) .count(); let chunks: u64 = bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum(); + let total = |f: fn(&Bot) -> &AtomicU64| -> u64 { + bots.iter().map(|b| f(b).load(Ordering::Relaxed)).sum() + }; let failed = bots .iter() .filter(|b| b.error.lock().unwrap().is_some()) @@ -536,6 +628,11 @@ fn main() { "failed": failed, "chunks": chunks, "chunks_per_second": chunks - previous_chunks, + "unique": total(|b| &b.unique), + "forgotten": total(|b| &b.forgotten), + "resent": total(|b| &b.resent), + "pulled_back": total(|b| &b.pulled_back), + "waited_ticks": total(|b| &b.waited), }) ); previous_chunks = chunks; @@ -554,19 +651,30 @@ fn main() { "bots": o.bots, "behaviour": o.behaviour, "seed": o.seed, + "explore_speed": o.explore_speed, "view_distance": o.view_distance, "seconds": o.seconds, "joined": bots.iter().filter(|b| b.joined_after_ms.load(Ordering::SeqCst) > 0).count(), "chunks": bots.iter().map(|b| b.chunks.load(Ordering::Relaxed)).sum::(), + "resent": bots.iter().map(|b| b.resent.load(Ordering::Relaxed)).sum::(), + "pulled_back": bots.iter().map(|b| b.pulled_back.load(Ordering::Relaxed)).sum::(), + "waited_ticks": bots.iter().map(|b| b.waited.load(Ordering::Relaxed)).sum::(), "per_bot": bots.iter().enumerate().map(|(i, b)| json!({ "name": format!("{}{i}", o.name), "behaviour": behaviour_of(&o.behaviour, i).name(), "joined_after_ms": b.joined_after_ms.load(Ordering::SeqCst), "chunks": b.chunks.load(Ordering::Relaxed), + "unique_chunks": b.unique.load(Ordering::Relaxed), + "resent": b.resent.load(Ordering::Relaxed), + "forgotten": b.forgotten.load(Ordering::Relaxed), + "pulled_back": b.pulled_back.load(Ordering::Relaxed), + "waited_ticks": b.waited.load(Ordering::Relaxed), "error": *b.error.lock().unwrap(), })).collect::>(), }); - if let Some(path) = &o.report { + if o.report.as_deref() == Some("-") { + println!("{summary:#}"); + } else if let Some(path) = &o.report { if let Err(e) = std::fs::write(path, format!("{summary:#}\n")) { eprintln!("horizon-bots: {path}: {e}"); } diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index 29a02553f..ffccb88e8 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -37,7 +37,7 @@ miniz_oxide = "0.8" ab_glyph = "0.2.32" log = "0.4" chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } horizon-theme = { path = "../horizon-theme" } # Opt-in data collection: the game keeps, the launcher sends (docs/telemetry.md). horizon-telemetry = { path = "../horizon-telemetry", default-features = false } diff --git a/crates/horizon-client/examples/block_entity_tickers_fixture.rs b/crates/horizon-client/examples/block_entity_tickers_fixture.rs new file mode 100644 index 000000000..f08c333f6 --- /dev/null +++ b/crates/horizon-client/examples/block_entity_tickers_fixture.rs @@ -0,0 +1,99 @@ +//! The Rust side of tools/test_block_entity_tickers_parity.py: the ops of +//! `VanillaBlockEntityTickerOracle` on `BlockEntities`, as `World` drives it +//! (a state write calls `state_changed`), printing the tick order. +use horizon_client::{ + block_entities::{BlockEntities, Pos, Ticking}, + containers::BlockEntity, +}; +use std::collections::HashMap; + +/// State ids of the fixture: 0 air, 1 a block whose block entity ticks, 2 a +/// jukebox without a record, 3 a block entity that never ticks (a chest). +fn state(name: &str) -> u32 { + match name { + "chest" | "barrel" => 3, + "jukebox" => 2, + _ => 1, + } +} + +fn entity(name: &str) -> BlockEntity { + if name.starts_with("jukebox") { + // The game makes a jukebox's block entity when a record goes in. + return BlockEntity::Jukebox(Default::default()); + } + BlockEntity::for_block(&format!("minecraft:{name}")) + .unwrap_or_else(|| panic!("no block entity for {name}")) +} + +fn main() { + let args: Vec = std::env::args().collect(); + let input = std::fs::read_to_string(&args[1]).expect("input"); + let mut out = String::new(); + let mut entities = BlockEntities::default(); + let mut states: HashMap = HashMap::new(); + let mut kinds: HashMap = HashMap::new(); + let table = vec![Ticking::No, Ticking::Yes, Ticking::Idle, Ticking::No]; + for line in input.lines() { + let w: Vec<&str> = line.split_whitespace().collect(); + let pos = |i: usize| -> Pos { + let n = |j: usize| w[i + j].parse::().expect("coordinate"); + (n(0), n(1), n(2)) + }; + match w[0] { + "reset" => { + entities = BlockEntities::default(); + entities.set_states(table.clone()); + states.clear(); + kinds.clear(); + } + "load" => { + let mut chunk = Vec::new(); + for i in (3..w.len()).step_by(4) { + let p = pos(i + 1); + states.insert(p, state(w[i])); + kinds.insert(p, w[i].to_owned()); + chunk.push((p, entity(w[i]))); + } + entities.load_chunk(chunk); + } + "place" => { + let p = pos(2); + // World::set, then the game adds the block entity. + let old = states.insert(p, state(w[1])).unwrap_or(0); + kinds.insert(p, w[1].to_owned()); + entities.state_changed(p, old, state(w[1])); + entities.insert(p, entity(w[1])); + } + "replace" => { + let p = pos(1); + entities.insert(p, entity(&kinds[&p])); + } + "remove" => { + let p = pos(1); + entities.remove(&p); + let old = states.insert(p, 0).unwrap_or(0); + entities.state_changed(p, old, 0); + } + "record" => { + let p = pos(1); + let s = if w[4] == "1" { 1 } else { 2 }; + let old = states.insert(p, s).unwrap_or(0); + entities.state_changed(p, old, s); + } + "unload" => { + let c = (w[1].parse::().unwrap(), w[2].parse::().unwrap()); + entities.retain(|p, _| (p.0 >> 4, p.2 >> 4) != c); + } + "tick" => { + out.push_str("tick"); + for (p, _) in entities.tickers(|p| states.get(&p).copied().unwrap_or(0)) { + out.push_str(&format!(" {},{},{}", p.0, p.1, p.2)); + } + out.push('\n'); + } + other => panic!("unknown op {other}"), + } + } + std::fs::write(&args[2], out).expect("output"); +} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 16fc36b95..20d87e03c 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -22,12 +22,7 @@ fn main() -> Result<(), Box> { let port: u16 = args.next().ok_or("port")?.parse()?; let assets = Assets::load(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; - let state = |name: &str| { - assets - .registry - .default_state(name) - .map_or(0, |s| s.0 as u16) - }; + let state = |name: &str| assets.registry.default_state(name).map_or(0, |s| s.0); let sync = Arc::new(SyncData::load(&root)?); let biomes: Vec = sync .dynamic @@ -121,6 +116,7 @@ fn main() -> Result<(), Box> { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; for event in hub.tick(&mut ctx) { match event { @@ -132,7 +128,9 @@ fn main() -> Result<(), Box> { eprintln!("[lan] {packet:?}"); } } - HostEvent::Chat(line) => println!("{line}"), + HostEvent::Chat { line, .. } | HostEvent::Warn(line) | HostEvent::Error(line) => { + println!("{line}") + } HostEvent::Left(_) => {} } } diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/light_parity.rs index afc3e3156..29488130e 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/light_parity.rs @@ -232,7 +232,7 @@ fn incremental( c.lit = true; world.insert((x, z), Arc::new(c)); } - let palette: Vec = [ + let palette: Vec = [ "minecraft:air", "minecraft:stone", "minecraft:torch", @@ -242,7 +242,7 @@ fn incremental( "minecraft:glass", ] .iter() - .filter_map(|n| registry.default_state(n).map(|s| s.0 as u16)) + .filter_map(|n| registry.default_state(n).map(|s| s.0)) .chain( facts .states @@ -257,7 +257,7 @@ fn incremental( ] .contains(&&*f.name) }) - .map(|(i, _)| i as u16) + .map(|(i, _)| i as u32) .step_by(3), ) .collect(); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 087fd3edf..0b3adec31 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -999,6 +999,7 @@ fn main() -> horizon_client::Result<()> { hero: false, uuid: PLAYER_UUID, allies: Default::default(), + remote: false, } }); let mut scratch = LegacyRandom::new(0); diff --git a/crates/horizon-client/examples/options_probe.rs b/crates/horizon-client/examples/options_probe.rs index 1cdf8c8fb..f186af994 100644 --- a/crates/horizon-client/examples/options_probe.rs +++ b/crates/horizon-client/examples/options_probe.rs @@ -1,7 +1,10 @@ #![forbid(unsafe_code)] //! Loads and saves option files like `Options.load`/`save`, for the //! differential harness (tools/test_options_parity.py). -use horizon_client::{Result, keybinds, options_file::OptionsFile}; +use horizon_client::{ + Result, keybinds, + options_file::{OptionsFile, V}, +}; use std::{fs, io::Write}; fn main() -> Result<()> { @@ -14,11 +17,16 @@ fn main() -> Result<()> { let mut first = true; for path in names { let name = path.file_name().unwrap().to_string_lossy().into_owned(); - let file = if name == "absent.txt" { + let mut file = if name == "absent.txt" { OptionsFile::default() } else { OptionsFile::parse(&String::from_utf8_lossy(&fs::read(&path)?)) }; + // Horizon extends the slider to 64; vanilla rejects 33..64 to its default. + // Compare that deliberate extension as vanilla would serialize it. + if file.int("renderDistance") > 32 { + file.set("renderDistance", V::Int(12)); + } write!(out, "== {name}\n{}", file.serialize())?; if first { first = false; diff --git a/crates/horizon-client/examples/random_tick_eligibility_bench.rs b/crates/horizon-client/examples/random_tick_eligibility_bench.rs index 856d7d520..49c32a8f7 100644 --- a/crates/horizon-client/examples/random_tick_eligibility_bench.rs +++ b/crates/horizon-client/examples/random_tick_eligibility_bench.rs @@ -56,16 +56,16 @@ fn main() -> horizon_client::Result<()> { "resource_load_ms={:.3}", start.elapsed().as_secs_f64() * 1000.0 ); - let inactive: Vec = facts + let inactive: Vec = facts .states .iter() .enumerate() .filter(|(_, f)| !f.random_ticks) .take(128) - .map(|(i, _)| i as u16) + .map(|(i, _)| i as u32) .collect(); - let active = registry.default_state("minecraft:grass_block").unwrap().0 as u16; - assert!(facts.get(BlockStateId(u32::from(active))).random_ticks); + let active = registry.default_state("minecraft:grass_block").unwrap().0; + assert!(facts.get(BlockStateId(active)).random_ticks); for (name, palette) in [("sparse", 1), ("dense", 128)] { let start = Instant::now(); let mut chunks = FxHashMap::default(); diff --git a/crates/horizon-client/examples/resource_memory.rs b/crates/horizon-client/examples/resource_memory.rs new file mode 100644 index 000000000..1eb6c45b7 --- /dev/null +++ b/crates/horizon-client/examples/resource_memory.rs @@ -0,0 +1,151 @@ +//! Resident memory of each resource loader, in the game's start order: what a +//! larger registry (content mods, docs/modpacks.md) costs, loader by loader. +//! +//! resource_memory RESOURCES +//! +//! RESOURCES is a prepared root or a content-mod root (`.horizon-cache/mod-content`). +//! Prints, after each step, the live heap (a counting allocator: what the +//! step keeps), the heap's peak during the step (what it parsed on the way) +//! and the process RSS (what the allocator holds on to). On macOS it ends +//! with `footprint`'s physical footprint, the number the OS charges: RSS also +//! counts freed pages the allocator marked reusable. +use horizon_client::{ + assets::Assets, biome::Biomes, blocks::BlockFacts, collisions, crafting::Recipes, items::Items, + light::LightTables, mesher::MeshTables, models, motion::MotionResources, + vanillagen::VanillaTerrain, +}; +use std::{ + alloc::{GlobalAlloc, Layout, System}, + sync::atomic::{AtomicUsize, Ordering::Relaxed}, +}; +use std::{path::PathBuf, process::Command}; +type Result = std::result::Result>; + +struct Counting; +static LIVE: AtomicUsize = AtomicUsize::new(0); +static PEAK: AtomicUsize = AtomicUsize::new(0); +// SAFETY: forwards to the system allocator, only counting sizes. +unsafe impl GlobalAlloc for Counting { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + let p = unsafe { System.alloc(layout) }; + if !p.is_null() { + let now = LIVE.fetch_add(layout.size(), Relaxed) + layout.size(); + PEAK.fetch_max(now, Relaxed); + } + p + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + unsafe { System.dealloc(ptr, layout) }; + LIVE.fetch_sub(layout.size(), Relaxed); + } + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new: usize) -> *mut u8 { + let p = unsafe { System.realloc(ptr, layout, new) }; + if !p.is_null() { + if new >= layout.size() { + let now = LIVE.fetch_add(new - layout.size(), Relaxed) + new - layout.size(); + PEAK.fetch_max(now, Relaxed); + } else { + LIVE.fetch_sub(layout.size() - new, Relaxed); + } + } + p + } +} +#[global_allocator] +static ALLOC: Counting = Counting; +const MB: f64 = 1048576.0; + +fn rss_mb() -> f64 { + let out = Command::new("ps") + .args(["-o", "rss=", "-p", &std::process::id().to_string()]) + .output() + .ok(); + out.and_then(|o| String::from_utf8(o.stdout).ok()) + .and_then(|s| s.trim().parse::().ok()) + .map_or(0.0, |kb| kb / 1024.0) +} + +fn main() -> Result<()> { + let root = PathBuf::from( + std::env::args() + .nth(1) + .ok_or("usage: resource_memory RESOURCES")?, + ); + println!( + "{:<24} {:>8} {:>8} {:>10} {:>8}", + "step", "live MB", "+live", "step peak", "RSS MB" + ); + let mut last = 0usize; + let mut step = |name: &str| { + let live = LIVE.load(Relaxed); + let peak = PEAK.swap(live, Relaxed); + println!( + "{name:<24} {:>8.0} {:>+8.0} {:>10.0} {:>8.0}", + live as f64 / MB, + (live as f64 - last as f64) / MB, + peak as f64 / MB, + rss_mb() + ); + last = live; + }; + step("start"); + let registry = horizon_world::level::data::load_registry(&root)?; + step("registry alone"); + drop(registry); + step("registry dropped"); + let assets = Assets::load(&root)?; + step("assets"); + println!( + " sprites: {} layers of {}px, {:.0} MB of pixels", + assets.texture_layers, + assets.sprite_size, + assets.pixels.len() as f64 / MB + ); + // The game decodes gameplay facts once for both tables (BlockFacts::load_pair). + let (facts, behaviours) = BlockFacts::load_pair(&root, assets.registry)?; + step("block facts+behaviours"); + let items = Items::load(&root, assets.registry, &facts)?; + step("items"); + let recipes = Recipes::load(&root, &items)?; + step("recipes"); + let biomes = Biomes::load(&root)?; + step("biomes"); + let light = LightTables::load(&root, assets.registry, &facts)?; + step("light tables"); + let tables = MeshTables::new( + &assets, + &facts, + models::load_visibility(&root, assets.registry)?, + )?; + step("mesh tables"); + let collision = collisions::load(&root, assets.registry)?; + step("collision"); + let motion = MotionResources::load_with_facts(&root, &assets, &facts)?; + step("motion"); + let terrain = VanillaTerrain::new(&root.join("worldgen"), assets.registry, &biomes, 1234)?; + step("worldgen"); + println!( + "{} block states; live {:.0} MB, RSS {:.0} MB", + facts.states.len(), + LIVE.load(Relaxed) as f64 / MB, + rss_mb() + ); + if let Ok(out) = Command::new("footprint") + .arg(std::process::id().to_string()) + .output() + { + let text = String::from_utf8_lossy(&out.stdout); + for line in text + .lines() + .filter(|l| l.contains("Footprint") || l.contains("phys_footprint")) + { + println!(" {}", line.trim()); + } + } + // Keep everything alive until the end. + drop(( + terrain, behaviours, motion, collision, tables, light, biomes, recipes, items, facts, + assets, + )); + Ok(()) +} diff --git a/crates/horizon-client/examples/save_batch_bench.rs b/crates/horizon-client/examples/save_batch_bench.rs index 11c4f64ed..4ee5103de 100644 --- a/crates/horizon-client/examples/save_batch_bench.rs +++ b/crates/horizon-client/examples/save_batch_bench.rs @@ -4,7 +4,7 @@ //! Exact NBT equality is always validated. No GPU, compression or disk I/O timed. use horizon_client::{ biome::Biomes, - chunk::{BLOCK_STRATEGY, Chunk}, + chunk::{Chunk, block_strategy}, containers::BlockEntity, items::ItemStack, save::{self, ChunkExtras}, @@ -64,7 +64,7 @@ fn fixture(per_chunk: usize) -> (Vec>, Entities, Names) { }; let mut template = Chunk::empty(0, 0); for s in &mut template.sections[..8] { - Arc::make_mut(s).blocks = PalettedContainer::new(BLOCK_STRATEGY, 1); + Arc::make_mut(s).blocks = PalettedContainer::new(block_strategy(), 1); } template.heights = Arc::new([64; 256]); for i in 0..256 { diff --git a/crates/horizon-client/examples/save_parity.rs b/crates/horizon-client/examples/save_parity.rs index ba2c4b0fa..3954e3bb3 100644 --- a/crates/horizon-client/examples/save_parity.rs +++ b/crates/horizon-client/examples/save_parity.rs @@ -257,9 +257,9 @@ fn main() -> horizon_client::Result<()> { ); Ok(()) } -fn tables_air(assets: &Assets) -> u16 { +fn tables_air(assets: &Assets) -> u32 { assets .registry .default_state("minecraft:air") - .map_or(0, |s| s.0 as u16) + .map_or(0, |s| s.0) } diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index a42448794..6359f32d0 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -83,7 +83,7 @@ fn scene( for block in row["blocks"].as_array().ok_or("missing blocks")? { let (x, y, z) = (int(&block[0])?, int(&block[1])?, int(&block[2])?); let i = chunk_index(x, z)?; - chunks[i].set(x & 15, y, z & 15, u16::try_from(int(&block[3])?)?); + chunks[i].set(x & 15, y, z & 15, u32::try_from(int(&block[3])?)?); } for cell in row["lights"].as_array().ok_or("missing lights")? { let (x, y, z) = (int(&cell[0])?, int(&cell[1])?, int(&cell[2])?); diff --git a/crates/horizon-client/examples/tooltip_display_fixture.rs b/crates/horizon-client/examples/tooltip_display_fixture.rs new file mode 100644 index 000000000..ec61159cd --- /dev/null +++ b/crates/horizon-client/examples/tooltip_display_fixture.rs @@ -0,0 +1,40 @@ +//! Tooltip display visibility oracle companion for tools/test_tooltip_display_parity.py. +use horizon_client::{item_tooltip::TooltipDisplay, items::ItemStack}; +use horizon_world::nbt::Tag; +use std::{error::Error, fmt::Write}; + +fn main() -> Result<(), Box> { + let args: Vec = std::env::args().collect(); + let mut output = String::new(); + for line in std::fs::read_to_string(&args[1])?.lines() { + let fields: Vec<&str> = line.split('\t').collect(); + let hide_tooltip: bool = fields[0].parse()?; + let creative: bool = fields[1].parse()?; + let hide_attributes: bool = fields[2].parse()?; + let mut component = Vec::new(); + if hide_tooltip { + component.push(("hide_tooltip", Tag::Byte(1))); + } + if hide_attributes { + component.push(( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]), + )); + } + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + if !component.is_empty() { + stack + .data_mut() + .set_other("minecraft:tooltip_display", Some(Tag::compound(component))); + } + let display = TooltipDisplay::for_stack(&stack); + writeln!( + output, + "{}\t{}", + display.name_visible(creative), + display.shows("minecraft:attribute_modifiers") + )?; + } + std::fs::write(&args[2], output)?; + Ok(()) +} diff --git a/crates/horizon-client/src/advancements.rs b/crates/horizon-client/src/advancements.rs index 22ffcc9d7..16028e220 100644 --- a/crates/horizon-client/src/advancements.rs +++ b/crates/horizon-client/src/advancements.rs @@ -607,6 +607,29 @@ pub struct Entities<'a> { pub tool: Option<&'a ItemView>, pub block_pos: Option<[i32; 3]>, } +/// Conditions shared by item/entity interactions and thrown-item pickups. +pub fn item_entity( + v: &Value, + player: &EntityView, + target: &EntityView, + stack: &ItemView, + w: &dyn World, +) -> bool { + let pctx = Entities { + this: Some(player), + origin: player.position, + tool: None, + block_pos: None, + }; + let ectx = Entities { + this: Some(target), + ..pctx + }; + conditions(&v["player"], &pctx, w) + && conditions(&v["entity"], &ectx, w) + && item(&v["item"], stack, w) +} + /// A `ContextAwarePredicate`: a list of loot conditions (or one condition). pub fn conditions(v: &Value, ctx: &Entities, w: &dyn World) -> bool { match v { @@ -996,7 +1019,75 @@ mod tests { false } fn in_tag(&self, _: &str, tag: &str, id: &str) -> bool { - tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone" + (tag == "minecraft:stone_tool_materials" && id == "minecraft:cobblestone") + || (tag == "minecraft:sulfur_cube_archetype/explosive" && id == "minecraft:tnt") + } + } + #[test] + fn uh_oh_accepts_either_tnt_event_only_for_adult_sulfur_cubes() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join( + "../../.local/horizon-client/26.3/data/minecraft/advancement/husbandry/uh_oh.json", + ); + if !path.exists() { + return; + } + let json = serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap(); + let advancement = parse("minecraft:husbandry/uh_oh", &json).unwrap(); + assert_eq!(advancement.criteria.len(), 2); + let player = EntityView { + kind: "minecraft:player".into(), + ..Default::default() + }; + let mut target = EntityView { + kind: "minecraft:sulfur_cube".into(), + ..Default::default() + }; + let mut stack = ItemView { + id: "minecraft:tnt".into(), + count: 1, + ..Default::default() + }; + for criterion in &advancement.criteria { + assert!(item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + let mut progress = Progress::default(); + progress.grant(&advancement.id, &criterion.name, "test"); + assert!( + progress.done(&advancement), + "either criterion must award Uh Oh" + ); + target.baby = true; + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.baby = false; + target.kind = "minecraft:pig".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + target.kind = "minecraft:sulfur_cube".into(); + stack.id = "minecraft:stone".into(); + assert!(!item_entity( + &criterion.conditions, + &player, + &target, + &stack, + &Flat + )); + stack.id = "minecraft:tnt".into(); } } #[test] diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index b8551a059..c42f0aaf7 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -2,14 +2,13 @@ use crate::Result; use horizon_world::{ DATA_VERSION, heightmap::HeightmapState, - nbt::Tag, registry::{BlockRegistry, BlockStateId}, worldgen::{tags::TagDefinitions, terrain::TerrainBlockStates}, }; use serde_json::Value; use std::{ collections::BTreeSet, - fs::{self, File}, + fs::File, io::{self, BufReader}, path::Path, sync::Arc, @@ -74,24 +73,6 @@ pub struct Assets { fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) } -fn tag(value: &Value) -> Result { - Ok(match value { - Value::String(value) => Tag::String(value.as_str().into()), - Value::Number(value) => Tag::Int(i32::try_from( - value - .as_i64() - .ok_or_else(|| invalid("invalid registry number"))?, - )?), - Value::Array(values) => Tag::List(values.iter().map(tag).collect::>()?), - Value::Object(values) => Tag::Compound( - values - .iter() - .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) - .collect::>()?, - ), - _ => return Err(invalid("unsupported registry value").into()), - }) -} impl Assets { pub fn load(root: &Path) -> Result { let manifest: Value = serde_json::from_reader(BufReader::new(File::open( @@ -100,23 +81,8 @@ impl Assets { if manifest["data_version"].as_i64() != Some(i64::from(DATA_VERSION)) { return Err(invalid("resources do not match Horizon's pinned data version").into()); } - let facts: Value = serde_json::from_slice(&fs::read(root.join("facts.json"))?)?; - let states = facts["states"] - .as_array() - .ok_or_else(|| invalid("missing registry state facts"))?; - let registry = BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - states - .iter() - .map(|state| tag(&state[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ]))?; + let (registry, flags) = + BlockRegistry::from_facts_json_with_flags(File::open(root.join("facts.json"))?)?; let bundle: Value = serde_json::from_reader(BufReader::new(File::open(root.join("block-tags.json"))?))?; let mut definitions = TagDefinitions::default(); @@ -132,7 +98,7 @@ impl Assets { )?; } let built = - definitions.build(|name, _| facts["defaults"].get(name).map(|_| name.to_owned()))?; + definitions.build(|name, _| registry.default_state(name).map(|_| name.to_owned()))?; if !built.missing.is_empty() { return Err(invalid("unresolved block tags").into()); } @@ -158,27 +124,20 @@ impl Assets { .cloned() .collect(); let properties = Properties(Arc::new( - states + flags .iter() - .map(|state| { + .enumerate() + .map(|(i, &(air, fluid))| { + let name = ®istry + .state(BlockStateId(i as u32)) + .ok_or_else(|| invalid("missing registry state"))? + .name; Ok(StateFacts { - air: state[1] - .as_bool() - .ok_or_else(|| invalid("missing air fact"))?, - fluid: state[2] - .as_bool() - .ok_or_else(|| invalid("missing fluid fact"))?, - air_block: state[0].as_str() == Some("minecraft:air"), - motion: motion.contains( - state[0] - .as_str() - .ok_or_else(|| invalid("missing state name"))?, - ), - no_leaves: no_leaves.contains( - state[0] - .as_str() - .ok_or_else(|| invalid("missing state name"))?, - ), + air, + fluid, + air_block: name == "minecraft:air", + motion: motion.contains(name.as_str()), + no_leaves: no_leaves.contains(name.as_str()), }) }) .collect::>()?, @@ -189,6 +148,9 @@ impl Assets { .default_state(&format!("minecraft:{name}")) .ok_or_else(|| invalid("missing test-scene material"))?; } + // Chunks hold every state of this registry: content mods can take it + // past vanilla's 16-bit global palette. + crate::chunk::set_block_states(registry.len()); let registry: &'static BlockRegistry = Box::leak(Box::new(registry)); Self::with_models( root, diff --git a/crates/horizon-client/src/block_entities.rs b/crates/horizon-client/src/block_entities.rs new file mode 100644 index 000000000..93abb3711 --- /dev/null +++ b/crates/horizon-client/src/block_entities.rs @@ -0,0 +1,395 @@ +//! The world's block entities and the order they tick in: vanilla's +//! `Level.blockEntityTickers`, kept beside the block entity map so a tick +//! visits only the block entities that tick, in vanilla's order, instead of +//! scanning the whole map once per kind. +//! +//! The list follows `LevelChunk.updateBlockEntityTicker` and +//! `Level.tickBlockEntities`: +//! - a block entity whose block state has a ticker gets a slot at the end of +//! the list (through `pendingBlockEntityTickers`, so a slot made during a +//! tick first ticks on the next one); +//! - replacing the block entity at a position (`setBlockEntity`), or changing +//! its block state to another state with a ticker, keeps its slot +//! (`RebindableTickingBlockEntityWrapper.rebind`); +//! - removing it (`removeBlockEntity`), unloading its chunk +//! (`clearAllBlockEntities`) or changing its state to one without a ticker +//! (a jukebox losing its record) frees the slot; a later ticker there is +//! appended again; +//! - a loaded chunk's block entities are added in the iteration order of its +//! `Object2ObjectOpenHashMap` +//! (`registerAllBlockEntitiesAfterLevelLoad`), filled in the order the chunk +//! listed them. +//! +//! Which states tick is a table by state id, built by the game from the block +//! registry; whether a slot is made is decided when the slot is promoted at +//! the start of the next tick, from the block state then. +use crate::containers::BlockEntity; +use crate::fast_hash::{FxHashMap, FxHashSet}; +use std::collections::HashMap; + +pub type Pos = (i32, i32, i32); + +/// What a block state's block entity does each tick (`BlockState.getTicker`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Ticking { + /// No ticker, and the block has no block entity that could have one. + #[default] + No, + /// A ticker. + Yes, + /// The block's block entity, but this state has no ticker (a jukebox + /// without a record): a state change to it frees the slot. + Idle, +} + +#[derive(Default)] +pub struct BlockEntities { + map: HashMap, + /// `Level.blockEntityTickers`: positions and the slot each was given. + tickers: Vec<(Pos, u32)>, + /// `LevelChunk.tickersInLevel`: the live slot of each ticking position. + live: FxHashMap, + /// Positions that may need a slot, in the order vanilla would have made + /// it (`pendingBlockEntityTickers`), each with a token; decided at the + /// next promotion from the block state then. + added: Vec<(Pos, u32)>, + /// The token of each position's pending entry: an entry whose token is + /// not here any more was cancelled. + pending: FxHashMap, + next_slot: u32, + /// Whether a slot was freed since the list was last swept: otherwise + /// every slot in it is still live, unless its block entity is `out`. + freed: bool, + /// Positions whose block entity `take` took and `put` has not brought + /// back. + out: FxHashSet, + /// `Ticking` by block state id; empty until the game builds it. + states: Vec, +} + +impl std::ops::Deref for BlockEntities { + type Target = HashMap; + fn deref(&self) -> &Self::Target { + &self.map + } +} + +impl<'a> IntoIterator for &'a BlockEntities { + type Item = (&'a Pos, &'a BlockEntity); + type IntoIter = std::collections::hash_map::Iter<'a, Pos, BlockEntity>; + fn into_iter(self) -> Self::IntoIter { + self.map.iter() + } +} + +/// `Vec3i.hashCode`. +fn java_hash((x, y, z): Pos) -> i32 { + y.wrapping_add(z.wrapping_mul(31)) + .wrapping_mul(31) + .wrapping_add(x) +} +/// `HashCommon.mix`. +fn mix(x: i32) -> usize { + let h = (x as u32).wrapping_mul(0x9E37_79B9); + (h ^ (h >> 16)) as usize +} + +/// The order `values().forEach` visits a `new Object2ObjectOpenHashMap<>()` +/// keyed by these positions, put in this order (repeats keep their first +/// slot): open addressing with linear probing, a rehash to twice the size +/// past three quarters full, and iteration from the last slot down. +pub fn chunk_map_order(positions: impl IntoIterator) -> Vec { + // HashCommon.arraySize(16, .75f), and maxFill of each size. + let mut slots: Vec> = vec![None; 32]; + let max_fill = |n: usize| (n * 3).div_ceil(4).min(n - 1); + let mut size = 0; + for p in positions { + let mask = slots.len() - 1; + let mut at = mix(java_hash(p)) & mask; + let mut known = false; + while let Some(k) = slots[at] { + if k == p { + known = true; + break; + } + at = (at + 1) & mask; + } + if known { + continue; + } + slots[at] = Some(p); + // `if (size++ >= maxFill) rehash(arraySize(size + 1, f))`, which + // puts the keys back from the last slot down. + size += 1; + if size > max_fill(slots.len()) { + let n = ((size + 1) * 4).div_ceil(3).next_power_of_two(); + let old = std::mem::replace(&mut slots, vec![None; n]); + for k in old.into_iter().rev().flatten() { + let mut at = mix(java_hash(k)) & (n - 1); + while slots[at].is_some() { + at = (at + 1) & (n - 1); + } + slots[at] = Some(k); + } + } + } + slots.into_iter().rev().flatten().collect() +} + +impl BlockEntities { + /// Whether the ticking table has been built. + pub fn has_states(&self) -> bool { + !self.states.is_empty() + } + pub fn set_states(&mut self, states: Vec) { + self.states = states; + } + pub fn take_states(&mut self) -> Vec { + std::mem::take(&mut self.states) + } + pub fn ticking(&self, state: u32) -> Ticking { + self.states.get(state as usize).copied().unwrap_or_default() + } + + fn next(&mut self) -> u32 { + let n = self.next_slot; + self.next_slot = n.wrapping_add(1); + n + } + /// A ticker may be made for `pos` now (`updateBlockEntityTicker`). + fn add(&mut self, pos: Pos) { + let token = self.next(); + self.pending.insert(pos, token); + self.added.push((pos, token)); + } + /// `removeBlockEntityTicker`: no slot, made or pending. + fn cancel(&mut self, pos: &Pos) { + self.freed |= self.live.remove(pos).is_some(); + self.pending.remove(pos); + } + + pub fn get_mut(&mut self, pos: &Pos) -> Option<&mut BlockEntity> { + self.map.get_mut(pos) + } + pub fn iter_mut(&mut self) -> impl Iterator { + self.map.iter_mut() + } + pub fn values_mut(&mut self) -> impl Iterator { + self.map.values_mut() + } + /// `LevelChunk.setBlockEntity` (+ `addAndRegisterBlockEntity`): a new + /// block entity may get a slot; one replacing another keeps its slot. + pub fn insert(&mut self, pos: Pos, entity: BlockEntity) -> Option { + let old = self.map.insert(pos, entity); + if old.is_none() { + self.add(pos); + } + old + } + /// The block entity at `pos`, made by `make` when there is none. + pub fn get_or_insert_with( + &mut self, + pos: Pos, + make: impl FnOnce() -> BlockEntity, + ) -> &mut BlockEntity { + if !self.map.contains_key(&pos) { + self.add(pos); + } + self.map.entry(pos).or_insert_with(make) + } + /// `LevelChunk.removeBlockEntity`: the block entity and its slot. + pub fn remove(&mut self, pos: &Pos) -> Option { + self.cancel(pos); + self.map.remove(pos) + } + /// The block entity at `pos`, out of the map for a while: its slot stays + /// for `put` to bring it back (a tick working on it). + pub fn take(&mut self, pos: &Pos) -> Option { + let taken = self.map.remove(pos); + if taken.is_some() { + self.out.insert(*pos); + } + taken + } + /// Brings back what `take` took, in its slot. + pub fn put(&mut self, pos: Pos, entity: BlockEntity) { + self.out.remove(&pos); + if self.map.insert(pos, entity).is_none() + && !self.live.contains_key(&pos) + && !self.pending.contains_key(&pos) + { + self.add(pos); + } + } + /// Removes the block entities `keep` refuses, and their slots + /// (`clearAllBlockEntities` of unloaded chunks). + pub fn retain(&mut self, mut keep: impl FnMut(&Pos, &mut BlockEntity) -> bool) { + let (live, pending, freed) = (&mut self.live, &mut self.pending, &mut self.freed); + self.map.retain(|p, e| { + let kept = keep(p, e); + if !kept { + *freed |= live.remove(p).is_some(); + pending.remove(p); + } + kept + }); + } + pub fn clear(&mut self) { + self.map.clear(); + self.tickers.clear(); + self.live.clear(); + self.added.clear(); + self.pending.clear(); + self.out.clear(); + self.freed = false; + } + /// A loaded or generated chunk's block entities, in the order the chunk + /// lists them; they tick in its block entity map's order + /// (`registerAllBlockEntitiesAfterLevelLoad`). + pub fn load_chunk(&mut self, entities: Vec<(Pos, BlockEntity)>) { + let order = chunk_map_order(entities.iter().map(|(p, _)| *p)); + for (p, e) in entities { + self.map.insert(p, e); + } + for p in order { + self.add(p); + } + } + /// `LevelChunk.setBlockState` on a block entity's position, from state + /// `old` to `new`: a ticker made, kept or dropped. + pub fn state_changed(&mut self, pos: Pos, old: u32, new: u32) { + if self.states.is_empty() || !self.map.contains_key(&pos) { + return; + } + match self.ticking(new) { + // A new ticker, unless one was made or is pending (rebound). + Ticking::Yes => { + if self.ticking(old) != Ticking::Yes && !self.live.contains_key(&pos) { + self.add(pos); + } + } + Ticking::Idle => self.cancel(&pos), + // Another block: the game removes or replaces the block entity. + Ticking::No => {} + } + } + /// The start of `Level.tickBlockEntities`: pending slots join the list + /// and freed ones leave it. `state` reads the block state at a position. + /// Returns the slots to tick, in order; check each with `is_live` before + /// ticking it, as the ticks before it can free it. + pub fn tickers(&mut self, state: impl Fn(Pos) -> u32) -> Vec<(Pos, u32)> { + for (pos, token) in std::mem::take(&mut self.added) { + if self.pending.get(&pos) != Some(&token) { + continue; + } + self.pending.remove(&pos); + if self.live.contains_key(&pos) + || !self.map.contains_key(&pos) + || self.ticking(state(pos)) != Ticking::Yes + { + continue; + } + let slot = self.next(); + self.live.insert(pos, slot); + self.tickers.push((pos, slot)); + } + if !std::mem::take(&mut self.freed) && self.out.is_empty() { + return self.tickers.clone(); + } + self.out.clear(); + let (live, map) = (&mut self.live, &self.map); + self.tickers.retain(|(p, slot)| { + let mine = live.get(p) == Some(slot); + if mine && !map.contains_key(p) { + live.remove(p); + } + mine && map.contains_key(p) + }); + self.tickers.clone() + } + /// Whether a slot from `tickers` still ticks. + pub fn is_live(&self, (pos, slot): (Pos, u32)) -> bool { + self.live.get(&pos) == Some(&slot) && self.map.contains_key(&pos) + } + /// Frees the slot at `pos` (the block entity stays). + pub fn forget(&mut self, pos: &Pos) { + self.cancel(pos); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hopper() -> BlockEntity { + BlockEntity::Chest(vec![None; 5]) + } + /// States: 0 air, 1 ticks, 2 idle. + fn level() -> BlockEntities { + let mut b = BlockEntities::default(); + b.set_states(vec![Ticking::No, Ticking::Yes, Ticking::Idle]); + b + } + fn order(b: &mut BlockEntities, states: &HashMap) -> Vec { + b.tickers(|p| states.get(&p).copied().unwrap_or(0)) + .into_iter() + .map(|(p, _)| p) + .collect() + } + + #[test] + fn slots_follow_vanilla_lifecycle() { + let mut b = level(); + let mut s = HashMap::new(); + for p in [(0, 0, 0), (1, 0, 0), (2, 0, 0)] { + s.insert(p, 1); + b.insert(p, hopper()); + } + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]); + // Replacing keeps the slot; removing and placing again appends. + b.insert((0, 0, 0), hopper()); + b.remove(&(1, 0, 0)); + b.insert((1, 0, 0), hopper()); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]); + // Take and put keep it; an idle state frees it, ticking again appends. + let e = b.take(&(0, 0, 0)).unwrap(); + b.put((0, 0, 0), e); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (2, 0, 0), (1, 0, 0)]); + s.insert((2, 0, 0), 2); + b.state_changed((2, 0, 0), 1, 2); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0)]); + s.insert((2, 0, 0), 1); + b.state_changed((2, 0, 0), 2, 1); + assert_eq!(order(&mut b, &s), [(0, 0, 0), (1, 0, 0), (2, 0, 0)]); + // A slot freed during a tick is not live any more. + let slots = b.tickers(|p| s.get(&p).copied().unwrap_or(0)); + b.retain(|p, _| *p != (1, 0, 0)); + assert!(b.is_live(slots[0]) && !b.is_live(slots[1])); + // A block entity taken and never brought back loses its slot. + b.take(&(0, 0, 0)); + assert_eq!(order(&mut b, &s), [(2, 0, 0)]); + assert_eq!(order(&mut b, &s), [(2, 0, 0)]); + } + + #[test] + fn chunk_loads_in_open_hash_map_order() { + // A few keys: their mixed hashes over 32 slots, read from the top. + let positions = [ + (0, 64, 0), + (1, 64, 0), + (0, 64, 1), + (15, -64, 15), + (3, 70, 9), + ]; + let slot = |p: &Pos| mix(java_hash(*p)) & 31; + let mut expected = positions.to_vec(); + expected.sort_by_key(|p| std::cmp::Reverse(slot(p))); + let distinct: std::collections::HashSet = positions.iter().map(slot).collect(); + assert_eq!(distinct.len(), positions.len()); + assert_eq!(chunk_map_order(positions), expected); + // Past 24 keys the table doubles; every key stays, once. + let many: Vec = (0..100).map(|i| (i % 16, i / 16, 3)).collect(); + let order = chunk_map_order(many.iter().copied().chain(many.iter().copied())); + assert_eq!(order.len(), 100); + } +} diff --git a/crates/horizon-client/src/block_entity_render.rs b/crates/horizon-client/src/block_entity_render.rs index 9c90e8ebf..db6bf7b79 100644 --- a/crates/horizon-client/src/block_entity_render.rs +++ b/crates/horizon-client/src/block_entity_render.rs @@ -737,6 +737,8 @@ pub struct Scene<'a> { pub struct BlockEntityRenderer { models: HashMap<&'static str, ModelPart>, kinds: Vec, + // Closed chest geometry: dimension lighting, chest part, horizontal facing. + closed_chests: [[[Vec; 4]; 3]; 2], /// Item id to its `PROVIDES_POTTERY_PATTERN` side texture (`Sheets.DECORATED_POT_MAPPER`). pot_patterns: HashMap, /// `Block.shouldRenderFace` for End gateway faces (its occlusion pair cache needs a lock). @@ -817,6 +819,43 @@ impl BlockEntityRenderer { Ok(renderer) } fn new(models: HashMap<&'static str, ModelPart>, registry: &BlockRegistry) -> Self { + let closed_chests = [false, true].map(|nether| { + ["chest", "double_chest_left", "double_chest_right"].map(|name| { + [0.0f32, 90.0, 180.0, 270.0].map(|y_rot| { + let mut vertices = Vec::new(); + if let Some(model) = models.get(name) { + draw_part( + model, + "root", + around( + Mat4::from_rotation_y((-y_rot).to_radians()), + Vec3::new(0.5, 0.0, 0.5), + ), + &|name, p| { + if name == "lid" || name == "lock" { + p[3] = crate::block_entity_anim::chest_lid_x_rot(0.0); + } + }, + Paint { + sprite: Rect { + u0: 0.0, + v0: 0.0, + u1: 1.0, + v1: 1.0, + w: 16, + h: 16, + }, + tint: 0xFFFFFF, + light: 0, + lights: diffuse_lights(nether), + }, + &mut vertices, + ); + } + vertices + }) + }) + }); let kinds = (0..registry.len() as u32) .map(|id| { registry.state(BlockStateId(id)).map_or(Kind::None, |s| { @@ -831,6 +870,7 @@ impl BlockEntityRenderer { Self { models, kinds, + closed_chests, pot_patterns: HashMap::new(), visibility: None, } @@ -876,7 +916,7 @@ impl BlockEntityRenderer { .as_vec3(); let base = Mat4::from_translation(origin); let packed = scene.world.light(pos[0], pos[1], pos[2]); - self.render_one(scene, *pos, kind, base, packed, lights, false, out); + self.render_one(scene, *pos, kind, base, packed, lights, false, true, out); } } /// One block entity at `pos` drawn under `base` with the given packed light @@ -892,7 +932,7 @@ impl BlockEntityRenderer { ) { let kind = self.kind(state); let lights = diffuse_lights(scene.nether); - self.render_one(scene, pos, kind, base, packed, lights, false, out); + self.render_one(scene, pos, kind, base, packed, lights, false, false, out); } /// Whether this block state has a block-entity renderer here. pub fn renders(&self, state: u32) -> bool { @@ -915,6 +955,7 @@ impl BlockEntityRenderer { 0xff, diffuse_lights(scene.nether), true, + false, out, ); crate::breaking::entity_geometry(&mut out[start..], origin); @@ -991,7 +1032,17 @@ impl BlockEntityRenderer { let kind = self.kind(state); if !matches!(kind, Kind::None) { let lights = diffuse_lights(scene.nether); - self.render_one(scene, [i32::MAX; 3], kind, base, packed, lights, false, out); + self.render_one( + scene, + [i32::MAX; 3], + kind, + base, + packed, + lights, + false, + false, + out, + ); } } #[allow(clippy::too_many_arguments)] @@ -1004,6 +1055,7 @@ impl BlockEntityRenderer { packed: u8, lights: (Vec3, Vec3), crumbling: bool, + world_chests: bool, out: &mut Vec, ) { let sprite = |name: &str| scene.sprites.get(name).copied(); @@ -1107,6 +1159,23 @@ impl BlockEntityRenderer { let l = scene.world.light(other[0], other[1], other[2]); packed = (packed >> 4).max(l >> 4) << 4 | (packed & 15).max(l & 15); } + if world_chests && open == 0.0 { + if let Some(paint) = paint(texture, 0xFFFFFF, packed) { + let vertices = &self.closed_chests[usize::from(scene.nether)] + [*part as usize][*y_rot as usize / 90]; + let origin = base.w_axis.truncate(); + out.extend(vertices.iter().map(|v| Vertex { + pos: (Vec3::from_array(v.pos) + origin).to_array(), + uv: [ + paint.sprite.u0 + (paint.sprite.u1 - paint.sprite.u0) * v.uv[0], + paint.sprite.v0 + (paint.sprite.v1 - paint.sprite.v0) * v.uv[1], + ], + light: paint.light, + ..*v + })); + } + return; + } let m = base * around( Mat4::from_rotation_y((-y_rot).to_radians()), @@ -1791,16 +1860,18 @@ mod tests { ( name.to_owned(), Rect { - u0: 0.0, - v0: 0.0, - u1: 1.0, - v1: 1.0, + u0: 0.25, + v0: 0.125, + u1: 0.375, + v1: 0.25, w: 16, h: 16, }, ) }) .collect(); + let cache_open = std::cell::Cell::new(0.0); + let cache_lid = |_| cache_open.get(); let mut scene = Scene { camera: DVec3::ZERO, orientation: Quat::IDENTITY, @@ -1817,6 +1888,56 @@ mod tests { banner: &|_| Vec::new(), glyph: &|_| (None, 0.0), }; + // Compare the cached world path with the original model renderer, + // including atlas replacement, current light and animated fallback. + scene.lid = &cache_lid; + for nether in [false, true] { + scene.nether = nether; + for part in [ChestPart::Single, ChestPart::Left, ChestPart::Right] { + for y_rot in [0.0, 90.0, 180.0, 270.0] { + let kind = Kind::Chest { + block: "chest".into(), + texture: "entity/chest/normal", + part, + y_rot, + double_with: None, + }; + for (open, packed) in [(0.0, 0xF0), (0.0, 0x7F), (0.5, 0x7F)] { + cache_open.set(open); + let base = Mat4::from_translation(Vec3::new(3.25, -8.5, 12.75)); + let mut cached = Vec::new(); + let mut original = Vec::new(); + for (use_cache, out) in [(true, &mut cached), (false, &mut original)] { + renderer.render_one( + &scene, + [0; 3], + &kind, + base, + packed, + diffuse_lights(nether), + false, + use_cache, + out, + ); + } + assert!(!cached.is_empty()); + assert_eq!(cached.len(), original.len()); + for (a, b) in cached.iter().zip(&original) { + assert!( + (Vec3::from_array(a.pos) - Vec3::from_array(b.pos)).length() < 3e-6 + ); + assert_eq!(a.uv, b.uv); + assert_eq!(a.color, b.color); + assert_eq!(a.light, b.light); + assert_eq!(a.normal, b.normal); + assert_eq!(a.layer, b.layer); + } + } + } + } + } + scene.nether = false; + scene.lid = &|_| 0.0; for state in 0..names.len() as u32 { let mut base = Vec::new(); renderer.render_block(&scene, [0; 3], state, Mat4::IDENTITY, 0xff, &mut base); diff --git a/crates/horizon-client/src/chat.rs b/crates/horizon-client/src/chat.rs index 6156a041d..7c51a40f1 100644 --- a/crates/horizon-client/src/chat.rs +++ b/crates/horizon-client/src/chat.rs @@ -386,6 +386,12 @@ pub struct ChatScreen { parse: Option, /// The completions at the cursor (`pendingSuggestions`): range start (bytes) and list. pending: Option<(usize, Vec)>, + /// Completions waiting for the server's (an `ask_server` node at the + /// cursor): `pendingSuggestions` is not done until they come. + awaiting: Option, + /// The request to send (`ServerboundCommandSuggestionPacket`): id and + /// the command up to the cursor. + request: Option<(i32, String)>, suggestions: Option, usage: Vec, usage_position: i32, @@ -394,6 +400,16 @@ pub struct ChatScreen { keep_suggestions: bool, pub auto_suggestions: bool, } +/// Local completions waiting for the server's reply to request `id`. +struct Awaiting { + id: i32, + /// The command up to the cursor, as sent. + truncated: String, + local: Vec, +} +/// `ClientSuggestionProvider.pendingSuggestionsId`: one counter for the +/// connection, so a reply to an older request never matches. +static SUGGESTION_ID: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0); /// `CommandSuggestions`' fill colour. const FILL: i32 = -805306368; fn byte_at(s: &str, chars: usize) -> usize { @@ -442,6 +458,8 @@ impl ChatScreen { history_pos: history_len, parse: None, pending: None, + awaiting: None, + request: None, suggestions: None, usage: Vec::new(), usage_position: 0, @@ -518,24 +536,84 @@ impl ChatScreen { } if cursor >= 1 && (self.suggestions.is_none() || !self.keep_suggestions) { let parse = self.parse.as_ref().expect("parsed above"); - let (range, list) = c - .dispatcher - .client_suggestions(parse, cursor_b, c.registries); - self.pending = Some((range.0, list)); - self.update_usage_info(m, c); + let (range, list, ask) = + c.dispatcher + .client_suggestions_asking(parse, cursor_b, c.registries); + if ask { + // ClientSuggestionProvider.customSuggestion: the + // suggestions are done when the server answers. + let id = SUGGESTION_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1; + let truncated = command[..cursor_b].to_owned(); + self.request = Some((id, truncated.clone())); + self.awaiting = Some(Awaiting { + id, + truncated, + local: list, + }); + self.pending = None; + } else { + self.awaiting = None; + self.pending = Some((range.0, list)); + self.update_usage_info(m, c); + } } } else if !command.chars().all(char::is_whitespace) { let partial = &command[..cursor_b]; let mut builder = SuggestionsBuilder::new(partial, last_word_index(partial)); builder.suggest_matching(c.registries.players.iter().map(String::as_str)); let (range, list) = merge_suggestions(partial, builder.out); + self.awaiting = None; self.pending = Some((range.0, list)); self.usage_width = 0; self.usage_position = 0; } else { + self.awaiting = None; self.pending = None; } } + /// The completion request to send to the server, if one is waiting. + pub fn take_request(&mut self) -> Option<(i32, String)> { + self.request.take() + } + /// `ClientSuggestionProvider.completeCustomSuggestions`: the server's + /// completions for request `id`, with `range` in UTF-16 units of the + /// command sent. They join the local ones (`Suggestions.merge`) and the + /// pending suggestions are done. + pub fn server_suggestions( + &mut self, + m: &Measure, + c: &Commands, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let Some(awaiting) = self.awaiting.take_if(|a| a.id == id) else { + return; + }; + let input = &awaiting.truncated; + let byte = |units: usize| { + let mut n = 0; + input + .char_indices() + .find(|(_, ch)| { + let past = n >= units; + n += ch.len_utf16(); + past + }) + .map_or(input.len(), |(i, _)| i) + }; + let range = (byte(range.0), byte(range.0 + range.1)); + let mut all = awaiting.local; + all.extend(list.into_iter().map(|(text, tooltip)| Suggestion { + range, + text, + tooltip, + int_value: None, + })); + let (range, list) = merge_suggestions(input, all); + self.pending = Some((range.0, list)); + self.update_usage_info(m, c); + } /// `CommandSuggestions.updateUsageInfo`. fn update_usage_info(&mut self, m: &Measure, c: &Commands) { let Some(parse) = &self.parse else { return }; diff --git a/crates/horizon-client/src/chat_tests.rs b/crates/horizon-client/src/chat_tests.rs index 3cbac071b..e1bf2feda 100644 --- a/crates/horizon-client/src/chat_tests.rs +++ b/crates/horizon-client/src/chat_tests.rs @@ -230,3 +230,58 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() { screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); assert_eq!(screen.value(), "/coords"); } + +#[test] +fn ask_server_nodes_wait_for_the_servers_completions() { + // ClientSuggestionProvider.customSuggestion: an `ask_server` node at the + // cursor sends the command so far, and the list is done with the reply. + let font = font(); + let m = Measure(&font); + let registries = Registries { + permission: 4, + ..Registries::default() + }; + let mut d = crate::command::vanilla::game_dispatcher().clone(); + let child = |d: &crate::command::Dispatcher, n: usize, name: &str| { + d.nodes[n] + .children + .iter() + .copied() + .find(|&c| d.nodes[c].name() == name) + .expect(name) + }; + let id = child(&d, child(&d, child(&d, 0, "bossbar"), "get"), "id"); + d.nodes[id].suggests = Some(crate::command::Suggests::AskServer); + let c = Commands { + dispatcher: &d, + registries: ®istries, + }; + let tab = |screen: &mut ChatScreen| { + screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false); + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + let (request, sent) = screen.take_request().expect("the server is asked"); + assert_eq!(sent, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); + // Nothing to complete until the reply. + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + // A reply to an older request is dropped; the range is in UTF-16 units. + let reply = |text: &str| vec![(text.to_owned(), None)]; + screen.server_suggestions(&m, &c, request - 1, (13, 2), reply("pt6:old")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt"); + screen.server_suggestions(&m, &c, request, (13, 2), reply("pt6:check")); + tab(&mut screen); + assert_eq!(screen.value(), "/bossbar get pt6:check"); + // Without the server's provider the local list is done at once. + let local = crate::command::vanilla::game_dispatcher(); + let c = Commands { + dispatcher: local, + registries: ®istries, + }; + let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360); + screen.type_text(&m, &c, "/bossbar get pt"); + assert_eq!(screen.take_request(), None); +} diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index b0b2ef262..ce2c4ea71 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -9,11 +9,26 @@ pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; pub const SECTIONS: usize = (HEIGHT / 16) as usize; -/// Block states are `PalettedContainer`s over the pinned registry (35,723 -/// states: a 16-bit global palette); biomes are 4x4x4 containers over the -/// biome table (67 entries: a 7-bit global palette). -pub const BLOCK_STRATEGY: Strategy = Strategy::blocks(16); +/// Biomes are 4x4x4 containers over the biome table (67 entries: a 7-bit +/// global palette). pub const BIOME_STRATEGY: Strategy = Strategy::biomes(7); + +/// Bits of the block states' global palette: 16 for vanilla's 35,723 states +/// (what vanilla servers and clients send), more when content mods add states +/// past 65,536 (docs/modpacks.md). Set once, before the first chunk. +static BLOCK_BITS: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(16); + +/// Block states are `PalettedContainer`s over the registry: vanilla's 16-bit +/// global palette, wider with enough content mods. +pub fn block_strategy() -> Strategy { + Strategy::blocks(BLOCK_BITS.load(std::sync::atomic::Ordering::Relaxed)) +} + +/// Sizes the block states' global palette for a registry of `states`. +pub fn set_block_states(states: usize) { + let bits = horizon_core::paletted::ceil_log2(states).max(16); + BLOCK_BITS.store(bits, std::sync::atomic::Ordering::Relaxed); +} /// Packed light per block: sky light in the high nibble, block light in the low one. #[derive(Clone)] pub enum Light { @@ -43,7 +58,7 @@ pub struct Section { impl Default for Section { fn default() -> Self { Self { - blocks: PalettedContainer::new(BLOCK_STRATEGY, 0), + blocks: PalettedContainer::new(block_strategy(), 0), biomes: PalettedContainer::new(BIOME_STRATEGY, 0), light: Light::Uniform(0xF0), } @@ -51,27 +66,26 @@ impl Default for Section { } impl Section { #[inline] - pub fn get(&self, i: usize) -> u16 { - self.blocks.get(i) as u16 + pub fn get(&self, i: usize) -> u32 { + self.blocks.get(i) } - pub fn set(&mut self, i: usize, v: u16) -> u16 { - self.blocks.set(i, u32::from(v)) as u16 + pub fn set(&mut self, i: usize, v: u32) -> u32 { + self.blocks.set(i, v) } /// All 4,096 block states in index order. - pub fn unpack(&self, out: &mut [u16; 4096]) { - self.blocks.unpack_u16(out); + pub fn unpack(&self, out: &mut [u32; 4096]) { + self.blocks.unpack(out); } /// The block states of a whole section at once. - pub fn from_blocks(values: &[u16; 4096]) -> PalettedContainer { - let wide: Vec = values.iter().map(|&v| u32::from(v)).collect(); - PalettedContainer::from_values(BLOCK_STRATEGY, &wide) + pub fn from_blocks(values: &[u32; 4096]) -> PalettedContainer { + PalettedContainer::from_values(block_strategy(), values) } #[inline] pub fn light(&self, i: usize) -> u8 { self.light.get(i) } - pub fn is_uniform(&self, v: u16) -> bool { - self.blocks.is_uniform(u32::from(v)) + pub fn is_uniform(&self, v: u32) -> bool { + self.blocks.is_uniform(v) } /// Heap bytes held by the block, biome and light storage (benchmark accounting). pub fn heap_bytes(&self) -> usize { @@ -147,7 +161,7 @@ impl Chunk { } } #[inline] - pub fn get(&self, x: i32, y: i32, z: i32) -> u16 { + pub fn get(&self, x: i32, y: i32, z: i32) -> u32 { let s = (y - MIN_Y) >> 4; if !(0..SECTIONS as i32).contains(&s) { return 0; @@ -156,11 +170,11 @@ impl Chunk { } #[inline] pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { - BlockStateId(u32::from(self.get(x, y, z))) + BlockStateId(self.get(x, y, z)) } /// The highest y where `matches`, scanning down. Sections holding only /// `skip` are passed over whole: `matches` must be false for it. - pub fn highest(&self, skip: u16, mut matches: impl FnMut(i32) -> bool) -> Option { + pub fn highest(&self, skip: u32, mut matches: impl FnMut(i32) -> bool) -> Option { self.sections .iter() .enumerate() @@ -171,7 +185,7 @@ impl Chunk { (base..base + 16).rev().find(|&y| matches(y)) }) } - pub fn set(&mut self, x: i32, y: i32, z: i32, v: u16) -> u16 { + pub fn set(&mut self, x: i32, y: i32, z: i32, v: u32) -> u32 { let s = (y - MIN_Y) >> 4; if !(0..SECTIONS as i32).contains(&s) { return v; @@ -228,15 +242,15 @@ mod tests { Arc::make_mut(&mut chunk.sections[5]).set(i, cave_air); } chunk.set(3, 150, 4, stone); - let full = |c: &Chunk, matches: &dyn Fn(u16) -> bool| { + let full = |c: &Chunk, matches: &dyn Fn(u32) -> bool| { (MIN_Y..MIN_Y + HEIGHT) .rev() .find(|&y| matches(c.get(3, y, 4))) }; for matches in [ - &(|v: u16| v != air) as &dyn Fn(u16) -> bool, - &|v: u16| v == stone, - &|v: u16| v == cave_air, + &(|v: u32| v != air) as &dyn Fn(u32) -> bool, + &|v: u32| v == stone, + &|v: u32| v == cave_air, ] { let fast = chunk.highest(air, |y| matches(chunk.get(3, y, 4))); assert_eq!(fast, full(&chunk, matches)); diff --git a/crates/horizon-client/src/chunk_map.rs b/crates/horizon-client/src/chunk_map.rs index 81e06f020..ed25491c5 100644 --- a/crates/horizon-client/src/chunk_map.rs +++ b/crates/horizon-client/src/chunk_map.rs @@ -76,7 +76,7 @@ impl<'a> IntoIterator for &'a ChunkMap { } } impl crate::light::LightWorld for ChunkMap { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + fn state(&self, x: i32, y: i32, z: i32) -> Option { self.columns.state(x, y, z) } fn light(&self, x: i32, y: i32, z: i32) -> Option { diff --git a/crates/horizon-client/src/collisions.rs b/crates/horizon-client/src/collisions.rs index d3e00daca..5d5f4c1bb 100644 --- a/crates/horizon-client/src/collisions.rs +++ b/crates/horizon-client/src/collisions.rs @@ -15,24 +15,18 @@ use horizon_world::{ entity_obstruction::EntityIdentity, fluid::{FluidKind, FluidState}, liquid_collision::LiquidCollisionWorld, - nbt::{self, Limits}, powder_snow_collision::{PowderSnowEntity, PowderSnowWorld}, - registry::BlockRegistry, + registry::{BlockRegistry, BlockTableFile}, world_movement::{ CollisionCheckRequest, EntityMovementWorld, MovementRequest, no_world_collision, resolve_world_movement, }, }; -use std::{fs, io, path::Path, sync::Arc}; +use std::{io, path::Path, sync::Arc}; pub fn load<'r>(root: &Path, registry: &'r BlockRegistry) -> Result> { - let data = nbt::read_named( - &fs::read(root.join("cached-collision.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let cached = CachedCollisionRegistry::from_nbt(&data, registry)?; + let file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?; + let cached = CachedCollisionRegistry::from_table(file.table("collision")?)?; if !cached.has_canonical_identities() { return Err("scene collisions require canonical shape identities".into()); } diff --git a/crates/horizon-client/src/command/mod.rs b/crates/horizon-client/src/command/mod.rs index 52e76100a..e9aeaae51 100644 --- a/crates/horizon-client/src/command/mod.rs +++ b/crates/horizon-client/src/command/mod.rs @@ -8,6 +8,7 @@ pub mod block; pub mod codec; pub mod component; pub mod item; +pub mod network; pub mod packrat; pub mod selector; pub mod snbt; @@ -311,6 +312,9 @@ pub enum Suggests { /// ScoreboardCommand.suggestTriggers: trigger objectives some of the /// parsed `targets` have no score in, or a locked one. EnableTriggers, + /// SuggestionProviders.ASK_SERVER: the server completes the node + /// (ClientSuggestionProvider.customSuggestion); nothing locally. + AskServer, } impl Node { pub fn name(&self) -> &str { @@ -690,7 +694,7 @@ impl Suggests { Suggests::Triggers => { builder.suggest_matching(reg.trigger_objectives.iter().map(String::as_str)) } - Suggests::Nothing => {} + Suggests::Nothing | Suggests::AskServer => {} } } } @@ -954,7 +958,8 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { - self.suggestions_within(parse, cursor, reg, u8::MAX) + let (range, list, _) = self.suggestions_within(parse, cursor, reg, u8::MAX); + (range, list) } /// The suggestions the player's chat shows: the client's tree only holds /// the nodes the player may use (Commands.sendCommands prunes by canUse). @@ -964,6 +969,18 @@ impl Dispatcher { cursor: usize, reg: &Registries, ) -> (Range, Vec) { + let (range, list, _) = self.suggestions_within(parse, cursor, reg, reg.permission); + (range, list) + } + /// [`Self::client_suggestions`], and whether a node at the cursor asks + /// the server (`ask_server`): its completions come with the server's + /// reply, to be merged with these. + pub fn client_suggestions_asking( + &self, + parse: &ParseResults, + cursor: usize, + reg: &Registries, + ) -> (Range, Vec, bool) { self.suggestions_within(parse, cursor, reg, reg.permission) } fn suggestions_within( @@ -972,15 +989,17 @@ impl Dispatcher { cursor: usize, reg: &Registries, permission: u8, - ) -> (Range, Vec) { + ) -> (Range, Vec, bool) { let (parent, start, context) = parse.context.suggestion_context(cursor); let start = start.min(cursor); let truncated = &parse.input[..cursor.min(parse.input.len())]; let mut all = Vec::new(); + let mut ask = false; for &child in &self.nodes[parent].children { if self.nodes[child].permission > permission { continue; } + ask |= matches!(self.nodes[child].suggests, Some(Suggests::AskServer)); let mut builder = SuggestionsBuilder::new(truncated, start); match &self.nodes[child].kind { NodeKind::Literal(l) => { @@ -996,7 +1015,8 @@ impl Dispatcher { } all.extend(builder.out); } - merge_suggestions(truncated, all) + let (range, list) = merge_suggestions(truncated, all); + (range, list, ask) } fn smart_usage_of(&self, node: usize, optional: bool, deep: bool, level: u8) -> Option { let n = &self.nodes[node]; diff --git a/crates/horizon-client/src/command/network.rs b/crates/horizon-client/src/command/network.rs new file mode 100644 index 000000000..8fed97db0 --- /dev/null +++ b/crates/horizon-client/src/command/network.rs @@ -0,0 +1,403 @@ +//! The command tree a server sends (ClientboundCommandsPacket) as a +//! dispatcher the chat parses, colours and completes with +//! (ClientPacketListener.handleCommands). +//! +//! The packet holds each argument's parser and its network properties. A +//! node the client's own vanilla tree has at the same path takes that node's +//! argument type and suggestion provider (the parsers' suggestion lists and +//! the custom providers are the same code on both sides); any other node +//! (another server's or a mod's) gets the type its parser and properties +//! describe. +use super::{ArgType, Dispatcher, Node, NodeKind, Suggests}; +use horizon_protocol::packets::play::{ARGUMENT_TYPES, ArgumentProperties, Commands}; +use std::{ + collections::{HashSet, VecDeque}, + sync::{Mutex, OnceLock}, +}; + +/// The command id of every executable node of a server's tree: the chat +/// sends the command, the server runs it. +pub const SERVER_COMMAND: &str = "server"; + +/// The dispatcher for a server's tree. `local` is the client's own tree +/// (vanilla's), whose matching nodes lend their types and providers. +pub fn from_packet(packet: &Commands, local: &Dispatcher) -> Dispatcher { + let count = packet.nodes.len(); + let root = usize::try_from(packet.root) + .ok() + .filter(|&r| r < count) + .unwrap_or(0); + // The packet's root becomes node 0, the others follow in packet order. + let index = |i: usize| -> usize { + if i == root { + 0 + } else if i < root { + i + 1 + } else { + i + } + }; + let valid = |c: &i32| usize::try_from(*c).ok().filter(|&c| c < count); + // The local node at the same path, found breadth first from the roots + // along children (redirects are not paths of their own). + let mut matched: Vec> = vec![None; count]; + matched[root] = Some(0); + let mut queue = VecDeque::from([root]); + let mut seen = HashSet::from([root]); + while let Some(n) = queue.pop_front() { + for c in packet.nodes[n].children.iter().filter_map(valid) { + if !seen.insert(c) { + continue; + } + let node = &packet.nodes[c]; + matched[c] = matched[n].and_then(|l| { + local.nodes[l].children.iter().copied().find(|&lc| { + let ln = &local.nodes[lc]; + ln.name() == node.name + && matches!( + (&ln.kind, node.kind), + (NodeKind::Literal(_), 1) | (NodeKind::Argument { .. }, 2) + ) + }) + }); + queue.push_back(c); + } + } + let mut nodes = vec![None; count]; + for (i, node) in packet.nodes.iter().enumerate() { + let local_node = matched[i].map(|l| &local.nodes[l]); + let kind = match node.kind { + 1 => NodeKind::Literal(node.name.clone()), + 2 => { + let ty = match local_node.map(|l| &l.kind) { + Some(NodeKind::Argument { ty, .. }) => ty.clone(), + _ => node + .parser + .as_ref() + .map_or(ArgType::Word, |(id, props)| argument_type(*id, props)), + }; + NodeKind::Argument { + name: node.name.clone(), + ty, + } + } + _ => NodeKind::Root, + }; + // The server's providers, as the client knows them + // (ArgumentNodeStub.build): its own custom ones arrive as `ask_server`. + let suggests = node.suggestions.as_deref().and_then(provider); + nodes[index(i)] = Some(Node { + kind: if i == root { NodeKind::Root } else { kind }, + children: node.children.iter().filter_map(valid).map(index).collect(), + command: node.executable.then_some(SERVER_COMMAND), + redirect: node.redirect.as_ref().and_then(valid).map(index), + // The server sent only what the player may use. + permission: 0, + suggests, + }); + } + let mut d = Dispatcher::new(); + if count > 0 { + d.nodes = nodes.into_iter().flatten().collect(); + } + d +} + +/// SuggestionProviders by id (`SuggestionProviders.getProvider`). +fn provider(id: &str) -> Option { + match id { + "minecraft:ask_server" => Some(Suggests::AskServer), + "minecraft:summonable_entities" => Some(Suggests::SummonableEntities), + _ => None, + } +} + +/// A registry name kept for the life of the game (argument types hold +/// `&'static str`): each distinct name is stored once. +fn intern(name: &str) -> &'static str { + static NAMES: OnceLock>> = OnceLock::new(); + let mut names = NAMES + .get_or_init(Default::default) + .lock() + .unwrap_or_else(|e| e.into_inner()); + if let Some(&n) = names.get(name) { + return n; + } + let n: &'static str = Box::leak(name.to_owned().into_boxed_str()); + names.insert(n); + n +} + +/// The argument type a parser and its properties describe +/// (ArgumentTypeInfo.Template.instantiate). +pub fn argument_type(id: i32, props: &[u8]) -> ArgType { + let Some(name) = usize::try_from(id).ok().and_then(|i| ARGUMENT_TYPES.get(i)) else { + return ArgType::Word; + }; + let p = ArgumentProperties::decode(id, props).unwrap_or(ArgumentProperties::None); + let registry = || match &p { + ArgumentProperties::Registry(r) => intern(r), + _ => "", + }; + match *name { + "brigadier:bool" => ArgType::Bool, + "brigadier:integer" => match p { + ArgumentProperties::Integer { min, max } => ArgType::Integer { + min: min.unwrap_or(i32::MIN), + max: max.unwrap_or(i32::MAX), + }, + _ => ArgType::Integer { + min: i32::MIN, + max: i32::MAX, + }, + }, + // No long type of its own: a double over the same bounds reads + // the same digits. + "brigadier:long" => match p { + ArgumentProperties::Long { min, max } => ArgType::Double { + min: min.map_or(f64::MIN, |v| v as f64), + max: max.map_or(f64::MAX, |v| v as f64), + }, + _ => ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + }, + "brigadier:float" => match p { + ArgumentProperties::Float { min, max } => ArgType::Float { + min: min.unwrap_or(f32::MIN), + max: max.unwrap_or(f32::MAX), + }, + _ => ArgType::Float { + min: f32::MIN, + max: f32::MAX, + }, + }, + "brigadier:double" => match p { + ArgumentProperties::Double { min, max } => ArgType::Double { + min: min.unwrap_or(f64::MIN), + max: max.unwrap_or(f64::MAX), + }, + _ => ArgType::Double { + min: f64::MIN, + max: f64::MAX, + }, + }, + "brigadier:string" => match p { + ArgumentProperties::String(1) => ArgType::Str, + ArgumentProperties::String(2) => ArgType::Greedy, + _ => ArgType::Word, + }, + "minecraft:entity" => match p { + ArgumentProperties::Entity { + single, + players_only, + } => ArgType::Entity { + single, + players: players_only, + }, + _ => ArgType::Entity { + single: false, + players: false, + }, + }, + "minecraft:game_profile" => ArgType::GameProfile, + "minecraft:block_pos" => ArgType::BlockPos, + "minecraft:column_pos" => ArgType::ColumnPos, + "minecraft:vec3" => ArgType::Vec3 { center: true }, + "minecraft:vec2" => ArgType::Vec2, + "minecraft:block_state" => ArgType::BlockState, + "minecraft:block_predicate" => ArgType::BlockPredicate, + "minecraft:item_stack" => ArgType::Item, + "minecraft:item_predicate" => ArgType::ItemPredicate, + "minecraft:team_color" => ArgType::TeamColor, + "minecraft:hex_color" => ArgType::HexColor, + "minecraft:component" => ArgType::Component, + "minecraft:style" => ArgType::Style, + "minecraft:message" => ArgType::Message, + "minecraft:nbt_compound_tag" => ArgType::Nbt, + "minecraft:nbt_tag" => ArgType::NbtTag, + "minecraft:nbt_path" => ArgType::NbtPath, + "minecraft:objective" => ArgType::Objective, + "minecraft:objective_criteria" => ArgType::Criteria, + "minecraft:operation" => ArgType::Operation, + "minecraft:particle" => ArgType::Particle, + "minecraft:angle" => ArgType::Angle, + "minecraft:rotation" => ArgType::Rotation, + "minecraft:scoreboard_slot" => ArgType::ScoreboardSlot, + "minecraft:score_holder" => ArgType::ScoreHolder { + multiple: matches!(p, ArgumentProperties::ScoreHolder { multiple: true }), + }, + "minecraft:swizzle" => ArgType::Swizzle, + "minecraft:team" => ArgType::Team, + "minecraft:item_slot" => ArgType::Slot, + "minecraft:item_slots" => ArgType::Slots, + "minecraft:resource_location" => ArgType::Id("none"), + "minecraft:function" => ArgType::Function, + "minecraft:entity_anchor" => ArgType::Anchor, + "minecraft:int_range" => ArgType::IntRange, + "minecraft:float_range" => ArgType::FloatRange, + "minecraft:dimension" => ArgType::Dimension, + "minecraft:gamemode" => ArgType::GameMode, + "minecraft:time" => ArgType::Time { + min: match p { + ArgumentProperties::Time { min } => min, + _ => 0, + }, + }, + "minecraft:resource_or_tag" => ArgType::ResOrTag(registry()), + "minecraft:resource_or_tag_key" => ArgType::ResOrTagKey(registry()), + "minecraft:resource" => ArgType::Res(registry()), + "minecraft:resource_key" => ArgType::ResKey(registry()), + "minecraft:resource_selector" => ArgType::ResourceSelector(registry()), + "minecraft:template_mirror" => ArgType::Enum(&["none", "front_back", "left_right"]), + "minecraft:template_rotation" => { + ArgType::Enum(&["none", "clockwise_90", "180", "counterclockwise_90"]) + } + "minecraft:heightmap" => ArgType::Enum(&[ + "world_surface", + "motion_blocking", + "motion_blocking_no_leaves", + "ocean_floor", + ]), + "minecraft:swing_animation" => ArgType::Enum(&["none", "whack", "stab"]), + "minecraft:loot_table" => ArgType::ResourceOrId("minecraft:loot_table"), + "minecraft:loot_predicate" => ArgType::ResourceOrId("minecraft:predicate"), + "minecraft:loot_modifier" => ArgType::ResourceOrId("minecraft:item_modifier"), + "minecraft:context_float_provider" => { + ArgType::ResourceOrId("minecraft:context_float_provider") + } + "minecraft:context_int_provider" => ArgType::ResourceOrId("minecraft:context_int_provider"), + "minecraft:slot_source" => ArgType::SlotSource, + "minecraft:dialog" => ArgType::ResourceOrId("minecraft:dialog"), + "minecraft:feature" => ArgType::ResourceOrId("minecraft:worldgen/feature"), + "minecraft:uuid" => ArgType::Uuid, + _ => ArgType::Word, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_protocol::{ + buf::{Codec, Reader, Writer}, + packets::play::CommandNode, + }; + + fn literal(name: &str, children: Vec, executable: bool) -> CommandNode { + CommandNode { + kind: 1, + executable, + restricted: false, + children, + redirect: None, + name: name.into(), + parser: None, + suggestions: None, + } + } + + fn argument(name: &str, parser: &str, props: Vec, executable: bool) -> CommandNode { + let id = ARGUMENT_TYPES.iter().position(|p| *p == parser).unwrap() as i32; + CommandNode { + kind: 2, + executable, + restricted: false, + children: Vec::new(), + redirect: None, + name: name.into(), + parser: Some((id, props)), + suggestions: Some("minecraft:ask_server".into()), + } + } + + /// A tree with the root last (as vanilla's numbering need not put it + /// first), a vanilla command and one the client does not know. + fn packet() -> Commands { + let mut range = Writer::new(); + range.u8(3); + range.i32(1); + range.i32(64); + Commands { + nodes: vec![ + literal("give", vec![2], false), + literal("warp", vec![3], false), + argument("targets", "minecraft:entity", vec![2], false), + argument("count", "brigadier:integer", range.data, true), + CommandNode { + kind: 0, + executable: false, + restricted: false, + children: vec![0, 1], + redirect: None, + name: String::new(), + parser: None, + suggestions: None, + }, + ], + root: 4, + } + } + + #[test] + fn argument_nodes_round_trip() { + let p = packet(); + let mut w = Writer::new(); + Commands::write(&p, &mut w); + let back = Commands::read(&mut Reader::new(&w.data)).unwrap(); + assert_eq!(back, p); + } + + #[test] + fn server_tree_becomes_a_dispatcher() { + let local = super::super::vanilla::dispatcher(); + let d = from_packet(&packet(), local); + assert!(matches!(d.nodes[0].kind, NodeKind::Root)); + let warp = d.find("warp").expect("warp"); + let count = d.nodes[warp].children[0]; + match &d.nodes[count].kind { + NodeKind::Argument { + ty: ArgType::Integer { min, max }, + .. + } => assert_eq!((*min, *max), (1, 64)), + other => panic!("count is {other:?}"), + } + assert_eq!(d.nodes[count].command, Some(SERVER_COMMAND)); + // `give ` is vanilla's: it keeps the client's type. + let give = d.find("give").expect("give"); + let targets = d.nodes[give].children[0]; + assert!(matches!( + d.nodes[targets].kind, + NodeKind::Argument { + ty: ArgType::Entity { + single: false, + players: true + }, + .. + } + )); + } + + #[test] + fn every_argument_type_decodes() { + for (id, name) in ARGUMENT_TYPES.iter().enumerate() { + let mut w = Writer::new(); + match *name { + "brigadier:integer" | "brigadier:long" | "brigadier:float" | "brigadier:double" => { + w.u8(0) + } + "brigadier:string" => w.varint(2), + "minecraft:entity" | "minecraft:score_holder" => w.u8(1), + "minecraft:time" => w.i32(0), + n if n.starts_with("minecraft:resource") && n != "minecraft:resource_location" => { + w.string("minecraft:item") + } + _ => {} + } + let mut r = Reader::new(&w.data); + ArgumentProperties::read(&mut r, id as i32).unwrap(); + assert_eq!(r.remaining(), 0, "{name}"); + let _ = argument_type(id as i32, &w.data); + } + } +} diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index 9cdac1463..6a135799c 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -45,6 +45,9 @@ pub struct Furnace { pub cooking_total: i32, pub speed: f32, } +/// A hopper's slots: the only plain container with five. +pub const HOPPER_SLOTS: usize = 5; + #[derive(Clone, Debug)] pub enum BlockEntity { Chest(Vec>), @@ -242,7 +245,7 @@ impl BlockEntity { let size = match name { "minecraft:chest" | "minecraft:trapped_chest" | "minecraft:barrel" => 27, n if n.ends_with("copper_chest") => 27, - "minecraft:hopper" => 5, + "minecraft:hopper" => HOPPER_SLOTS, "minecraft:dispenser" | "minecraft:dropper" => 9, n if n.ends_with("shulker_box") => 27, _ => return None, @@ -270,7 +273,7 @@ impl BlockEntity { pub fn id(&self) -> &'static str { match self { Self::Chest(items) => match items.len() { - 5 => "minecraft:hopper", + HOPPER_SLOTS => "minecraft:hopper", 9 => "minecraft:dispenser", _ => "minecraft:chest", }, diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index 457ddf497..0b8f2856b 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -1209,7 +1209,15 @@ impl Recipes { for (prefix, path) in files { let stem = path.file_stem().and_then(|s| s.to_str()).unwrap_or(""); let name = format!("{prefix}{stem}"); - let v: Value = serde_json::from_slice(&fs::read(&path)?)?; + // Vanilla's RecipeManager logs a file that does not parse and + // goes on ("Couldn't parse data file"). + let v: Value = match serde_json::from_slice(&fs::read(&path)?) { + Ok(v) => v, + Err(e) => { + log::warn!("Horizon: recipe {name} not loaded: {e}"); + continue; + } + }; let text = |k: &str| v[k].as_str().unwrap_or("").to_owned(); meta.insert(name.clone(), (text("category"), text("group"))); let ing = |k: &str| Ingredient::parse(&v[k], items); diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index 2e600333a..a258ccf3a 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -386,6 +386,12 @@ impl PlayerEffects { 4.0, "add_value", )), + "absorption" => Some(( + "minecraft:max_absorption", + "minecraft:effect.absorption", + 4.0, + "add_value", + )), "luck" => Some(("minecraft:luck", "minecraft:effect.luck", 1.0, "add_value")), "unluck" => Some(( "minecraft:luck", @@ -538,4 +544,29 @@ mod tests { assert!((fx.mining_speed_factor() - 1.4).abs() < 1e-6); assert_eq!(fx.modifiers().len(), 1); } + + #[test] + fn absorption_modifier_scales_with_amplifier() { + let mut fx = PlayerEffects::default(); + fx.add(EffectInstance::new("absorption", 2400, 0)); + assert_eq!( + fx.modifiers(), + vec![( + "minecraft:max_absorption", + "minecraft:effect.absorption", + 4.0, + "add_value", + )] + ); + fx.add(EffectInstance::new("absorption", 2400, 3)); + assert_eq!( + fx.modifiers(), + vec![( + "minecraft:max_absorption", + "minecraft:effect.absorption", + 16.0, + "add_value", + )] + ); + } } diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 5e6a3336a..5c905ac54 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -16,6 +16,7 @@ pub struct ItemEntity { pub fire_ticks: i32, pub id: u32, pub stack: ItemStack, + pub thrower: Option<[i32; 4]>, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -178,6 +179,8 @@ impl ItemEntity { /// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks. #[derive(Clone, Debug)] pub struct ExperienceOrb { + /// The entity id servers track it by. + pub id: u32, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -532,15 +535,16 @@ impl ArmorStand { Vec3::new(p.x + w, p.y + h, p.z + w), ) } - /// LivingEntity.travel with gravity 0.08 and 0.98 drag, falling until it - /// lands (armor stands have no other movement). + /// LivingEntity.travelInAir (armor stands have no other movement): move + /// by the velocity (a landing stops the fall, + /// `Block.updateEntityMovementAfterFallOn`), then gravity 0.08 and the + /// 0.98 drag, so a stand at rest on the ground keeps -0.0784 as vanilla's. pub fn tick(&mut self, scene: &mut crate::collisions::SceneCollisions) { if self.marker { return; } - let mut v = self.velocity; - v.y -= 0.08; - let wanted = v; + let wanted = self.velocity; + let mut y = wanted.y; if let Ok(moved) = scene.resolve(self.bounds(), wanted, 0.0, self.on_ground) { self.position = Vec3::new( self.position.x + moved.x, @@ -548,9 +552,11 @@ impl ArmorStand { self.position.z + moved.z, ); self.on_ground = wanted.y < 0.0 && moved.y > wanted.y; - v = Vec3::new(0.0, if moved.y != wanted.y { 0.0 } else { v.y * 0.98 }, 0.0); + if moved.y != wanted.y { + y = 0.0; + } } - self.velocity = v; + self.velocity = Vec3::new(0.0, (y - 0.08) * f64::from(0.98f32), 0.0); } } @@ -610,6 +616,7 @@ mod fire_environment_tests { .unwrap(); let make = |id: &str| ItemEntity { id: 1, + thrower: None, stack: ItemStack { item: std::sync::Arc::from(id), count: 1, diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index adeb1da25..d627dc363 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -863,7 +863,7 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - Some(m) } -/// `ItemEntity`: Health, Age, PickupDelay, Item. +/// `ItemEntity`: Health, Age, PickupDelay, Item, Thrower. pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> Tag { let base = Base { id: "minecraft:item", @@ -887,6 +887,11 @@ pub fn item_entity_to_nbt(e: &ItemEntity, uuid: [i32; 4], raw: Option<&Tag>) -> ] { put(&mut tag, key, value); } + if let Some(thrower) = e.thrower { + put(&mut tag, "Thrower", Tag::IntArray(thrower.to_vec())); + } else if let Tag::Compound(map) = &mut tag { + map.remove(&"Thrower".into()); + } tag } pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option { @@ -897,6 +902,7 @@ pub fn item_entity_from_nbt(tag: &Tag, id: u32, bob_offset: f32) -> Option Vec { }; let count = number(tag.get("Count")).unwrap_or(1).clamp(1, 64) as usize; let orb = ExperienceOrb { + id: 0, position, previous: position, velocity: motion(tag), @@ -1529,6 +1536,7 @@ mod tests { let e = ItemEntity { health: 2, fire_ticks: 73, + thrower: Some([5, 6, 7, 8]), id: 7, stack: ItemStack { item: Arc::from("minecraft:diamond_pickaxe"), @@ -1555,6 +1563,11 @@ mod tests { (120, 10, true) ); assert_eq!(back.position.x, 100.5); + assert_eq!(back.thrower, e.thrower); + let mut cleared = back; + cleared.thrower = None; + let cleared = item_entity_to_nbt(&cleared, [1, 2, 3, 4], Some(&tag)); + assert!(cleared.get("Thrower").is_none()); } #[test] fn unknown_fields_survive() { @@ -1575,6 +1588,7 @@ mod tests { #[test] fn orbs_expand_their_count() { let o = ExperienceOrb { + id: 0, position: Vec3::new(1.0, 2.0, 3.0), previous: Vec3::ZERO, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/flatgen.rs b/crates/horizon-client/src/flatgen.rs index d7764c30e..1cff68b11 100644 --- a/crates/horizon-client/src/flatgen.rs +++ b/crates/horizon-client/src/flatgen.rs @@ -4,7 +4,7 @@ use horizon_world::{nbt::Tag, registry::BlockRegistry}; /// The layers of a flat generator, bottom up from the world's minimum Y. pub struct FlatTerrain { - layers: Vec, + layers: Vec, biome: u16, } impl FlatTerrain { @@ -30,7 +30,7 @@ impl FlatTerrain { for layer in list { let block = crate::save::text(layer.get("block"))?; let height = crate::save::number(layer.get("height")).unwrap_or(0).max(0); - let state = registry.default_state(&block)?.0 as u16; + let state = registry.default_state(&block)?.0; layers.extend(std::iter::repeat_n(state, height as usize)); } } @@ -44,6 +44,113 @@ impl FlatTerrain { crate::chunk::MIN_Y + self.layers.len().min(crate::chunk::HEIGHT as usize) as i32 } } +/// DimensionType.Y_SIZE: the most layers FlatLevelGeneratorSettings takes. +const Y_SIZE: i64 = 4064; + +/// FlatLevelGeneratorSettings.CODEC reading a dedicated server's +/// `generator-settings` (DedicatedServerProperties.WorldDimensionData for +/// the `minecraft:flat` preset): the settings as `world_gen_settings` stores +/// them, and the errors vanilla logs, in order (the constructor's, then +/// `resultOrPartial`'s). No settings means the preset's own layers; a layer +/// that doesn't parse is left out, as the codec's partial result leaves it. +/// `is_block` says whether a block id is registered, `is_biome` a biome id. +pub fn settings_from_json( + json: &crate::server::json::Json, + is_block: impl Fn(&str) -> bool, + is_biome: impl Fn(&str) -> bool, +) -> (Option, Vec) { + use crate::server::json::Json; + let id = |s: &str| { + if s.contains(':') { + s.to_owned() + } else { + format!("minecraft:{s}") + } + }; + let Some(Json::Array(list)) = json.get("layers") else { + let error = match json.get("layers") { + None => format!("No key layers in MapLike[{}]", json.compact()), + Some(v) => format!("Not a list: {}", v.compact()), + }; + return (None, vec![error]); + }; + let mut errors = Vec::new(); + let mut layers = Vec::new(); + let mut total = 0; + for layer in list { + let height = layer.get("height").and_then(Json::as_string); + let height = height.as_deref().and_then(|h| h.parse::().ok()); + let block = layer.get("block").and_then(Json::as_string).map(|b| id(&b)); + match (height, block) { + (Some(h), _) if !(0..=Y_SIZE).contains(&h) => { + errors.push(format!("Value {h} outside of range [0:{Y_SIZE}]")); + } + (Some(h), Some(b)) if is_block(&b) => { + total += h; + layers.push(Tag::compound([ + ("height", Tag::Int(h as i32)), + ("block", Tag::String(b.as_str().into())), + ])); + } + (Some(_), Some(b)) => errors.push(format!( + "Unknown registry key in ResourceKey[minecraft:root / minecraft:block]: {b}" + )), + (None, _) => errors.push(format!("No key height in MapLike[{}]", layer.compact())), + (_, None) => errors.push(format!("No key block in MapLike[{}]", layer.compact())), + } + } + // The constructor: Biome.CODEC is lenient, and a biome that is missing + // or unknown is Plains. + let biome = json + .get("biome") + .and_then(Json::as_string) + .map(|b| id(&b)) + .filter(|b| is_biome(b)); + let mut logged = Vec::new(); + if biome.is_none() { + logged.push("Unknown biome, defaulting to plains".to_owned()); + } + let biome = biome.unwrap_or_else(|| "minecraft:plains".to_owned()); + // validateHeight. + if total > Y_SIZE { + errors.push(format!("Sum of layer heights is > {Y_SIZE}")); + logged.push(errors.join("; ")); + return (None, logged); + } + let flag = |key: &str| match json.get(key) { + Some(Json::Bool(b)) => *b, + Some(Json::Number(n)) => n.parse::().is_ok_and(|v| v != 0.0), + _ => false, + }; + let mut settings = Vec::new(); + // RegistryCodecs.holderSet, lenient too: a tag or a list of ids. + match json.get("structure_overrides") { + Some(Json::String(s)) => { + settings.push(("structure_overrides", Tag::String(s.as_str().into()))) + } + Some(Json::Array(ids)) if ids.iter().all(|i| matches!(i, Json::String(_))) => settings + .push(( + "structure_overrides", + Tag::List( + ids.iter() + .filter_map(Json::as_string) + .map(|i| Tag::String(id(&i).as_str().into())) + .collect(), + ), + )), + _ => {} + } + settings.extend([ + ("layers", Tag::List(layers)), + ("lakes", Tag::Byte(i8::from(flag("lakes")))), + ("features", Tag::Byte(i8::from(flag("features")))), + ("biome", Tag::String(biome.as_str().into())), + ]); + if !errors.is_empty() { + logged.push(errors.join("; ")); + } + (Some(Tag::compound(settings)), logged) +} impl ChunkGenerator for FlatTerrain { type Worker = (); fn worker(&self) {} @@ -75,3 +182,71 @@ impl ChunkGenerator for FlatTerrain { *proto.downcast::().expect("flat terrain proto") } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::save::{number, text}; + use crate::server::json::{self, Json}; + + fn read(text: &str) -> (Option, Vec) { + let json: Json = json::parse(text, false).unwrap(); + settings_from_json( + &json, + |b| ["minecraft:stone", "minecraft:bedrock"].contains(&b), + |b| ["minecraft:plains", "minecraft:desert"].contains(&b), + ) + } + + #[test] + fn generator_settings_read_as_flat_level_generator_settings() { + // server.properties' default: the preset's own layers, and the codec's error. + assert_eq!( + read("{}"), + (None, vec!["No key layers in MapLike[{}]".into()]) + ); + let (settings, errors) = read( + r#"{"layers":[{"block":"bedrock","height":1},{"block":"minecraft:stone","height":3}],"biome":"desert","features":true}"#, + ); + assert!(errors.is_empty()); + let settings = settings.unwrap(); + let Some(Tag::List(layers)) = settings.get("layers") else { + panic!("{settings:?}") + }; + assert_eq!(layers.len(), 2); + assert_eq!( + text(layers[0].get("block")).as_deref(), + Some("minecraft:bedrock") + ); + assert_eq!(number(layers[1].get("height")), Some(3)); + assert_eq!( + text(settings.get("biome")).as_deref(), + Some("minecraft:desert") + ); + assert_eq!(number(settings.get("features")), Some(1)); + assert_eq!(number(settings.get("lakes")), Some(0)); + // A layer that doesn't parse is left out; an unknown biome is Plains, and logged first. + let (settings, errors) = read( + r#"{"layers":[{"block":"nope","height":2},{"block":"stone","height":2}],"biome":"x"}"#, + ); + assert_eq!(errors.len(), 2); + assert_eq!(errors[0], "Unknown biome, defaulting to plains"); + assert!(errors[1].contains("minecraft:nope")); + let settings = settings.unwrap(); + let Some(Tag::List(layers)) = settings.get("layers") else { + panic!("{settings:?}") + }; + assert_eq!(layers.len(), 1); + assert_eq!( + text(settings.get("biome")).as_deref(), + Some("minecraft:plains") + ); + // validateHeight. + assert_eq!( + read( + r#"{"layers":[{"block":"stone","height":4000},{"block":"stone","height":100}],"biome":"plains"}"# + ), + (None, vec!["Sum of layer heights is > 4064".into()]) + ); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 0f898f8bf..54d032d20 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -10,6 +10,7 @@ mod banners; mod beacon; mod beehives; mod block_entity_anims; +mod block_entity_ticks; mod block_items; mod blockctl; mod boats; @@ -63,13 +64,17 @@ mod item_particles; mod jukebox; mod lan; mod lan_actions; +mod lan_chat; mod lan_crafting; +mod lan_entities; mod lan_mobs; mod lan_pvp; mod lan_screen; mod lan_trading; +mod lan_waypoints; mod leads; mod level_particles; +mod levels; mod lightning; mod llamas; mod loom; @@ -105,6 +110,8 @@ mod powder_snow; mod raids; mod recipe_book; mod remote; +mod remote_objects; +mod remote_projectiles; mod render_control; mod render_tick; mod respawn_anchor; @@ -195,7 +202,12 @@ use horizon_world::{ use std::{ collections::{HashMap, HashSet}, path::PathBuf, - sync::Arc, + sync::{ + Arc, + atomic::{AtomicU32, Ordering}, + mpsc::{Receiver, TryRecvError}, + }, + thread::JoinHandle, time::{Duration, Instant}, }; use winit::{ @@ -640,6 +652,8 @@ impl LevelAccess for GameLevel<'_> { /// FallingBlockEntity carrying a block state. #[derive(Clone, Debug)] struct FallingBlock { + /// The entity id a server tracks it by (0 until it is tracked). + id: u32, state: BlockStateId, /// `DATA_START_POS`: spawn position used to select weighted block models. start_pos: BlockPos, @@ -967,14 +981,23 @@ struct Game<'a> { /// `ClientAvatarState`: walked distance and view bob. avatar: horizon_client::camera::AvatarBob, flash: u32, - /// Sleeping in a bed: (bed head position, ticks asleep). - sleeping: Option<([i32; 3], u32)>, + /// The head of the bed while sleeping; the visual timer also survives waking. + sleeping: Option<[i32; 3]>, + sleep_timer: u32, dim: Dim, world_root: PathBuf, /// A player carried through a portal, re-placed once the destination loads. travelling: Option<(PlayerMotion, Vec3)>, - /// A server's lone player on its way to another level. - server_trip: Option, + /// A server's players on their way to another level, each waiting for + /// the destination to load around them. + server_trips: Vec, + /// Players a command sends to another level, once it has run. + level_teleports: Vec, + /// A server's levels other than the one in place (game/levels.rs). + levels: levels::Levels, + /// Which pass of a server tick runs (`tick_server`): the first one reads + /// the network, the last one ends the players' tick. + level_pass: levels::Pass, /// Nether portals: the player's, items' and mobs' (game/nether_portal.rs). portals: nether_portal::Portals, /// The pending travel goes through an End portal (EndPortalBlock destinations). @@ -1125,7 +1148,7 @@ struct Game<'a> { lan_events: Vec<(i32, [i32; 3], i32, Option)>, /// Block events (position, b0, b1, state) and entity events (id, event, /// position) for the guests. - lan_block_events: Vec<([i32; 3], i32, i32, u16)>, + lan_block_events: Vec<([i32; 3], i32, i32, u32)>, lan_entity_events: Vec<(i32, i8, [f64; 3])>, /// `ContainerOpenersCounter`: how many players (the host and the guests) /// have each chest open. @@ -1137,6 +1160,16 @@ struct Game<'a> { lan_acting_uuid: Option, /// Command feedback to forward to a guest. chat_capture: Option>, + /// Packets for the guest acting now, sent once its action returns. + guest_packets: Vec, + /// `broadcastToAdmins` lines a guest's command queued, sent once it + /// returns: the line, whether operators get it and whether the console + /// logs it. + admin_feedback: Vec<(horizon_client::text::Text, bool, bool)>, + /// The server console is running a command: whether its feedback goes to + /// the operators (`DedicatedServer.shouldInformAdmins`, + /// `broadcast-console-to-ops`). + console_broadcast: Option, /// State of `/spectate`, `/posteffect`, `/debug`, `/waypoint` and friends. cmds: commands::extra::CommandExtras, ui: chat::UiState, @@ -1156,7 +1189,7 @@ struct Game<'a> { tab_list: horizon_client::tab_list::TabList, subtitles: subtitle_hud::SubtitleState, adv: advancements::AdvState, - restore_player_environment: bool, + restore_player_state: bool, stats_ui: stats_screen::StatsUi, adv_ui: advancements_screen::AdvUi, camera_type: perspective::CameraType, @@ -1164,7 +1197,7 @@ struct Game<'a> { /// The local player as a model (third person, the inventory). player_model: Option, } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] enum Dim { Overworld, Nether, @@ -1527,6 +1560,7 @@ impl Game<'_> { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: self.next_entity, stack, position: p, @@ -1609,6 +1643,10 @@ impl Game<'_> { yaw.cos() * pitch.cos() * 0.3 + spread.sin() * strength, ]; self.spawn_item(thrown, [eye[0], eye[1] - 0.3, eye[2]], v, 40); + if self.lan_acting.is_none() { + let uuid = self.level.ensure_player_uuid(); + self.dropped.last_mut().unwrap().thrower = Some(uuid); + } } fn tick_items(&mut self) { let mut items = std::mem::take(&mut self.dropped); @@ -2029,6 +2067,7 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ); self.falling.push(FallingBlock { + id: 0, state, start_pos: pos, position: p, @@ -2178,13 +2217,13 @@ impl Game<'_> { self.audio .play("minecraft:block.ender_chest.open", Some(at), 0.5, pitch); } else if &*name == "minecraft:beacon" && self.open_station(pos, &name) { - self.world.block_entities.entry(key).or_insert_with(|| { + self.world.block_entities.get_or_insert_with(key, || { BlockEntity::for_block(&name).unwrap_or(BlockEntity::Chest(Vec::new())) }); } else if storage::is_shulker_box(&name) && !self.shulker_can_open(pos) { // ShulkerBoxBlock.canOpen: the lid has no room; nothing opens. } else if let Some(entity) = BlockEntity::for_block(&name) { - self.world.block_entities.entry(key).or_insert(entity); + self.world.block_entities.get_or_insert_with(key, || entity); let centre = [ f64::from(key.0) + 0.5, f64::from(key.1) + 0.5, @@ -2741,7 +2780,7 @@ impl Game<'_> { || !self .player .as_ref() - .is_some_and(|p| p.health.food.food < 20 || self.creative) + .is_some_and(|p| info.can_always_eat || p.health.food.food < 20 || self.creative) { return false; } @@ -2750,6 +2789,56 @@ impl Game<'_> { } true } + fn apply_consume_effect( + &mut self, + effect: &horizon_client::items::ConsumeEffect, + eye: [f64; 3], + ) { + use horizon_client::items::ConsumeEffect; + match effect { + ConsumeEffect::ApplyEffects { + effects, + probability, + } => { + if *probability >= 1.0 || self.world.random.next_float() <= *probability { + for eff in effects { + if let Some(def) = horizon_client::brewing::effect(&eff.id) { + if def.instant { + if let Some(a) = + horizon_client::effects::instant(def.id, eff.amplifier, 1.0) + { + self.apply_effect_action(a); + } + } else { + self.add_player_effect( + horizon_client::effects::EffectInstance::new( + def.id, + eff.duration, + eff.amplifier, + ), + ); + } + } + } + } + } + ConsumeEffect::ClearAllEffects => { + self.potions.effects.clear(); + self.apply_effect_status(); + } + ConsumeEffect::RemoveEffects(to_remove) => { + for target in to_remove { + let id = target.trim_start_matches("minecraft:"); + self.potions.effects.list.retain(|e| e.id != id); + } + self.apply_effect_status(); + } + ConsumeEffect::TeleportRandomly => {} + ConsumeEffect::PlaySound(sound) => { + self.audio.play(sound, Some(eye), 1.0, 1.0); + } + } + } fn consume_held(&mut self) { if self.creative { return; @@ -2852,19 +2941,22 @@ impl Game<'_> { self.eat_particles(&stack, 16); // Consumable.onConsume. self.post_entity_event("minecraft:eat", horizon_client::mobs::Who::Player); - if let Some((nutrition, saturation)) = info.food - && let Some(p) = self.player.as_mut() - { - // FoodData.eat(nutrition, saturation) - let food = &mut p.health.food; - food.food = (food.food + nutrition as i32).clamp(0, 20); - food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32); + if let Some((nutrition, saturation)) = info.food { + if let Some(p) = self.player.as_mut() { + // FoodData.eat(nutrition, saturation) + let food = &mut p.health.food; + food.food = (food.food + nutrition as i32).clamp(0, 20); + food.saturation = (food.saturation + saturation).clamp(0.0, food.food as f32); + } self.audio.play( "minecraft:entity.player.burp", Some(eye), 0.5, self.world.random.next_float() * 0.1 + 0.9, ); + for effect in &info.consume_effects { + self.apply_consume_effect(effect, eye); + } self.trigger_item("minecraft:consume_item", &stack); self.consume_held(); } @@ -3075,14 +3167,16 @@ impl Game<'_> { }; let mut player = PlayerMotion::new(self.motion, feet)?; player.yaw = self.yaw; - player.load_environment_once( - &mut self.restore_player_environment, - self.level.player_extra.as_ref(), - ); + player.load_saved_state_once(&mut self.restore_player_state, &self.level)?; let spectator = self.mode == horizon_client::command::args::GameMode::Spectator; player.may_fly = self.creative || spectator; player.invulnerable = self.creative || spectator; player.spectator = spectator; + if spectator { + player.flying = true; + } else if !player.may_fly { + player.flying = false; + } player.respiration = self.armor[0] .as_ref() .map_or(0, |s| s.enchantment_level("minecraft:respiration") as i32); @@ -3094,10 +3188,12 @@ impl Game<'_> { .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); - if self.level.health > 0.0 && self.ticks < 2 { - player.set_health(self.level.health, false)?; - player.health.food.food = self.level.food; - player.health.food.saturation = self.level.saturation; + // A saved death already dropped inventory/XP and counted the death. + if player.health.dead_or_dying() { + self.screen = Screen::Dead; + self.ui.died_at = Some(Instant::now()); + self.ui.death_text = None; + self.capture(false); } self.previous_position = feet; self.player = Some(player); @@ -3182,7 +3278,7 @@ impl Game<'_> { if !self.streaming.is_lit(cx, cz) { return Ok(()); } - let playing = self.screen == Screen::Playing; + let playing = self.screen == Screen::Playing && self.sleeping.is_none(); let held = |k| playing && self.keys.contains(&k); let keys = Keys { forward: held(KeyCode::KeyW), @@ -3276,7 +3372,12 @@ impl Game<'_> { let feet = [player.position.x, player.position.y, player.position.z]; let player_velocity = [player.velocity.x, player.velocity.y, player.velocity.z]; self.previous_eye = self.eye; - self.eye += (camera_eye.unwrap_or(player.dimensions.eye_height) - self.eye) * 0.5; + let eye_height = if self.sleeping.is_some() { + 0.2 + } else { + player.dimensions.eye_height + }; + self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; let crouching = player.pose == horizon_client::pose::Pose::Crouching; self.tick_avatar(before, riding); self.record_combat(&events); @@ -3539,7 +3640,11 @@ impl Game<'_> { }); horizon_client::spans::time("tick_particles", || self.tick_particles()); } - if self.right && self.use_delay == 0 && self.screen == Screen::Playing { + if self.right + && self.use_delay == 0 + && self.screen == Screen::Playing + && self.sleeping.is_none() + { self.use_with_hand()?; self.use_delay = 4; } @@ -3666,6 +3771,11 @@ impl Game<'_> { ) || self.book.is_some()) } fn capture(&mut self, capture: bool) { + // A guest's action (`as_guest`) opens and closes screens on the + // guest's own client: the window's pointer stays the host's (#687). + if self.lan_acting.is_some() { + return; + } // MouseHandler.grabMouse never captures an inactive window. if capture && !self.focused { return; @@ -3691,10 +3801,7 @@ impl Game<'_> { /// LevelLoadingScreen.onClose -> Gui.setScreen(null) -> grabMouse. fn capture_loaded_world(&mut self) { // Loading may finish after focus was lost or another screen opened. - if self.title.is_none() - && self.screen == Screen::Playing - && !self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) - { + if self.title.is_none() && self.screen == Screen::Playing { self.capture(true); } } @@ -3922,15 +4029,7 @@ impl Game<'_> { self.draw_boss_bars(&mut batch); self.draw_extras(&mut batch); } - // Hud.extractSleepOverlay, under the sidebar, titles and chat. - if let Some((_, ticks)) = self.sleeping { - let draws = hud_overlays::sleep_overlay(wi, hi, ticks as i32); - hud_layout::paint(&mut batch, &self.atlas, &draws); - } if show_hud { - self.draw_titles(&mut batch); - self.draw_scoreboard(&mut batch); - self.draw_subtitles(&mut batch); // The mount's hearts (and the jump bar that replaces the experience bar). let (vehicle_hearts, jump_bar) = if spectator { (0, false) @@ -4002,6 +4101,14 @@ impl Game<'_> { self.draw_selected_name(&mut batch, !self.creative); } } + // Hud.extractSleepOverlay: over all health/food bars, under titles and chat. + let draws = hud_overlays::sleep_overlay(wi, hi, self.sleep_timer as i32); + hud_layout::paint(&mut batch, &self.atlas, &draws); + if show_hud { + self.draw_titles(&mut batch); + self.draw_scoreboard(&mut batch); + self.draw_subtitles(&mut batch); + } let atlas = &self.atlas; if show_hud && let Some((text, at)) = &self.message @@ -4513,6 +4620,10 @@ impl Game<'_> { /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { use horizon_client::menu::Input; + if self.remote.is_some() && self.screen == Screen::Inventory { + // On a server the clicks are the server's: predicted and sent. + return self.remote_menu_ops(ops); + } if let [(Some(slot), button, input)] = ops { self.crafter_slot_clicked(*slot, *button, *input); } @@ -4687,7 +4798,7 @@ impl Game<'_> { plain: false, }; (kind, map) - } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + } else if self.station.is_none() && !self.mount_active() { let table = self.craft_size == 3; let map = Map { container: 0, @@ -4800,7 +4911,12 @@ impl Game<'_> { Some(false) => return true, Some(true) => {} } - self.register_exploration_maps(made); + // On a server the clicks only predict: the server drops, crafts and + // makes maps itself. + let predicting = self.remote.is_some(); + if !predicting { + self.register_exploration_maps(made); + } if let Some(s) = menu.merchant.take() { self.merchant_sync_out(s); } @@ -4818,10 +4934,12 @@ impl Game<'_> { if !offhand_mapped { self.offhand = menu.player_item(40).cloned(); } - for stack in dropped { - self.player_drop(stack); + if !predicting { + for stack in dropped { + self.player_drop(stack); + } + self.award_crafted(&crafted); } - self.award_crafted(&crafted); if kind == Kind::Loom { if let Some(s) = self.station.as_mut() { s.loom.selected = usize::try_from(menu.data[0]).ok(); @@ -4953,9 +5071,13 @@ impl Game<'_> { return; } if let Some(moved) = self.last_quick_moved.clone() { - self.menu_session(|menu, env, to_menu| { - Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) - }); + if self.remote.is_some() { + self.remote_quick_move_all(slot, &moved); + } else { + self.menu_session(|menu, env, to_menu| { + Some(menu.quick_move_all(env, to_menu(slot)?, &moved).is_ok()) + }); + } } self.last_inv_click = None; self.inv_clicks.skip_release(); @@ -5584,6 +5706,9 @@ impl Game<'_> { ) }; let visible = r.block_entities().filter(|(p, state)| { + if !self.res.block_entity_render.renders(*state) { + return false; + } off_screen(*state) || view.is_none_or(|v| { let o = @@ -5705,9 +5830,10 @@ impl Game<'_> { let start = out.len(); self.block_model_vertices( f.state, - f.start_pos, + horizon_core::random::position_seed(f.start_pos), glam::Mat4::from_translation(o), packed, + false, &mut out, ); let tint = horizon_client::mobs::render::abgr(tint); @@ -6055,38 +6181,6 @@ impl Game<'_> { false, ) } - fn tick_block_entities(&mut self) -> Result<()> { - self.tick_hoppers()?; - self.tick_crafters(); - self.tick_mount_menu(); - self.tick_jukeboxes(); - self.tick_beacons(); - self.tick_creaking_hearts()?; - self.tick_spawners()?; - self.tick_trial_spawners()?; - self.tick_vaults()?; - self.tick_beehives(); - let mut lit_changes = Vec::new(); - for (pos, entity) in self.world.block_entities.iter_mut() { - if let BlockEntity::Furnace(f) = entity - && let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) - { - lit_changes.push((*pos, lit)); - } - } - for ((x, y, z), lit) in lit_changes { - let state = self.world.block(x, y, z); - if let Some(mut s) = self.pack.assets.registry.state(state).cloned() - && s.properties.contains_key("lit") - { - s.properties.insert("lit".into(), lit.to_string()); - if let Ok(id) = self.pack.assets.registry.resolve(&s) { - self.world.set(x, y, z, id)?; - } - } - } - Ok(()) - } /// Copies of a save batch carrying its live block entities and save data. fn with_entities<'a>( &self, @@ -6231,7 +6325,8 @@ impl Game<'_> { self.fns = Default::default(); self.bosses = Default::default(); reset_world_progress(&mut self.adv, &mut self.stats); - self.restore_player_environment = true; + self.prefetch_advancement_tree(); + self.restore_player_state = true; // RandomSequences: the world's data/minecraft/random_sequences.dat. self.rand_sequences = horizon_client::save::read_dat(&save_root.join("data/minecraft/random_sequences.dat")) @@ -6368,6 +6463,8 @@ impl Game<'_> { self.clear_entities(); self.travelling = None; self.player = None; + self.sleeping = None; + self.sleep_timer = 0; self.spawn = None; self.respawn_travel = None; self.respawn_config = @@ -6461,7 +6558,10 @@ impl Game<'_> { res.threads, ) } else { - let inner = Arc::new(VanillaTerrain::for_dimension(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id()).map_err(|e| { + // WorldOptions.generateStructures, from the world's settings. + let structures = + horizon_client::save::WorldGen::read(world_root).is_none_or(|w| w.structures); + let inner = Arc::new(VanillaTerrain::for_world(&self.options.resources.join("worldgen"), pack.assets.registry, &res.biomes, seed, dim.id(), structures).map_err(|e| { format!("{e}\nPrepare the worldgen bundle with the launcher, or: horizon-prepare --prepare") })?); self.end.set_locator(Some(inner.clone())); @@ -6484,8 +6584,9 @@ impl Game<'_> { streaming.biome_zoom = BiomeZoom::new(obfuscate_seed(seed)); streaming.sky_light = dim != Dim::Nether; streaming.nether_shading = dim == Dim::Nether; - // The integrated server draws nothing (the dedicated server keeps its behaviour). - streaming.mesh = !self.options.integrated; + // A server draws nothing: neither the integrated server nor the + // dedicated one meshes sections. + streaming.mesh = !self.options.integrated && self.options.dedicated.is_none(); Ok((streaming, save)) } /// Change dimension through a portal (Entity.changeDimension with @@ -6725,6 +6826,8 @@ impl Game<'_> { self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; + self.sleeping = None; + self.sleep_timer = 0; self.clear_entities(); self.screen = Screen::Playing; if let Some(r) = self.renderer.as_mut() { @@ -7336,7 +7439,9 @@ impl Game<'_> { let mut r = dispenser::entity_random(); let _yaw = r.next_float(); let p = Vec3::new(at[0], at[1], at[2]); + self.next_entity += 1; self.orbs.push(ExperienceOrb { + id: self.next_entity, position: p, previous: p, velocity: Vec3::new( @@ -7400,13 +7505,29 @@ impl Game<'_> { .player .as_ref() .filter(|p| !p.health.dead_or_dying() && !spectator); - let target = player.map(|p| { - [ - p.position.x, - p.position.y + f64::from(p.dimensions.eye_height) / 2.0, - p.position.z, - ] - }); + // ExperienceOrb.followNearbyPlayer: each orb goes for the nearest + // living player within 8 blocks, the host's own or a guest. + let mut followed: Vec<([f64; 3], [f64; 3])> = player + .map(|p| { + let feet = [p.position.x, p.position.y, p.position.z]; + let eye = f64::from(p.dimensions.eye_height); + (feet, [feet[0], feet[1] + eye / 2.0, feet[2]]) + }) + .into_iter() + .collect(); + if let Some(host) = self.lan.as_ref() { + followed.extend( + host.hub + .guests + .iter() + .filter(|g| g.placed && g.loaded && !g.dead && g.health > 0.0) + .filter(|g| !g.spectator()) + .map(|g| { + let p = g.position; + (p, [p[0], p[1] + g.eye_height() / 2.0, p[2]]) + }), + ); + } let bounds = player.map(|p| { let w = f64::from(p.dimensions.width) / 2.0; ( @@ -7419,7 +7540,19 @@ impl Game<'_> { ) }); let mut orbs = std::mem::take(&mut self.orbs); - orbs.retain_mut(|o| o.tick(&self.world, &self.res.facts, self.collision, target)); + orbs.retain_mut(|o| { + let distance = |feet: &[f64; 3]| -> f64 { + (feet[0] - o.position.x).powi(2) + + (feet[1] - o.position.y).powi(2) + + (feet[2] - o.position.z).powi(2) + }; + let target = followed + .iter() + .filter(|(feet, _)| distance(feet) < 64.0) + .min_by(|a, b| distance(&a.0).total_cmp(&distance(&b.0))) + .map(|(_, target)| *target); + o.tick(&self.world, &self.res.facts, self.collision, target) + }); let mut gained = 0; let mut taken = Vec::new(); if let Some((min, max)) = bounds { @@ -7453,19 +7586,25 @@ impl Game<'_> { (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; self.audio .play("minecraft:entity.experience_orb.pickup", at, 0.1, pitch); - if self.experience.give(gained as i32) - && self.experience.level % 5 == 0 - && self.ticks > self.last_level_up + 100 - { - self.last_level_up = self.ticks; - let volume = if self.experience.level > 30 { - 1.0 - } else { - self.experience.level as f32 / 30.0 - }; - self.audio - .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); - } + self.give_orb_points(gained); + } + } + /// `Player.giveExperiencePoints`, and `giveExperienceLevels`' level-up + /// sound every fifth level (at most every 100 ticks). + pub(super) fn give_orb_points(&mut self, gained: u32) { + let at = self.eye_position(); + if self.experience.give(gained as i32) + && self.experience.level % 5 == 0 + && self.ticks > self.last_level_up + 100 + { + self.last_level_up = self.ticks; + let volume = if self.experience.level > 30 { + 1.0 + } else { + self.experience.level as f32 / 30.0 + }; + self.audio + .play("minecraft:entity.player.levelup", at, volume * 0.75, 1.0); } } /// BowItem.releaseUsing: power from charge time, arrows at power * 3. @@ -7554,6 +7693,7 @@ impl Game<'_> { // GameRenderer.renderItemInHand: F1 hides the hand with the HUD. if self.spectator() || self.ui.hide_gui + || self.sleeping.is_some() || !self.camera_type.first_person() || self .player @@ -7750,27 +7890,13 @@ impl Game<'_> { pack: &PackResources, atlas: &HudAtlas, ) -> Result { - let assets = &pack.assets; - let mut renderer = pollster::block_on(Renderer::new( + build_renderer( window, self.options.offscreen, - &assets.pixels, - assets.sprite_size, - assets.sprite_minimum_size, - assets.texture_layers, - &assets.sprite_mips, - &assets.animations, - (&atlas.pixels, atlas.width, atlas.height), - (&pack.forcefield.2, pack.forcefield.0), - &pack.panorama, + pack, + atlas, self.renderer.as_ref(), - ))?; - renderer.hud.fire_animations = atlas - .fire_animations - .iter() - .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) - .collect(); - Ok(renderer) + ) } fn apply_settings(&mut self) { if let Some(r) = &self.renderer { @@ -8029,44 +8155,59 @@ impl Game<'_> { return; } self.message = Some(("Respawn point set".into(), Instant::now())); - self.sleeping = Some((head, 0)); + self.stop_mining(); + self.left = false; + self.right = false; + self.using = None; + self.sleeping = Some(head); + self.sleep_timer = 0; self.stats.custom("sleep_in_bed", 1); self.trigger_player("minecraft:slept_in_bed"); self.stats.reset("custom", "minecraft:time_since_rest"); } + fn wake_up(&mut self) { + if self.remote.is_some() { + // InBedChatScreen.sendWakeUp: the server wakes the player. + self.remote_stop_sleeping(); + return; + } + self.sleeping = None; + self.sleep_timer = 100; + } fn tick_sleep(&mut self) { - let Some((head, ticks)) = self.sleeping else { - return; - }; - if self.keys.contains(&KeyCode::ShiftLeft) - || self - .player - .as_ref() - .is_none_or(|p| p.health.dead_or_dying()) - { - self.sleeping = None; - return; + self.sleep_timer = tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); + if let Some(head) = self.sleeping { + if self.keys.contains(&KeyCode::ShiftLeft) + || self + .player + .as_ref() + .is_none_or(|p| p.health.dead_or_dying()) + { + self.wake_up(); + return; + } + if let Some(p) = self.player.as_mut() { + p.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + p.velocity = Vec3::ZERO; + } } - if let Some(p) = self.player.as_mut() { - p.position = Vec3::new( - f64::from(head[0]) + 0.5, - f64::from(head[1]) + 0.5625, - f64::from(head[2]) + 0.5, - ); - p.velocity = Vec3::ZERO; - } - let ticks = ticks + 1; - // ServerLevel: once everyone has slept 100 ticks, skip to morning and clear weather. - if ticks >= 100 { + // ServerLevel.tick: once enough of the players have slept 100 ticks, + // skip to morning, clear the weather and wake everyone. + if self.enough_slept() { let t = self.world.day_time; self.world.day_time = t + 24000 - t.rem_euclid(24000); self.world.weather.raining = false; self.world.weather.thundering = false; self.world.weather.rain_time = 0; self.world.weather.thunder_time = 0; - self.sleeping = None; - } else { - self.sleeping = Some((head, ticks)); + if self.sleeping.is_some() { + self.wake_up(); + } + self.wake_guests(); } } fn creative_origin(batch: &HudBatch) -> (f32, f32) { @@ -8369,6 +8510,7 @@ impl Game<'_> { level.food = p.health.food.food; level.saturation = p.health.food.saturation; + level.flying = p.flying; } level.inventory = self .inventory @@ -8424,18 +8566,10 @@ impl Game<'_> { if self.remote.is_some() { return Ok(()); } - self.streaming.save(&mut self.world, wait); - let keys: Vec<_> = self.world.modified.drain().collect(); - let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); - self.save - .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; - if wait { - self.save.flush(); - } - self.save_entities(wait)?; + self.save_level(wait)?; + self.save_parked_levels(wait)?; self.save_maps(); self.save_random_sequences(); - self.save_raids(); self.save_fight(); self.save_wandering_trader(); self.save_portal_arrivals(); @@ -8452,6 +8586,20 @@ impl Game<'_> { self.message = Some(("Saved the game".into(), Instant::now())); Ok(()) } + /// Save the level in place: its changed chunks, its entities and its raids. + fn save_level(&mut self, wait: bool) -> Result<()> { + self.streaming.save(&mut self.world, wait); + let keys: Vec<_> = self.world.modified.drain().collect(); + let chunks = self.with_entities(keys.iter().filter_map(|k| self.world.chunks.get(k))); + self.save + .save_later(&chunks, self.pack.assets.registry, &self.res.biomes)?; + if wait { + self.save.flush(); + } + self.save_entities(wait)?; + self.save_raids(); + Ok(()) + } fn render(&mut self) -> Result { self.poll_shader_pack(); let Some(size) = self @@ -8489,6 +8637,22 @@ impl Game<'_> { camera.y.floor() as i32, camera.z.floor() as i32, ]; + // The camera inside an opaque block sees nothing through it: disable. + let cave_culling = self.settings.horizon.cave_culling + && !self + .res + .facts + .get(self.world.block(block[0], block[1], block[2])) + .solid_render; + // The cave culling search runs on its worker while the frame is prepared. + if cave_culling + && self.title.is_none() + && let Some(renderer) = self.renderer.as_mut() + { + horizon_client::spans::time("occlusion", || { + renderer.start_occlusion(camera, (self.streaming.radius * 16) as f32) + }); + } let biome = self .world .chunks @@ -8677,13 +8841,7 @@ impl Game<'_> { skybox: self.dim == Dim::Overworld && self.settings.horizon.sky, end_sky: self.dim == Dim::End && self.settings.horizon.sky, environment_fog: (self.dim == Dim::Nether).then_some((sky.fog_start, sky.fog_end)), - // The camera inside an opaque block sees nothing through it: disable. - cave_culling: self.settings.horizon.cave_culling - && !self - .res - .facts - .get(self.world.block(block[0], block[1], block[2])) - .solid_render, + cave_culling, water_fog, fog: Some({ let mut fog = self.frame_fog(camera, &sky, biome); @@ -8874,6 +9032,18 @@ impl Game<'_> { } /// A key press while a world is open (keyboard or control socket). fn key_pressed(&mut self, key: KeyCode) -> Result<()> { + if self.sleeping.is_some() + && self.screen == Screen::Playing + && !matches!( + key, + KeyCode::F1 | KeyCode::F2 | KeyCode::F11 | KeyCode::KeyT | KeyCode::Slash + ) + { + if matches!(key, KeyCode::Escape | KeyCode::ShiftLeft) { + self.wake_up(); + } + return Ok(()); + } if self.sort_key_press(key) { return Ok(()); } @@ -9004,6 +9174,9 @@ impl Game<'_> { } /// A mouse button while playing (window or control socket). fn play_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { + if self.sleeping.is_some() { + return Ok(()); + } if self.remote.is_some() { return self.remote_mouse(button, pressed); } @@ -9333,6 +9506,7 @@ impl ApplicationHandler for Game<'_> { title.scroll_worlds(d, self.cursor, (batch.width, batch.height)); } if self.screen == Screen::Playing + && self.sleeping.is_none() && self.player.is_some() && !self.extras_scroll(d) && let Some((wheel, _)) = @@ -9606,9 +9780,6 @@ impl ApplicationHandler for Game<'_> { self.station_text(event.text.as_deref(), backspace); } } - WindowEvent::KeyboardInput { event, .. } if self.remote_chat_open() => { - self.remote_chat_key(&event) - } WindowEvent::KeyboardInput { event, .. } if self.screen == Screen::WorldOptions && !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) => @@ -9715,7 +9886,6 @@ impl ApplicationHandler for Game<'_> { && self.title.is_none() && self.sign_edit.is_none() && self.book.is_none() - && !self.remote_chat_open() { let turn = |k| f32::from(u8::from(self.keys.contains(&k))); let secs = elapsed.as_secs_f32().min(0.1); @@ -9810,6 +9980,10 @@ impl ApplicationHandler for Game<'_> { self.pause = self.pauses_game(); if let Some(server) = &self.integrated { server.set_paused(self.pause); + server.set_distances( + self.settings.render_distance, + self.settings.simulation_distance, + ); } self.clock.end_frame(self.pause); let finished = self @@ -10124,10 +10298,14 @@ impl<'a> Game<'a> { avatar: Default::default(), flash: 0, sleeping: None, + sleep_timer: 0, dim: Dim::Overworld, world_root: PathBuf::new(), travelling: None, - server_trip: None, + server_trips: Vec::new(), + level_teleports: Vec::new(), + levels: Default::default(), + level_pass: Default::default(), portals: Default::default(), end_travel: false, respawn_config: None, @@ -10230,9 +10408,12 @@ impl<'a> Game<'a> { lan_entity_events: Vec::new(), lid_openers: HashMap::new(), lan_acting: None, + guest_packets: Vec::new(), lan_acting_name: None, lan_acting_uuid: None, chat_capture: None, + admin_feedback: Vec::new(), + console_broadcast: None, cmds: Default::default(), ui: Default::default(), combat: Default::default(), @@ -10249,7 +10430,7 @@ impl<'a> Game<'a> { tab_list: Default::default(), subtitles: Default::default(), adv: Default::default(), - restore_player_environment: true, + restore_player_state: true, stats_ui: Default::default(), adv_ui: Default::default(), camera_type: Default::default(), @@ -10259,41 +10440,83 @@ impl<'a> Game<'a> { } } -pub fn run() -> Result<()> { - let Some(mut options) = Options::read()? else { - return Ok(()); - }; - if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { - return Ok(()); +/// The data the background loader produces for `Game::new`. +struct Loaded { + root: PathBuf, + pack_error: Option, + resources: Resources, + pack: PackResources, + atlas: HudAtlas, +} + +/// The loader's checkpoints, in order; the loading screen reports them. +const STAGES: u32 = 9; +const STAGE_LINES: [&str; 9] = [ + "Loading assets", + "Loading block facts", + "Loading items", + "Loading biomes", + "Loading pack tables", + "Loading atlas", + "Loading collision", + "Loading resources", + "Starting audio", +]; + +/// The background loader's checkpoint, read by the loading screen each frame. +#[derive(Clone)] +struct Progress(Arc); +impl Progress { + fn new() -> Self { + Self(Arc::new(AtomicU32::new(0))) } - let started = Instant::now(); - horizon_client::spans::enable(options.spikes.is_some()); - let vanilla_root = options.resources.clone(); - let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); - // Snapshots of derived tables live in the game folder, never beside the - // shared resources. - Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache")); + fn set(&self, stage: u32) { + self.0.store(stage, Ordering::Relaxed); + } + fn fraction(&self) -> f32 { + self.0.load(Ordering::Relaxed) as f32 / (STAGES - 1) as f32 + } + fn line(&self) -> &'static str { + STAGE_LINES[(self.0.load(Ordering::Relaxed) as usize).min(STAGE_LINES.len() - 1)] + } +} + +/// Harness and dedicated runs keep the fully-synchronous startup so their +/// output stays byte-identical; only an ordinary launch shows the window first. +fn synchronous_startup(options: &Options) -> bool { + let classic = std::env::var("HORIZON_MENU_STYLE").ok().as_deref() == Some("classic"); + options.frames.is_some() + || options.world_frames.is_some() + || options.benchmark.is_some() + || options.control.is_some() + || options.dedicated.is_some() + || classic + || std::env::var_os("HORIZON_DISPENSE_FIXTURE").is_some() + || std::env::var_os("HORIZON_SCULK_FIXTURE").is_some() + || std::env::var_os("HORIZON_COMMAND_SCRIPT").is_some() + || std::env::var_os("HORIZON_NET_REPORT").is_some() +} + +/// The current loading sequence, unchanged, as a function so the synchronous +/// launch can run it on the main thread and an ordinary launch on a worker. +/// `on_stage` reports [`STAGES`] checkpoints to the loading screen. +fn load_resources( + mut root: PathBuf, + vanilla_root: &std::path::Path, + settings: &Settings, + started: Instant, + on_stage: &(dyn Fn(u32) + Sync), +) -> Result { let mut pack_error = None; - options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs) - .unwrap_or_else(|e| { - log::warn!("Horizon: resource packs not applied: {e}"); - pack_error = Some(e.to_string()); - vanilla_root.clone() - }); - options.resources = mods::content_root( - &options.resources, - &early_settings.mods.enabled, - &options.dev_mods, - ); - let assets = match Assets::load(&options.resources) { + let assets = match Assets::load(&root) { Ok(assets) => assets, // Minecraft.rollbackResourcePacks: the packs break loading, start // with the game's own resources. - Err(e) if options.resources != vanilla_root => { + Err(e) if root != vanilla_root => { log::warn!("Horizon: resource packs failed to load ({e}); using the default resources"); pack_error = Some(e.to_string()); - options.resources = vanilla_root.clone(); - Assets::load(&vanilla_root)? + root = vanilla_root.to_path_buf(); + Assets::load(vanilla_root)? } Err(e) => { return Err(format!( @@ -10302,9 +10525,9 @@ pub fn run() -> Result<()> { .into()); } }; - let root = options.resources.clone(); let assets = Arc::new(assets); log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(0); let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( std::fs::File::open(root.join("block-behaviours.json"))?, ))?; @@ -10313,31 +10536,37 @@ pub fn run() -> Result<()> { let mob_data = horizon_client::mobs::MobData::load(&root, &facts); horizon_client::mobs::trial_spawner::load_registry(&root); log::info!("load facts: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(1); let items = Items::load(&root, assets.registry, &facts)?; log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(2); let recipes = Recipes::load(&root, &items)?; let transformers = horizon_client::block_transform::Transformers::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let environment = Environment::load(&root)?; log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(3); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; log::info!("load pack tables: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(4); let atlas = HudAtlas::build(&root)?; horizon_client::ui::load_metadata(&root); horizon_client::lang::set(horizon_client::lang::Language::load( &[&root], - &early_settings.language, + &settings.language, )); log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); + on_stage(5); let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; - let motion = MotionResources::load(&root, ®istry_owner)?; + let motion = MotionResources::load_with_facts(&root, ®istry_owner, &facts)?; log::info!( "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); - let threads = early_settings.horizon.worker_threads(); + on_stage(6); + let threads = settings.horizon.worker_threads(); log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", started.elapsed().as_secs_f32(), @@ -10346,16 +10575,11 @@ pub fn run() -> Result<()> { biomes.list.len(), threads ); - let audio = if options.dedicated.is_some() { - Audio::silent(&root) - } else { - Audio::new(&root) - }; let stations = horizon_client::stations::StationData::load(&root, &items); let animate = horizon_client::animate_tick::AnimateTables::load(&root, registry_owner.registry, &biomes)?; let fog = horizon_client::fog::FogTables::load(&root, &biomes); - let resources = Arc::new(Resources { + let resources = Resources { stations, facts, items, @@ -10392,11 +10616,159 @@ pub fn run() -> Result<()> { player_type: perspective::player_type(&root), player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") .and_then(|m| m.children.into_iter().find(|c| c.name == "right_arm")), - }); + }; // Both inputs are needed only while constructing the behaviour tables. // Release their owned JSON/Arc buffers before entering the long-lived game loop. drop(gameplay_projection); drop(behaviour_json); + on_stage(7); + Ok(Loaded { + root, + pack_error, + resources, + pack, + atlas, + }) +} + +/// The renderer from a pack's block sprites, its shared atlas and its border +/// texture; `previous` shares the device and window surface with an old one. +fn build_renderer( + window: Arc, + offscreen: bool, + pack: &PackResources, + atlas: &HudAtlas, + previous: Option<&Renderer>, +) -> Result { + let assets = &pack.assets; + let mut renderer = pollster::block_on(Renderer::new( + window, + offscreen, + &assets.pixels, + assets.sprite_size, + assets.sprite_minimum_size, + assets.texture_layers, + &assets.sprite_mips, + &assets.animations, + (&atlas.pixels, atlas.width, atlas.height), + (&pack.forcefield.2, pack.forcefield.0), + &pack.panorama, + previous, + ))?; + renderer.hud.fire_animations = atlas + .fire_animations + .iter() + .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .collect(); + Ok(renderer) +} + +/// The loading screen's renderer: the real HUD atlas and font over one opaque +/// white block-sprite layer, an empty border texture and an empty panorama. +fn loading_renderer( + window: Arc, + offscreen: bool, + atlas: Option<&HudAtlas>, +) -> Result { + static FORCEFIELD: [u8; 4] = [0; 4]; + static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255]; + let panorama = horizon_client::gfx::panorama::Faces { + size: 1, + pixels: [0u8; 4].repeat(6), + }; + let (pixels, width, height) = match atlas { + Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height), + None => (EMPTY_HUD.as_slice(), 1, 1), + }; + let mut renderer = pollster::block_on(Renderer::new( + window, + offscreen, + &[255, 255, 255, 255], + 1, + 1, + 1, + &[], + &[], + (pixels, width, height), + (&FORCEFIELD[..], 1), + &panorama, + None, + ))?; + if let Some(atlas) = atlas { + renderer.hud.fire_animations = atlas + .fire_animations + .iter() + .map(|(rect, animation)| (*rect, animation.clone(), usize::MAX)) + .collect(); + } + Ok(renderer) +} + +/// A title-shaped frame: black clear and panorama, only the HUD is drawn. +fn loading_frame(hud: &HudBatch) -> Frame<'_> { + Frame { + camera: glam::DVec3::new(0.5, 100.0, 0.5), + yaw: 0.0, + pitch: 10.0, + fov_degrees: 85.0, + bob: glam::Mat4::IDENTITY, + sky: horizon_client::environment::Sky::default(), + distance: 12.0, + depth_far: 1000.0, + underwater: false, + cave_culling: false, + title: true, + skybox: false, + end_sky: false, + environment_fog: None, + water_fog: [0.0; 3], + fog: None, + dark_disc: false, + outline: Vec::new(), + outline_after_terrain: false, + debug_lines: &[], + debug_lines_on_top: &[], + debug_crosshair: &[], + hud, + nether_lighting: false, + entities: &[], + clouds: None, + additive: &[], + see_through: &[], + celestial: &[], + hand: &[], + hand_fov_degrees: 70.0, + screen: &[], + border: None, + game_time: 0.0, + shader_game_time: 0.0, + end_portal_sprites: [[0.0; 4]; 2], + crumbling_sprite: [0.0; 4], + ticks: 0, + darkness: (0.0, 0.0), + night_vision: 0.0, + block_flicker: 0.0, + post: None, + menu_blur: None, + shader: Default::default(), + } +} + +/// The post-load setup once the resources are ready: `Game::new` and the +/// options, packs, mods, control socket, benchmark and world selection the +/// old `run` did after loading. `None` means a harness or dedicated run +/// finished here instead. +#[allow(clippy::too_many_arguments)] +fn start_game<'a>( + res: &'a Arc, + pack: PackResources, + atlas: HudAtlas, + options: Options, + pack_error: Option, + audio: Audio, + vanilla_root: PathBuf, + started: Instant, +) -> Result>> { let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); // Scripted and frame-limited runs (the parity harnesses) see vanilla's @@ -10409,7 +10781,7 @@ pub fn run() -> Result<()> { if let Some(d) = options.distance_override { settings.render_distance = d; } - let mut game = Game::new(&resources, pack, atlas, options, settings, audio)?; + let mut game = Game::new(res, pack, atlas, options, settings, audio)?; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { game.open_options_at(true, horizon_client::options_ui::Page::Packs); @@ -10459,13 +10831,16 @@ pub fn run() -> Result<()> { ); } if let Ok(spec) = std::env::var("HORIZON_DISPENSE_FIXTURE") { - return game.dispense_fixture(&spec); + game.dispense_fixture(&spec)?; + return Ok(None); } if let Ok(spec) = std::env::var("HORIZON_SCULK_FIXTURE") { - return game.sculk_fixture(&spec); + game.sculk_fixture(&spec)?; + return Ok(None); } if game.options.dedicated.is_some() { - return game.run_dedicated(); + game.run_dedicated()?; + return Ok(None); } match game.options.world.clone() { _ if game.options.server.is_some() => { @@ -10475,7 +10850,8 @@ pub fn run() -> Result<()> { ); game.connect_server(&address, &name)?; if let Some(report) = std::env::var_os("HORIZON_NET_REPORT") { - return game.run_net_harness(report.as_ref()); + game.run_net_harness(report.as_ref())?; + return Ok(None); } } Some(folder) => { @@ -10501,9 +10877,13 @@ pub fn run() -> Result<()> { std::env::var_os("HORIZON_COMMAND_SCRIPT"), std::env::var_os("HORIZON_COMMAND_OUTPUT"), ) { - return game.run_command_harness(script.as_ref(), output.as_ref()); + game.run_command_harness(script.as_ref(), output.as_ref())?; + return Ok(None); } - EventLoop::new()?.run_app(&mut game)?; + Ok(Some(game)) +} + +fn write_report(game: &Game<'_>) -> Result<()> { if let Some(path) = &game.options.report { let report = serde_json::json!({ "frames": game.frames, @@ -10516,12 +10896,399 @@ pub fn run() -> Result<()> { }); std::fs::write(path, serde_json::to_vec_pretty(&report)?)?; } - if let Some(e) = game.error { + Ok(()) +} + +fn run_event_loop(mut game: Game<'_>) -> Result<()> { + EventLoop::new()?.run_app(&mut game)?; + write_report(&game)?; + if let Some(e) = game.error.take() { return Err(e); } Ok(()) } +/// The loading screen's state while the worker loads the resources. +struct Loading { + window: Option>, + renderer: Option, + atlas: Option, + settings: Settings, + fullscreen: horizon_client::window::FullscreenState, + options: Option, + vanilla_root: PathBuf, + pack_error: Option, + started: Instant, + progress: Progress, + receiver: Receiver>, + loaded: Option>, + handle: Option>, + shown: bool, + error: Option>, +} +impl Loading { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + if self.window.is_some() { + return; + } + // The Window constructor: created fullscreen when options.txt says so. + let fullscreen = self.settings.fullscreen; + self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen); + let attributes = Window::default_attributes() + .with_title("Horizon") + .with_window_icon(horizon_client::window::icon()); + // Wayland names the window by its app id, which the horizon.desktop entry matches. + #[cfg(target_os = "linux")] + let attributes = winit::platform::wayland::WindowAttributesExtWayland::with_name( + attributes, "horizon", "horizon", + ); + let window = match event_loop.create_window( + attributes + .with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0)) + .with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))), + ) { + Ok(w) => Arc::new(w), + Err(e) => { + self.error = Some(e.into()); + event_loop.exit(); + return; + } + }; + let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); + match loading_renderer(window.clone(), offscreen, self.atlas.as_ref()) { + Ok(r) => self.renderer = Some(r), + Err(e) => { + self.error = Some(e); + event_loop.exit(); + return; + } + } + if let Some(r) = &self.renderer { + self.settings + .clamp_gui_scale([r.config.width as i32, r.config.height as i32]); + } + horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); + self.window = Some(window); + } + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + if self.window.as_ref().is_none_or(|w| w.id() != id) { + return; + } + match event { + WindowEvent::CloseRequested => event_loop.exit(), + WindowEvent::Resized(size) => { + if let Some(r) = &mut self.renderer { + r.resize(size.width, size.height); + } + } + WindowEvent::RedrawRequested => self.draw(), + _ => {} + } + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if self.loaded.is_none() { + match self.receiver.try_recv() { + Ok(result) => self.loaded = Some(result), + Err(TryRecvError::Disconnected) => { + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + self.error = Some("resource loader stopped before finishing".into()); + event_loop.exit(); + return; + } + Err(TryRecvError::Empty) => {} + } + } + if let Some(w) = &self.window { + if self.options.as_ref().is_some_and(|o| o.offscreen) { + self.draw(); + } else { + w.request_redraw(); + } + } + event_loop.set_control_flow(ControlFlow::Poll); + } + fn draw(&mut self) { + let Some(renderer) = self.renderer.as_mut() else { + return; + }; + let size = [renderer.config.width, renderer.config.height]; + let mut batch = HudBatch::new(size); + if let Some(atlas) = &self.atlas { + horizon_client::level_loading::draw_progress( + &mut batch, + atlas, + self.progress.line(), + self.progress.fraction(), + ); + } + let frame = loading_frame(&batch); + if let Err(e) = renderer.render(&frame) { + log::warn!("Horizon: loading screen frame failed: {e}"); + } + if !self.shown { + self.shown = true; + log::info!( + "Horizon: loading screen shown after {} ms", + self.started.elapsed().as_millis() + ); + } + } + fn finish(&mut self, loaded: Loaded) -> Result>> { + let mut options = self.options.take().ok_or("loading already finished")?; + options.resources = loaded.root.clone(); + self.progress.set(STAGES - 1); + // Audio is created on the main thread, after the join. + let audio = if options.dedicated.is_some() { + Audio::silent(&options.resources) + } else { + Audio::new(&options.resources) + }; + let window = self.window.clone().ok_or("window closed")?; + // Keep the loader's device and swap in the real textures in one step. + if let Some(renderer) = &mut self.renderer { + renderer.release_surface(); + } + let renderer = build_renderer( + window.clone(), + options.offscreen, + &loaded.pack, + &loaded.atlas, + self.renderer.as_ref(), + )?; + let pack_error = loaded.pack_error.or_else(|| self.pack_error.take()); + // The game borrows its shared resources for the process's lifetime, + // like the single copy an integrated server would share. + let res: &'static Arc = Box::leak(Box::new(Arc::new(loaded.resources))); + let Some(mut game) = start_game( + res, + loaded.pack, + loaded.atlas, + options, + pack_error, + audio, + self.vanilla_root.clone(), + self.started, + )? + else { + return Ok(None); + }; + game.window = Some(window); + game.renderer = Some(renderer); + game.fullscreen = self.fullscreen; + game.apply_settings(); + game.previous = Instant::now(); + Ok(Some(game)) + } +} + +/// The application: the loading screen until the resources are ready, then +/// the game itself, on the same event loop and window. +enum App { + Loading(Box), + Ready(Box>), +} +impl ApplicationHandler for App { + fn resumed(&mut self, event_loop: &ActiveEventLoop) { + match self { + App::Loading(loading) => loading.resumed(event_loop), + App::Ready(game) => game.resumed(event_loop), + } + } + fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) { + match self { + App::Loading(loading) => loading.window_event(event_loop, id, event), + App::Ready(game) => game.window_event(event_loop, id, event), + } + } + fn device_event(&mut self, event_loop: &ActiveEventLoop, id: DeviceId, event: DeviceEvent) { + if let App::Ready(game) = self { + game.device_event(event_loop, id, event); + } + } + fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + enum Step { + Waiting, + Ready(Box>), + Done, + Failed(Box), + } + let step = match self { + App::Ready(game) => { + game.about_to_wait(event_loop); + return; + } + App::Loading(loading) => { + loading.about_to_wait(event_loop); + if loading.error.is_some() { + event_loop.exit(); + return; + } + match loading.loaded.take() { + None => Step::Waiting, + Some(Err(e)) => Step::Failed(e.into()), + Some(Ok(loaded)) => match loading.finish(loaded) { + Ok(Some(game)) => Step::Ready(Box::new(game)), + Ok(None) => Step::Done, + Err(e) => Step::Failed(e), + }, + } + } + }; + match step { + Step::Waiting => {} + Step::Ready(game) => *self = App::Ready(game), + Step::Done => event_loop.exit(), + Step::Failed(e) => { + if let App::Loading(loading) = self { + loading.error = Some(e); + } + event_loop.exit(); + } + } + } + fn exiting(&mut self, event_loop: &ActiveEventLoop) { + if let App::Ready(game) = self { + game.exiting(event_loop); + } + } +} + +/// The ordinary launch: load the resources on a worker while the window shows +/// the loading screen, then swap in the game on the main thread. +fn run_loading( + options: Options, + settings: Settings, + vanilla_root: PathBuf, + pack_error: Option, + started: Instant, +) -> Result<()> { + let progress = Progress::new(); + let (sender, receiver) = std::sync::mpsc::channel(); + let loader = { + let progress = progress.clone(); + let settings = settings.clone(); + let vanilla_root = vanilla_root.clone(); + let root = options.resources.clone(); + std::thread::Builder::new() + .name("resource-loader".into()) + .spawn(move || { + let result = load_resources(root, &vanilla_root, &settings, started, &|stage| { + progress.set(stage) + }) + .map_err(|e| e.to_string()); + let _ = sender.send(result); + })? + }; + let atlas = HudAtlas::build(&options.resources).ok(); + let loading = Loading { + window: None, + renderer: None, + atlas, + settings, + fullscreen: horizon_client::window::FullscreenState::new(false), + options: Some(options), + vanilla_root, + pack_error, + started, + progress, + receiver, + loaded: None, + handle: Some(loader), + shown: false, + error: None, + }; + let mut app = App::Loading(Box::new(loading)); + EventLoop::new()?.run_app(&mut app)?; + match app { + App::Ready(mut game) => { + write_report(&game)?; + if let Some(e) = game.error.take() { + return Err(e); + } + } + App::Loading(loading) => { + if let Some(e) = loading.error { + return Err(e); + } + } + } + Ok(()) +} + +pub fn run() -> Result<()> { + let Some(mut options) = Options::read()? else { + return Ok(()); + }; + if options.dedicated.is_some() && !dedicated::preflight(&mut options)? { + return Ok(()); + } + let started = Instant::now(); + horizon_client::spans::enable(options.spikes.is_some()); + let vanilla_root = options.resources.clone(); + let early_settings = Settings::load(&std::env::current_dir()?.join("options.txt")); + // Snapshots of derived tables live in the game folder, never beside the + // shared resources. + Behaviours::set_cache_dir(std::env::current_dir()?.join(".horizon-cache")); + let mut pack_error = None; + options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs) + .unwrap_or_else(|e| { + log::warn!("Horizon: resource packs not applied: {e}"); + pack_error = Some(e.to_string()); + vanilla_root.clone() + }); + options.resources = mods::content_root( + &options.resources, + &early_settings.mods.enabled, + &options.dev_mods, + ); + // Harnesses and dedicated runs stay synchronous; a normal launch enters + // the event loop at once and loads the resources on a worker. + if !synchronous_startup(&options) { + return run_loading(options, early_settings, vanilla_root, pack_error, started); + } + let loaded = load_resources( + options.resources.clone(), + &vanilla_root, + &early_settings, + started, + &|_| {}, + )?; + options.resources = loaded.root.clone(); + let audio = if options.dedicated.is_some() { + Audio::silent(&options.resources) + } else { + Audio::new(&options.resources) + }; + let resources = Arc::new(loaded.resources); + let game = start_game( + &resources, + loaded.pack, + loaded.atlas, + options, + loaded.pack_error.or(pack_error), + audio, + vanilla_root, + started, + )?; + if let Some(game) = game { + run_event_loop(game)?; + } + Ok(()) +} + +// Player.tick: cap the sleeping fade at 100, then fade out over 10 waking ticks. +fn tick_sleep_timer(timer: u32, sleeping: bool) -> u32 { + if sleeping { + (timer + 1).min(100) + } else if (1..109).contains(&timer) { + timer + 1 + } else { + 0 + } +} + fn reset_world_progress(adv: &mut advancements::AdvState, stats: &mut stats::Stats) { *adv = Default::default(); *stats = Default::default(); @@ -10556,6 +11323,35 @@ mod tests { use horizon_client::container_screen::{Button, Clicks, Release, Target}; use horizon_client::keymapping::{KeyAction, SPRINT, ToggleKeys}; + #[test] + fn sleep_fade_lasts_ten_ticks_after_waking() { + let alpha = |timer| match hud_overlays::sleep_overlay(320, 240, timer).first() { + Some(hud_layout::GuiDraw::Fill { color, .. }) => color >> 24, + None => 0, + _ => panic!("sleep overlay must be a full-screen fill"), + }; + assert_eq!(tick_sleep_timer(0, false), 0); + let mut timer = 0; + for _ in 0..50 { + timer = tick_sleep_timer(timer, true); + } + assert_eq!(alpha(timer as i32), 110); + for _ in 0..100 { + timer = tick_sleep_timer(timer, true); + } + assert_eq!(timer, 100); + assert_eq!(alpha(timer as i32), 220); + for _ in 0..5 { + timer = tick_sleep_timer(timer, false); + } + assert_eq!(alpha(timer as i32), 110); + for _ in 0..5 { + timer = tick_sleep_timer(timer, false); + } + assert_eq!(timer, 0); + assert!(hud_overlays::sleep_overlay(320, 240, timer as i32).is_empty()); + } + /// An integrated server thread shares the loaded resources with the client. #[test] fn shared_resources_can_cross_threads() { diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 22d9a4da0..882b5cc93 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -88,6 +88,9 @@ pub(super) struct AdvState { pub(super) changed: BTreeSet, pub(super) unlocked: Vec, pub(super) announced: Vec, + /// The tree being read on another thread since the world opened + /// (`prefetch_advancement_tree`), taken by the first `advancement_tree`. + pub(super) pending_tree: Option>, } /// The game's world for predicates. struct View<'a, 'g>(&'a Game<'g>); @@ -221,10 +224,27 @@ impl Game<'_> { /// The advancement tree, loaded once. pub(super) fn advancement_tree(&mut self) -> Arc { if self.adv.tree.list.is_empty() { - self.adv.tree = Arc::new(Tree::load(&self.options.resources.join("data"))); + let tree = match self.adv.pending_tree.take().map(|h| h.join()) { + Some(Ok(tree)) => tree, + _ => Tree::load(&self.options.resources.join("data")), + }; + self.adv.tree = Arc::new(tree); } self.adv.tree.clone() } + /// Start reading the advancement files on another thread while the world + /// loads. The first tick's first criterion trigger used to read and parse + /// all of them on the game thread (about 60 ms). + pub(super) fn prefetch_advancement_tree(&mut self) { + if !self.adv.tree.list.is_empty() || self.adv.pending_tree.is_some() { + return; + } + let data = self.options.resources.join("data"); + self.adv.pending_tree = std::thread::Builder::new() + .name("horizon-advancements".into()) + .spawn(move || Tree::load(&data)) + .ok(); + } pub(super) fn load_advancements(&mut self) { if self.adv.loaded || self.remote.is_some() || self.no_player_here() { return; @@ -622,6 +642,19 @@ impl Game<'_> { adv::conditions(&c["player"], &pctx, w) && adv::item(&c["item"], &it, w) }); } + pub(super) fn trigger_item_entity( + &mut self, + name: &str, + stack: &ItemStack, + target: &EntityView, + ) { + if self.lan_acting.is_some() { + return; + } + let me = self.player_entity(); + let it = item_view(stack); + self.trigger(name, |c, w| adv::item_entity(c, &me, target, &it, w)); + } /// `EnterBlockTrigger`: the block, its state properties and the player. pub(super) fn trigger_enter_block(&mut self, state: horizon_world::registry::BlockStateId) { let Some(definition) = self.pack.assets.registry.state(state).cloned() else { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index 48b24bbb3..8a6b54650 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -466,9 +466,16 @@ impl Game<'_> { }), "dimension": self.dim.id(), "gamemode": format!("{:?}", self.mode).to_lowercase(), + // The bed (its head) the player sleeps in. + "sleeping": self.sleeping, + // The item in use: its slot and for how many ticks. + "using": self.using.map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "time": { "day_time": self.world.day_time, "day": self.world.day_time.div_euclid(24000), "time_of_day": self.world.day_time.rem_euclid(24000) }, "weather": { "raining": self.world.weather.raining, "thundering": self.world.weather.thundering }, "paused": self.pause, + // Mouse movement turns the camera (`apply_mouse_look`): the real + // pointer is grabbed, or an agent's `mouse-move` stands in for it. + "pointer_grabbed": self.captured || self.agent_pointer, "player": player, "selected": self.selected + 1, "held": self.held().map(|s| self.stack_value(s)), @@ -613,6 +620,9 @@ impl Game<'_> { "screen": self.screen_label(), "buttons": buttons, }); + if let Some(chat) = &self.ui.chat_screen { + v["chat_input"] = json!(chat.input.value); + } if self.title.is_some() { v["menu"] = self.title_value(); } @@ -631,6 +641,15 @@ impl Game<'_> { v["craft_size"] = json!(self.craft_size); v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind))); v["container"] = json!(self.container); + // The recipe book's buttons (GUI pixels): the book button, then + // the recipe buttons of the page, page arrows, filter and tabs. + let book = self.recipe_book_targets(); + if !book.is_empty() { + v["recipe_book"] = json!({ + "targets": book.iter().map(|t| t.rect).collect::>(), + "known": self.recipe_book_known(), + }); + } v["slot_ids"] = json!( "0-8 hotbar, 9-35 inventory, 100+ crafting grid (row-major), 200 crafting result, 300+ container, 500-503 armor, 504 offhand, 600+ station" ); diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 03a60faca..4ea8df359 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -413,6 +413,32 @@ impl Game<'_> { if a.invisible { continue; } + // ArmorStand.shouldRenderAtSqrDistance: 256 times the box's mean + // edge (4 for a marker's empty box), whatever the entity distance. + // LivingEntityRenderer grows the culling box by 0.5 for a dragon head. + let (width, height) = match (a.marker, a.small) { + (true, _) => (0.0, 0.0), + (false, true) => (0.25, 0.9875), + (false, false) => (0.5, 1.975), + }; + let edge = (width + height + width) / 3.0 * 4.0; + let range = if edge == 0.0 { 4.0 } else { edge } * 64.0; + let dragon = a.equipment[5] + .as_ref() + .is_some_and(|i| &*i.item == "minecraft:dragon_head"); + let position = super::entity_culling::at(a.position); + if !self.standing_entity_in_view( + camera, + position, + position, + alpha, + width, + height, + range, + if dragon { 0.5 } else { 0.0 }, + ) { + continue; + } let Some(model) = (if a.small { &assets.small } else { &assets.main }) else { continue; }; @@ -700,7 +726,7 @@ impl Game<'_> { } } /// `AbstractSkullBlock.getType` of a skull item. -fn skull_kind(item: &str) -> Option<&'static str> { +pub(super) fn skull_kind(item: &str) -> Option<&'static str> { Some(match item { "minecraft:skeleton_skull" => "skeleton", "minecraft:wither_skeleton_skull" => "wither_skeleton", diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 15a7de79d..73cdd15a4 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -105,24 +105,13 @@ impl Game<'_> { .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) .map_or(min, |y| y + 1) } - /// `BeaconBlockEntity.tick` for every beacon. - pub(super) fn tick_beacons(&mut self) { - let keys: Vec<(i32, i32, i32)> = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Beacon(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.remove(&key) else { - continue; - }; - self.tick_beacon(key, &mut b); - self.world - .block_entities - .insert(key, BlockEntity::Beacon(b)); - } + /// `BeaconBlockEntity.tick` of the beacon at `key`. + pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) { + let Some(BlockEntity::Beacon(mut b)) = self.world.block_entities.take(&key) else { + return; + }; + self.tick_beacon(key, &mut b); + self.world.block_entities.put(key, BlockEntity::Beacon(b)); } fn tick_beacon(&mut self, (x, y, z): (i32, i32, i32), b: &mut Beacon) { let mut check = if b.last_check_y < y { @@ -220,7 +209,11 @@ impl Game<'_> { levels } /// `applyEffects`: the powers for players within `levels * 10 + 10` (any height above). + /// `BeaconBlockEntity.applyEffects`: every player in range. fn beacon_effects(&mut self, p: [i32; 3], b: &Beacon) { + self.for_each_player(|g| g.beacon_effects_on_player(p, b)); + } + fn beacon_effects_on_player(&mut self, p: [i32; 3], b: &Beacon) { let Some(primary) = b.primary.as_deref().and_then(effect_id) else { return; }; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index 0520e4367..52fed3f3b 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -87,48 +87,37 @@ impl Game<'_> { let facing = beehive::facing_step(props.get("facing").map(String::as_str)); Some((honey, facing)) } - /// `BeehiveBlockEntity.serverTick` for every hive, after an emergency - /// exit for those with fire beside them (`BeehiveBlock.updateShape`). - pub(super) fn tick_beehives(&mut self) { - let mut keys: Vec<(i32, i32, i32)> = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Beehive(_))) - .map(|(k, _)| *k) - .collect(); - keys.sort_unstable(); - for key in keys { - let at = [key.0, key.1, key.2]; - let Some((honey, facing)) = self.hive_state(at) else { - continue; - }; - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) - else { - continue; - }; - let fire = [ - [1, 0, 0], - [-1, 0, 0], - [0, 1, 0], - [0, -1, 0], - [0, 0, 1], - [0, 0, -1], - ] - .iter() - .any(|d| { - let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]); - &*self.res.facts.get(state).name == "minecraft:fire" - }); - let mut host = GameHive { game: self }; - if fire && !hive.bees.is_empty() { - hive.release_all(at, facing, honey, Release::Emergency, &mut host); - } - hive.server_tick(at, facing, honey, &mut host); - self.world - .block_entities - .insert(key, BlockEntity::Beehive(hive)); + /// `BeehiveBlockEntity.serverTick` of the hive at `key`, after an + /// emergency exit if fire is beside it (`BeehiveBlock.updateShape`). + pub(super) fn tick_beehive(&mut self, key: (i32, i32, i32)) { + let at = [key.0, key.1, key.2]; + let Some((honey, facing)) = self.hive_state(at) else { + return; + }; + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { + return; + }; + let fire = [ + [1, 0, 0], + [-1, 0, 0], + [0, 1, 0], + [0, -1, 0], + [0, 0, 1], + [0, 0, -1], + ] + .iter() + .any(|d| { + let state = self.world.block(at[0] + d[0], at[1] + d[1], at[2] + d[2]); + &*self.res.facts.get(state).name == "minecraft:fire" + }); + let mut host = GameHive { game: self }; + if fire && !hive.bees.is_empty() { + hive.release_all(at, facing, honey, Release::Emergency, &mut host); } + hive.server_tick(at, facing, honey, &mut host); + self.world + .block_entities + .put(key, BlockEntity::Beehive(hive)); } /// `BeehiveBlockEntity.addOccupant` for a bee its `BeeEnterHiveGoal` /// sent in: off its lead, its tag stored, the bee gone. @@ -152,13 +141,13 @@ impl Game<'_> { self.mobs[i].extra.mount = None; let tag = self.mob_tree_nbt(i); let flower = bee::get(&self.mobs[i]).and_then(|b| b.flower); - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { return; }; let stored = hive.add_occupant(at, tag, flower, &mut GameHive { game: self }); self.world .block_entities - .insert(key, BlockEntity::Beehive(hive)); + .put(key, BlockEntity::Beehive(hive)); if stored && let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob) { m.removed = true; } @@ -166,13 +155,13 @@ impl Game<'_> { /// `BeehiveBlockEntity.emptyAllLivingFromHive` with no player about. pub(super) fn empty_hive(&mut self, at: [i32; 3], facing: [i32; 2], status: Release) { let key = (at[0], at[1], at[2]); - let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Beehive(mut hive)) = self.world.block_entities.take(&key) else { return; }; hive.release_all(at, facing, None, status, &mut GameHive { game: self }); self.world .block_entities - .insert(key, BlockEntity::Beehive(hive)); + .put(key, BlockEntity::Beehive(hive)); } /// `BeehiveBlock.playerDestroy` without silk touch: the bees come out /// angry at the player unless smoke calms them, then diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs new file mode 100644 index 000000000..afe1224fb --- /dev/null +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -0,0 +1,144 @@ +//! `Level.tickBlockEntities` for the block entities ticked together here +//! (hoppers, crafters, jukeboxes, beacons, creaking hearts, spawners, trial +//! spawners, vaults, beehives and furnaces): only those whose state has a +//! ticker, in vanilla's list order (`horizon_client::block_entities`), in +//! chunks that tick blocks. Sculk, brewing stands and pistons tick in their +//! own passes. +use super::Game; +use horizon_client::{ + Result, + block_entities::{Pos, Ticking}, + containers::{BlockEntity, FurnaceKind, HOPPER_SLOTS}, +}; +use horizon_world::registry::BlockStateId; + +impl Game<'_> { + pub(super) fn tick_block_entities(&mut self) -> Result<()> { + self.tick_mount_menu(); + self.load_entity_types(); + if !self.world.block_entities.has_states() { + let states = self.ticking_states(); + self.world.block_entities.set_states(states); + } + self.forget_gone_hoppers(); + let ticking = self.block_ticking_area(); + let mut spawners = Vec::new(); + let mut trial_spawners = Vec::new(); + for slot in self.world.block_entity_tickers() { + let pos = slot.0; + // Ticks before this one can remove it (`TickingBlockEntity.isRemoved`). + if !self.world.block_entities.is_live(slot) + || !ticking(pos.0, pos.2) + || !self.border.contains(f64::from(pos.0), f64::from(pos.2)) + { + continue; + } + match self.world.block_entities.get(&pos) { + Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS => { + self.tick_hopper(pos) + } + Some(BlockEntity::Crafter(_)) => self.tick_crafter(pos), + Some(BlockEntity::Jukebox(_)) => self.tick_jukebox(pos), + Some(BlockEntity::Beacon(_)) => self.tick_beacon_at(pos), + Some(BlockEntity::CreakingHeart(_)) => self.tick_creaking_heart(pos)?, + Some(BlockEntity::Spawner(_)) => { + self.tick_spawner(pos)?; + spawners.push(pos); + } + Some(BlockEntity::TrialSpawner(_)) => { + self.tick_trial_spawner(pos)?; + trial_spawners.push(pos); + } + Some(BlockEntity::Vault(_)) => self.tick_vault(pos)?, + Some(BlockEntity::Beehive(_)) => self.tick_beehive(pos), + Some(BlockEntity::Furnace(_)) => self.tick_furnace(pos)?, + _ => {} + } + } + self.update_song_volumes(); + self.scan_for_hearts(); + // The client ticks (particles, sounds, the turning mob) are for a + // window; a dedicated or integrated server has none. + if self.options.dedicated.is_none() { + self.client_tick_spawners(&spawners); + for key in trial_spawners { + self.client_tick_trial_spawner(key); + } + } + Ok(()) + } + /// `BlockState.getTicker` of every state, for the block entities ticked + /// here. A creaking heart keeps its slot while uprooted (see + /// `tick_creaking_heart`). + fn ticking_states(&self) -> Vec { + let registry = self.pack.assets.registry; + (0..registry.len()) + .map(|i| { + let state = BlockStateId(i as u32); + let name: &str = &self.res.facts.get(state).name; + match name { + "minecraft:hopper" + | "minecraft:crafter" + | "minecraft:beacon" + | "minecraft:creaking_heart" + | "minecraft:spawner" + | "minecraft:trial_spawner" + | "minecraft:vault" + | "minecraft:beehive" + | "minecraft:bee_nest" => Ticking::Yes, + "minecraft:jukebox" => { + let record = registry + .state(state) + .and_then(|s| s.properties.get("has_record")) + .is_some_and(|v| v == "true"); + if record { Ticking::Yes } else { Ticking::Idle } + } + n if FurnaceKind::from_block(n).is_some() => Ticking::Yes, + _ => Ticking::No, + } + }) + .collect() + } + /// `ServerLevel.shouldTickBlocksAt`: chunks within the simulation + /// distance plus one (`DistanceManager.inBlockTickingRange`, Chebyshev + /// in chunks) of the player or a guest. With nobody there, a dedicated + /// server ticks none; the game alone (no player yet, headless fixtures) + /// ticks every chunk. + fn block_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { + let d = self.settings.simulation_distance.max(2) + 1; + let mut centres: Vec<(i32, i32)> = self.streaming.extra.iter().map(|&(c, _)| c).collect(); + if let Some(p) = &self.player { + centres.push(( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + )); + } + let everywhere = centres.is_empty() && self.options.dedicated.is_none(); + move |x, z| { + everywhere + || centres + .iter() + .any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d) + } + } + /// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and + /// its block's `lit` following it. + fn tick_furnace(&mut self, pos: Pos) -> Result<()> { + let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) else { + return Ok(()); + }; + let Some(lit) = f.tick(&self.res.recipes, &self.res.items, &self.res.providers) else { + return Ok(()); + }; + let state = self.world.block(pos.0, pos.1, pos.2); + if let Some(mut s) = self.pack.assets.registry.state(state).cloned() + && s.properties.contains_key("lit") + { + s.properties.insert("lit".into(), lit.to_string()); + if let Ok(id) = self.pack.assets.registry.resolve(&s) { + self.world.set(pos.0, pos.1, pos.2, id)?; + } + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index a5a609cac..8f2cad5f5 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -2,7 +2,7 @@ //! paddling controls, collisions, riding (`positionRider`, `clampRotation`, //! dismounting), `BoatItem` placement, `VehicleEntity.hurtServer` breaking, //! saving and `AbstractBoatRenderer` with animated paddles. -use super::{Game, Keys, view_vector}; +use super::{Game, Keys, entity_culling::at, view_vector}; use horizon_client::{ blocks::Fluid, collisions::SceneCollisions, @@ -700,8 +700,19 @@ impl Game<'_> { /// AbstractBoatRenderer. pub(super) fn boat_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; + let range = super::entity_culling::default_range( + glam::DVec3::new(WIDTH, HEIGHT, WIDTH), + self.settings.entity_distance, + ); for b in &self.boats { let entity_start = out.len(); + // EntityRenderer.shouldRender. + let (previous, position) = (at(b.previous), at(b.position)); + if !self.standing_entity_in_view( + camera, previous, position, alpha, WIDTH, HEIGHT, range, 0.0, + ) { + continue; + } let models = if b.chest { &self.boat_models.chest_models } else { diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index bcf6426e1..cb8a3a0b5 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -10,6 +10,18 @@ use horizon_client::{ text::{ClickEvent, Style, Text}, }; use std::collections::BTreeMap; + +/// The tree the chat parses and completes with: a server's, once it has +/// sent one (ClientPacketListener.commands), else the game's own. +fn chat_tree<'a>( + remote: &'a Option, + mods: &'a super::mods::ModsState, +) -> &'a horizon_client::command::Dispatcher { + match remote.as_ref().and_then(|r| r.commands.as_ref()) { + Some(tree) => tree, + None => mods.dispatcher(), + } +} use winit::{ event::KeyEvent, keyboard::{KeyCode, PhysicalKey}, @@ -378,6 +390,10 @@ impl Game<'_> { /// The block the player is looking at, for coordinate suggestions. fn refresh_dynamic_registries(&mut self) { self.ui.registries.target_block = self.pick().map(|h| h.pos); + // ClientPacketListener.getOnlinePlayerNames on a server. + if let Some(names) = self.remote_online_names() { + self.ui.registries.players = names; + } } pub(super) fn open_chat(&mut self, initial: &str) { if self.player.is_none() { @@ -391,7 +407,7 @@ impl Game<'_> { let b = HudBatch::new(size); let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; let mut screen = ChatScreen::new( @@ -449,7 +465,7 @@ impl Game<'_> { if let Some(shortcut) = self.edit_shortcut(event) { let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -495,7 +511,7 @@ impl Game<'_> { }; let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; match screen.key(&m, &c, &self.ui.chat.recent, key, shift, ctrl) { @@ -517,11 +533,28 @@ impl Game<'_> { } } } + /// The server's completions for an `ask_server` request + /// (ClientPacketListener.handleCommandSuggestions). + pub(super) fn chat_server_suggestions( + &mut self, + id: i32, + range: (usize, usize), + list: Vec<(String, Option)>, + ) { + let m = Measure(&self.atlas.font); + let c = Commands { + dispatcher: chat_tree(&self.remote, &self.mods), + registries: &self.ui.registries, + }; + if let Some(screen) = self.ui.chat_screen.as_mut() { + screen.server_suggestions(&m, &c, id, range, list); + } + } /// Text typed into the chat box (control socket `chat`). pub(super) fn chat_type(&mut self, text: &str) { let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -531,6 +564,11 @@ impl Game<'_> { /// ChatScreen.handleChatInput: history, then a command or a chat line. pub(super) fn handle_chat_input(&mut self, message: &str) { self.ui.chat.add_recent(message); + // On a server (single player's own included) the server runs it. + if self.remote.is_some() { + self.send_chat(message); + return; + } if let Some(command) = message.strip_prefix('/') { self.run_command(command); } else { @@ -572,7 +610,7 @@ impl Game<'_> { }); let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; if let Some(screen) = self.ui.chat_screen.as_mut() { @@ -617,7 +655,7 @@ impl Game<'_> { }; let m = Measure(&self.atlas.font); let c = Commands { - dispatcher: self.mods.dispatcher(), + dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, }; screen.resize(&m, &c, batch.width as i32, batch.height as i32); diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 5a5fa11c8..717134515 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -357,6 +357,7 @@ impl Game<'_> { silent: false, store: None, elsewhere: false, + level: None, block: Some(pos), }; // performPrefixedCommand: a leading slash is allowed. @@ -598,13 +599,13 @@ impl Game<'_> { if let Ok(id) = registry.resolve(&wanted) && wanted != *current { - let entity = self.world.block_entities.remove(&pos); + let entity = self.world.block_entities.take(&pos); let at = BlockPos::new(pos.0, pos.1, pos.2); self.with_level(|b, level, ticks| { b.set_block(level, ticks, at, id, flags::UPDATE_CLIENTS) }); if let Some(entity) = entity { - self.world.block_entities.insert(pos, entity); + self.world.block_entities.put(pos, entity); } let _ = self.process_level_events(); } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 6c4817f63..575f5c93e 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -1,5 +1,6 @@ //! Command execution (the `execute` side of each vanilla command class): //! entity selectors resolved against the game, vanilla feedback and errors. +mod admin; pub(super) mod compute; mod data; mod effects; @@ -160,8 +161,70 @@ impl Game<'_> { return; } if self.ui.rules.bool("send_command_feedback") { - self.system_message(message); + self.system_message(message.clone()); } + self.broadcast_to_admins(message); + } + /// CommandSourceStack.broadcastToAdmins (`sendSuccess` with `broadcast`) + /// for a guest's command, the host's in a world open to LAN and the + /// dedicated server console's when `broadcast-console-to-ops` is on: + /// `[name: message]`, gray and italic, for the other operators when + /// `send_command_feedback`, and for a player's command on a dedicated + /// server the console when `log_admin_commands`. Queued while the + /// command runs; `send_admin_feedback` sends it. + pub(super) fn broadcast_to_admins(&mut self, message: Text) { + let informs = match self.console_broadcast { + Some(broadcast) => broadcast, + // While a guest acts the host's LanHost is out of `self.lan`. + None => self.lan_acting.is_some() || self.lan.is_some(), + }; + if !informs + || message + .translation_key() + .is_some_and(|k| admin::QUIET.contains(&k)) + { + return; + } + let ops = self.ui.rules.bool("send_command_feedback"); + // MinecraftServer.sendSystemMessage, unless the server is the source. + let console = self.console_broadcast.is_none() + && self.lan_acting.is_some() + && self.options.dedicated.is_some() + && self.ui.rules.bool("log_admin_commands"); + if !ops && !console { + return; + } + // getDisplayName: the entity the command runs as (`execute as`), or + // the server's own source, "Server". + let who = match self.command_source.and_then(|s| s.entity) { + Some(entity) => self.target_name(entity), + None if self.console_broadcast.is_some() => Text::literal("Server".to_owned()), + None => self.player_display_name(), + }; + let line = Text::translate("chat.type.admin", &[who, message]) + .with_color(text::GRAY) + .italic(); + self.admin_feedback.push((line, ops, console)); + } + /// Player.getDisplayName: the name (team-formatted), suggesting a + /// `/tell`, showing the player on hover, inserting the name. + fn player_display_name(&self) -> Text { + let name = self.acting_player_name().to_owned(); + let Some(uuid) = self.lan_acting_uuid else { + return self.target_name(Target::Player); + }; + self.target_name(Target::Player).with_component_fields(vec![ + ( + "click_event".into(), + serde_json::json!({"action": "suggest_command", "command": format!("/tell {name} ")}), + ), + ( + "hover_event".into(), + serde_json::json!({"action": "show_entity", "id": "minecraft:player", + "uuid": horizon_protocol::crypto::uuid_string(uuid), "name": name}), + ), + ("insertion".into(), name.into()), + ]) } fn source_position(&self) -> [f64; 3] { if let Some(s) = &self.command_source { @@ -321,12 +384,16 @@ impl Game<'_> { .map_or_else(String::new, |o| o.kind.clone()), } } + /// The name of the player the game acts for: a guest's own while their + /// command or action runs (`Player.getName`). + pub(super) fn acting_player_name(&self) -> &str { + self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME) + } /// Entity.getDisplayName. pub(super) fn target_name(&self, t: Target) -> Text { match t { Target::Player => { - // A guest's commands name the guest. - let name = self.lan_acting_name.as_deref().unwrap_or(PLAYER_NAME); + let name = self.acting_player_name(); match self.score.board.players_team(name) { // PlayerTeam.formatNameForTeam. Some(team) => team.formatted_name(Text::literal(name)), @@ -767,7 +834,7 @@ impl Game<'_> { } self.feedback(Text::translate( "commands.gamemode.success.other", - &[Text::literal(PLAYER_NAME), mode_name], + &[Text::literal(self.acting_player_name()), mode_name], )); } } @@ -922,7 +989,7 @@ impl Game<'_> { &[ Text::literal(count.to_string()), name, - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], ) } else { @@ -1089,7 +1156,23 @@ impl Game<'_> { (-(dy.atan2(horizontal).to_degrees())) as f32, ]); } + // `execute in` another dimension: a server's player moves to that + // level (ServerPlayer.teleport into another level), after the command. + let level = self + .command_source + .and_then(|s| s.level) + .filter(|d| *d != self.dim && self.options.dedicated.is_some()); for &t in &targets { + if let (Some(dim), Target::Player, Some(conn)) = (level, t, self.lan_acting) { + self.level_teleports + .push(super::server_travel::LevelTeleport { + conn, + dim, + at: pos, + rotation, + }); + continue; + } self.teleport_to(t, pos, rotation); } let [x, y, z] = pos.map(|v| Text::literal(format_double(v))); @@ -1418,7 +1501,9 @@ impl Game<'_> { return Err(err("commands.summon.failed", &[])); } "experience_orb" => { + self.next_entity += 1; self.orbs.push(horizon_client::entities::ExperienceOrb { + id: self.next_entity, position: Vec3::new(pos[0], pos[1], pos[2]), previous: Vec3::new(pos[0], pos[1], pos[2]), velocity: Vec3::new(0.0, 0.0, 0.0), @@ -1444,7 +1529,13 @@ impl Game<'_> { self.carts.push(cart); name = Text::translate(&format!("entity.minecraft.{k}"), &[]); } - _ => return Err(err("commands.summon.failed", &[])), + // SummonCommand.createEntity: any other type from an empty compound. + _ => { + let Some(target) = self.summon_with_nbt(&kind, pos, "{}")? else { + return Err(err("commands.summon.failed", &[])); + }; + name = self.target_name(target); + } } } self.feedback(Text::translate("commands.summon.success", &[name])); @@ -1794,7 +1885,7 @@ impl Game<'_> { ), _ => None, }; - let player = Text::literal(PLAYER_NAME); + let player = Text::literal(self.acting_player_name()); let players = targets.len(); if let (Some(i), Some(Arg::Str(criterion))) = (index, ctx.get("criterion")) { let a = &tree.list[i]; @@ -1904,7 +1995,10 @@ impl Game<'_> { }; self.system_message(Text::translate( &format!("commands.experience.query.{unit}"), - &[Text::literal(PLAYER_NAME), Text::literal(value.to_string())], + &[ + Text::literal(self.acting_player_name()), + Text::literal(value.to_string()), + ], )); return Ok(value); } @@ -1941,7 +2035,7 @@ impl Game<'_> { &key, &[ Text::literal(amount.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(targets.len() as i32) @@ -2248,7 +2342,7 @@ impl Game<'_> { return Err(if targets.len() == 1 { CommandError::new(Text::translate( "clear.failed.single", - &[Text::literal(PLAYER_NAME)], + &[Text::literal(self.acting_player_name())], )) } else { err("clear.failed.multiple", &[&targets.len()]) @@ -2259,7 +2353,7 @@ impl Game<'_> { &format!("commands.clear.{kind}.single"), &[ Text::literal(removed.to_string()), - Text::literal(PLAYER_NAME), + Text::literal(self.acting_player_name()), ], )); Ok(removed) @@ -2312,7 +2406,7 @@ impl Game<'_> { }; let from = self.source_position().map(|v| v.floor() as i32); const RANGE: i32 = 256; - let mut cache: std::collections::HashMap> = + let mut cache: std::collections::HashMap> = std::collections::HashMap::new(); let mut best: Option<(i64, [i32; 3], &'static str)> = None; let (cx0, cz0) = ((from[0] - RANGE) >> 4, (from[2] - RANGE) >> 4); @@ -2323,15 +2417,12 @@ impl Game<'_> { continue; }; for (i, section) in chunk.sections.iter().enumerate() { - let mut wanted_state = |v: u32| { - let state = v as u16; + let mut wanted_state = |state: u32| { cache .entry(state) .or_insert_with(|| { - self.poi_type(horizon_world::registry::BlockStateId(u32::from( - state, - ))) - .filter(|t| wanted.iter().any(|w| w == t)) + self.poi_type(horizon_world::registry::BlockStateId(state)) + .filter(|t| wanted.iter().any(|w| w == t)) }) .is_some() }; @@ -2513,7 +2604,7 @@ impl Game<'_> { let name = match self.command_source.map(|s| s.entity) { Some(Some(t)) => self.target_name(t), Some(None) => Text::literal("Server"), - None => Text::literal(PLAYER_NAME), + None => Text::literal(self.acting_player_name()), }; let line = match id { "say" => Text::translate("chat.type.announcement", &[name, message]), @@ -2523,14 +2614,14 @@ impl Game<'_> { // Whispering to yourself: the incoming and outgoing lines. let out = Text::translate( "commands.message.display.outgoing", - &[Text::literal(PLAYER_NAME), message.clone()], + &[Text::literal(self.acting_player_name()), message.clone()], ) .with_color(text::GRAY) .italic(); self.system_message(out); Text::translate( "commands.message.display.incoming", - &[Text::literal(PLAYER_NAME), message], + &[Text::literal(self.acting_player_name()), message], ) .with_color(text::GRAY) .italic() diff --git a/crates/horizon-client/src/game/commands/admin.rs b/crates/horizon-client/src/game/commands/admin.rs new file mode 100644 index 000000000..1a5115f4d --- /dev/null +++ b/crates/horizon-client/src/game/commands/admin.rs @@ -0,0 +1,92 @@ +//! Which command feedback vanilla tells the other operators and the console +//! about (`CommandSourceStack.sendSuccess`'s `broadcast`). + +/// The replies vanilla sends with `broadcast` false: queries and lists, which +/// only the player who asked sees. Every other success message is broadcast. +pub(super) const QUIET: &[&str] = &[ + "commands.attribute.base_value.get.success", + "commands.attribute.base_value.reset.success", + "commands.attribute.base_value.set.success", + "commands.attribute.modifier.add.success", + "commands.attribute.modifier.remove.success", + "commands.attribute.modifier.value.get.success", + "commands.attribute.value.get.success", + "commands.banlist.entry", + "commands.banlist.list", + "commands.banlist.none", + "commands.bossbar.list.bars.none", + "commands.bossbar.list.bars.some", + "commands.data.block.get", + "commands.data.block.query", + "commands.data.entity.get", + "commands.data.entity.query", + "commands.data.storage.get", + "commands.data.storage.query", + "commands.datapack.list.available.none", + "commands.datapack.list.available.success", + "commands.datapack.list.enabled.none", + "commands.datapack.list.enabled.success", + "commands.difficulty.query", + "commands.execute.conditional.pass", + "commands.execute.conditional.pass_count", + "commands.experience.query.levels", + "commands.experience.query.points", + "commands.fetchprofile.copy_component", + "commands.fetchprofile.copy_text", + "commands.fetchprofile.give_item", + "commands.fetchprofile.summon_mannequin", + "commands.forceload.list.multiple", + "commands.forceload.list.single", + "commands.forceload.query.success", + "commands.gamerule.query", + "commands.jfr.started", + "commands.jfr.stopped", + "commands.list.players", + "commands.locate.biome.success", + "commands.locate.poi.success", + "commands.locate.structure.success", + "commands.perf.started", + "commands.perf.stopped", + "commands.posteffect.list.empty", + "commands.posteffect.list.success", + "commands.random.reset.all.success", + "commands.random.reset.success", + "commands.random.sample.success", + "commands.save.saving", + "commands.scoreboard.objectives.list.empty", + "commands.scoreboard.objectives.list.success", + "commands.scoreboard.players.get.success", + "commands.scoreboard.players.list.empty", + "commands.scoreboard.players.list.entity.empty", + "commands.scoreboard.players.list.entity.entry", + "commands.scoreboard.players.list.entity.success", + "commands.scoreboard.players.list.success", + "commands.seed.success", + "commands.spectate.success.started", + "commands.spectate.success.stopped", + "commands.team.list.members.empty", + "commands.team.list.members.success", + "commands.team.list.teams.empty", + "commands.team.list.teams.success", + "commands.team.option.prefix.success", + "commands.team.option.suffix.success", + "commands.tick.query.percentiles", + "commands.tick.query.rate.running", + "commands.tick.query.rate.sprinting", + "commands.tick.status.frozen", + "commands.tick.status.lagging", + "commands.tick.status.running", + "commands.tick.status.sprinting", + "commands.time.query.absolute", + "commands.time.query.gametime", + "commands.time.query.timeline", + "commands.time.query.timeline.repetitions", + "commands.waypoint.list.empty", + "commands.waypoint.list.success", + "commands.waypoint.modify.color", + "commands.waypoint.modify.color.reset", + "commands.waypoint.modify.style", + "commands.whitelist.list", + "commands.whitelist.none", + "commands.worldborder.get", +]; diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 3e04f7179..86726fed9 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -86,7 +86,7 @@ impl Game<'_> { Target::Player => { let mut instance = EffectInstance::new(effect.id, duration, amplifier); instance.visible = particles; - self.potions.effects.add(instance) + self.add_player_effect(instance) } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { @@ -134,11 +134,13 @@ impl Game<'_> { (Target::Player, None) => { let any = !self.potions.effects.list.is_empty(); self.potions.effects.clear(); + self.apply_effect_status(); any } (Target::Player, Some(e)) => { let before = self.potions.effects.list.len(); self.potions.effects.list.retain(|x| x.id != e.id); + self.apply_effect_status(); self.potions.effects.list.len() != before } (Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) { diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 1fa67c8b6..01488db2c 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -26,6 +26,9 @@ pub(in crate::game) struct Source { /// `execute in` another dimension than the one Horizon has loaded: none /// of its chunks are loaded. pub elsewhere: bool, + /// The dimension `execute in` named, if any: a server teleports its + /// players there (`TeleportCommand` into the source's level). + pub level: Option, /// The command block whose output this source is /// (`BaseCommandBlock.CloseableCommandBlockSource`). pub block: Option<(i32, i32, i32)>, @@ -77,6 +80,7 @@ impl Game<'_> { silent: false, store: None, elsewhere: false, + level: None, block: None, } } @@ -90,6 +94,7 @@ impl Game<'_> { silent: true, store: None, elsewhere: false, + level: None, block: None, } } @@ -441,6 +446,7 @@ impl Game<'_> { pos: self.target_position(t)?, rot: self.target_rotation(t), elsewhere: false, + level: None, ..s }) }) @@ -544,6 +550,7 @@ impl Game<'_> { } vec![Source { elsewhere: dim != self.dim.id(), + level: Some(super::super::Dim::from_id(dim)), ..s }] } diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index da8485849..dead07d71 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -1,6 +1,7 @@ //! `/tellraw` (TellRawCommand) and `/title` (TitleCommand). use super::{Arg, Context, Game, R, Target, err}; -use horizon_client::text::Text; +use horizon_client::{hud_overlays::Titles, lan::data::component_nbt, text::Text}; +use horizon_protocol::packets::play::{self, Clientbound as C}; impl Game<'_> { /// ComponentArgument with selectors resolved for the source @@ -153,30 +154,45 @@ impl Game<'_> { let name = self.target_name(Target::Player); let single = n == 1; let key = if ctx.has("clear") { - self.titles.clear(); + self.titles_or_packet(Titles::clear, C::ClearTitles(play::Bool1 { value: false })); "cleared" } else if ctx.has("reset") { - self.titles.clear(); - self.titles.reset_times(); + self.titles_or_packet( + |t| { + t.clear(); + t.reset_times(); + }, + C::ClearTitles(play::Bool1 { value: true }), + ); "reset" } else if ctx.has("times") { let get = |k: &str| match ctx.get(k) { Some(Arg::Int(v)) => *v, _ => -1, }; - self.titles - .set_times(get("fadeIn"), get("stay"), get("fadeOut")); + let (fade_in, stay, fade_out) = (get("fadeIn"), get("stay"), get("fadeOut")); + self.titles_or_packet( + |t| t.set_times(fade_in, stay, fade_out), + C::SetTitlesAnimation(play::TitlesAnimation { + fade_in, + stay, + fade_out, + }), + ); "times" } else { let text = self.component_arg(ctx, "title")?; + let sent = play::Text { + text: component_nbt(&text.component()), + }; if ctx.has("subtitle") { - self.titles.set_subtitle(text); + self.titles_or_packet(|t| t.set_subtitle(text), C::SetSubtitleText(sent)); "show.subtitle" } else if ctx.has("actionbar") { - self.titles.set_overlay(text, false); + self.titles_or_packet(|t| t.set_overlay(text, false), C::SetActionBarText(sent)); "show.actionbar" } else { - self.titles.set_title(text); + self.titles_or_packet(|t| t.set_title(text), C::SetTitleText(sent)); "show.title" } }; @@ -191,4 +207,13 @@ impl Game<'_> { self.feedback(message); Ok(n as i32) } + /// The player the title is for: the guest acting now is sent the packet + /// (TitleCommand's `connection.send`), the window's own player shows it. + fn titles_or_packet(&mut self, local: impl FnOnce(&mut Titles), packet: C) { + if self.lan_acting.is_some() { + self.guest_packets.push(packet); + } else { + local(&mut self.titles); + } + } } diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 578153247..2055798f4 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -1,7 +1,6 @@ //! `/recipe`, `/damage`, `/rotate`, `/swing`, `/playsound`, `/stopsound`, //! `/particle`, `/attribute`, `/ride` and `/spreadplayers`. use super::{Arg, Context, Game, R, Target, err}; -use crate::game::chat::PLAYER_NAME; use horizon_client::{ mobs::{Damage, DamageKind, Who}, scoreboard_cmd::{Holder, Tracker}, @@ -313,7 +312,7 @@ impl Game<'_> { (pos, volume) }; self.audio.play_on(source, &sound, Some(at), v, pitch); - tracker.mark(&holder(Text::literal(PLAYER_NAME))); + tracker.mark(&holder(Text::literal(self.acting_player_name()))); } let name = Text::literal(sound.clone()); let (message, total) = tracker.message( diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index cf7510065..6827d49c9 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -173,6 +173,16 @@ impl Game<'_> { .chain(super::pad::HELP) .collect::>() }))), "setblock" | "fill" | "particle" | "signedit" => self.render_command(&words), + "section-draws" => { + let r = self.renderer.as_mut().ok_or("no renderer")?; + match words.get(1).copied() { + None => {} + Some("flat") => r.set_flat_draws(true)?, + Some("indirect") => r.set_flat_draws(false)?, + Some(other) => return Err(format!("unknown section draw mode {other}").into()), + } + Ok(Some(json!({ "ok": true, "flat": r.flat_draws() }))) + } "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "pad" => Ok(Some(self.pad_command(&words)?)), @@ -606,18 +616,6 @@ impl Game<'_> { fn control_key_down(&mut self, key: KeyCode) -> Result<()> { self.physical_keys.insert(key); - // A server's chat input takes the keys first, as remote_chat_key does. - if self.remote_chat_open() { - use winit::keyboard::NamedKey; - let named = match key { - KeyCode::Escape => Some(NamedKey::Escape), - KeyCode::Enter | KeyCode::NumpadEnter => Some(NamedKey::Enter), - KeyCode::Backspace => Some(NamedKey::Backspace), - _ => None, - }; - self.remote_chat_input(named, None); - return Ok(()); - } if self.screen == Screen::Chat { self.chat_key_code(key, None); return Ok(()); @@ -684,6 +682,8 @@ impl Game<'_> { "size": [r.config.width, r.config.height], "present_mode": format!("{:?}", r.config.present_mode), "drawn_sections": r.drawn_sections, + "section_draws": r.section_draws, + "section_draw_calls": r.section_draw_calls, "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), "arena_bytes": arena_bytes, @@ -758,6 +758,10 @@ impl Game<'_> { .map(|e| self.shown_name_tags(glam::DVec3::from_array(e))), }); status["physical_keys"] = json!(physical_keys); + // Boats, minecarts, armor stands, item frames and paintings. + status["objects"] = json!(self.objects_status()); + // Primed TNT, falling blocks, projectiles, tridents and end crystals. + status["projectiles"] = json!(self.projectiles_status()); status } } diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 1caa419ff..1df29a3e4 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -164,7 +164,7 @@ impl Game<'_> { return; } let key = (home[0], home[1], home[2]); - let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) else { return; }; @@ -173,7 +173,7 @@ impl Game<'_> { }); self.world .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + .put(key, BlockEntity::CreakingHeart(heart)); } /// `Creaking.tearDown`: the crumble particles. pub(super) fn creaking_tear_down(&mut self, center: [f64; 3], spread: [f64; 3]) { @@ -220,7 +220,7 @@ impl Game<'_> { /// death and a natural heart drops experience. pub(super) fn creaking_heart_broken(&mut self, pos: [i32; 3]) { let key = (pos[0], pos[1], pos[2]); - let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.remove(&key) + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) else { return; }; @@ -248,43 +248,35 @@ impl Game<'_> { } self.world .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + .put(key, BlockEntity::CreakingHeart(heart)); } - /// `CreakingHeartBlockEntity.serverTick` for every heart. - pub(super) fn tick_creaking_hearts(&mut self) -> Result<()> { - let keys: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::CreakingHeart(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let Some(BlockEntity::CreakingHeart(mut heart)) = - self.world.block_entities.remove(&key) - else { - continue; - }; - let state = self.world.block(key.0, key.1, key.2); - if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { - // The block is gone: preRemoveSideEffects. - self.with_heart(key, &mut heart, |h, _, _, host, out| { - creaking_heart::remove_protector(h, host, false, out); - })?; - continue; - } - // getTicker: none once uprooted. - if self.heart_state_name(state) != "uprooted" { - let pos = [key.0, key.1, key.2]; - self.with_heart(key, &mut heart, |h, w, lr, host, out| { - creaking_heart::server_tick(h, pos, w, lr, host, out); - })?; - } - self.world - .block_entities - .insert(key, BlockEntity::CreakingHeart(heart)); + /// `CreakingHeartBlockEntity.serverTick` of the heart at `key`. Its slot + /// stays while uprooted, so that a heart whose block went away is still + /// found here and lets go of its protector. + pub(super) fn tick_creaking_heart(&mut self, key: Pos) -> Result<()> { + let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) + else { + return Ok(()); + }; + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { + // The block is gone: preRemoveSideEffects. + self.world.block_entities.forget(&key); + self.with_heart(key, &mut heart, |h, _, _, host, out| { + creaking_heart::remove_protector(h, host, false, out); + })?; + return Ok(()); } - self.scan_for_hearts(); + // getTicker: none once uprooted. + if self.heart_state_name(state) != "uprooted" { + let pos = [key.0, key.1, key.2]; + self.with_heart(key, &mut heart, |h, w, lr, host, out| { + creaking_heart::server_tick(h, pos, w, lr, host, out); + })?; + } + self.world + .block_entities + .put(key, BlockEntity::CreakingHeart(heart)); Ok(()) } /// `ServerLevel.isSpawningMonsters`. @@ -295,7 +287,7 @@ impl Game<'_> { } /// Hearts that came with generated or loaded chunks get their block /// entity (`newBlockEntity`) the first time their chunk is seen. - fn scan_for_hearts(&mut self) { + pub(super) fn scan_for_hearts(&mut self) { let Some(heart) = self .pack .assets @@ -327,13 +319,16 @@ impl Game<'_> { } let hearts = &self.creaking.hearts; let _ = heart; + let is_heart = |id: u32| hearts.get(id as usize).copied().unwrap_or(false); for (si, section) in chunk.sections.iter().enumerate() { - if section.is_uniform(0) { + // Only a section whose palette holds a heart state can have + // one: the others are skipped without reading their 4,096 blocks. + if !section.blocks.maybe_has(is_heart) { continue; } for i in 0..4096 { let id = section.get(i); - if !hearts.get(usize::from(id)).copied().unwrap_or(false) { + if !is_heart(id) { continue; } let (lx, lz, ly) = ((i & 15) as i32, ((i >> 4) & 15) as i32, (i >> 8) as i32); @@ -344,8 +339,7 @@ impl Game<'_> { ); self.world .block_entities - .entry(pos) - .or_insert_with(|| BlockEntity::CreakingHeart(Box::default())); + .get_or_insert_with(pos, || BlockEntity::CreakingHeart(Box::default())); } } } @@ -362,3 +356,11 @@ pub(super) struct CreakingState { /// Which block states are creaking hearts, by state id. hearts: Vec, } + +impl CreakingState { + /// Exchange the chunks scanned for creaking hearts with another level's + /// (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.scanned, &mut other.scanned); + } +} diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 076c2fbef..3ef399e62 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -196,6 +196,7 @@ impl Game<'_> { hero: self.potions.effects.get("hero_of_the_village").is_some(), uuid: self.level.player_uuid.unwrap_or_default(), allies: std::sync::Arc::new(self.player_allies()), + remote: false, }) } /// Biome facts at a position for finalizeSpawn and variant rules. @@ -1358,25 +1359,52 @@ impl Game<'_> { /// mining fatigue III for five minutes unless a stronger or longer one /// is on, with the curse sound and the elder's apparition. fn elder_curse(&mut self, at: [f64; 3]) { + let mut cursed = Vec::new(); + self.for_each_player(|g| { + if g.elder_curse_player(at) { + cursed.push(g.lan_acting); + } + }); + // A guest's client shows the apparition and plays the curse itself + // (ClientboundGameEventPacket.GUARDIAN_ELDER_EFFECT). + if let Some(host) = self.lan.as_ref() { + for conn in cursed.into_iter().flatten() { + host.hub.send_to( + conn, + &horizon_protocol::packets::play::Clientbound::GameEvent( + horizon_protocol::packets::play::GameEvent { + event: horizon_client::lan::hub::game_event::GUARDIAN_ELDER_EFFECT, + param: 1.0, + }, + ), + ); + } + } + } + /// The curse on the player in place; whether it took. + fn elder_curse_player(&mut self, at: [f64; 3]) -> bool { if self.creative || self.spectator() { - return; + return false; } let Some(p) = self.player.as_ref() else { - return; + return false; }; let d = p.position.subtract(Vec3::new(at[0], at[1], at[2])); if d.x * d.x + d.y * d.y + d.z * d.z >= 2500.0 || p.health.dead_or_dying() { - return; + return false; } let active = self.potions.effects.get("minecraft:mining_fatigue"); if active.is_some_and(|e| e.amplifier >= 2 && e.duration >= 1200) { - return; + return false; } let at = [p.position.x, p.position.y, p.position.z]; self.give_player_effect("minecraft:mining_fatigue", 6000, 2); - self.audio - .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); - self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if self.lan_acting.is_none() { + self.audio + .play("minecraft:entity.elder_guardian.curse", Some(at), 1.0, 1.0); + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + } + true } /// Damage of a given type to the player from a point. pub(super) fn mob_hits_player_kind(&mut self, amount: f32, from: [f64; 3], kind: &str) { @@ -2253,6 +2281,10 @@ impl Game<'_> { return Ok(true); } if self.interact_sulfur_cube(index, &item) { + if let Some(stack) = &held { + let target = self.mob_entity(&self.mobs[index]); + self.trigger_item_entity("minecraft:player_interacted_with_entity", stack, &target); + } self.swing_arm(); return Ok(true); } @@ -2802,6 +2834,17 @@ impl Game<'_> { if mob.fire_ticks > 0 || matches!(mob.species(), Species::Blaze | Species::MagmaCube) { packed = (15 * 16) | ((15 * 16) << 8); } + if mob.species() == Species::SulfurCube + && !horizon_client::mobs::trader::is_invisible(mob) + { + self.sulfur_cube_body_geometry( + mob, + alpha as f32, + horizon_client::mobs::render::base_transform(mob, alpha as f32, camera), + packed, + out, + ); + } // Other players on a server: PlayerRenderer's HumanoidArmorLayer. let armor = if &*mob.kind.id == "minecraft:player" { self.worn_armor_layers(mob) diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 36761a85e..1de6669e7 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -88,8 +88,7 @@ impl Game<'_> { || self.book.is_some() || (self.screen == Screen::Creative && self.creative_screen.tab().search) || self.recipe_search_focused() - || self.station_typing() - || self.remote_chat_open(); + || self.station_typing(); // Container screens use Escape, the inventory key and the hotbar and // drop keys first; any other screen closes on Escape. let screen_key = match self.screen { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 9c4b41db0..8a8ed63f9 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -13,7 +13,9 @@ use horizon_client::{ server::{ eula, java_properties::now_millis, + profiles, properties::{GAME_MODES, ServerProperties, SystemEntropy}, + user_cache::UserCache, user_lists::{ BanEntry, BanList, IpBanList, NameAndId, OpEntry, OpList, WhiteEntry, WhiteList, format_date, @@ -57,6 +59,18 @@ struct Setup { started: Instant, } static SETUP: OnceLock>> = OnceLock::new(); +/// usercache.json (Services.nameToIdCache): used by the server thread only. +static USER_CACHE: Mutex> = Mutex::new(None); + +/// PlayerList.placeNewPlayer: a player who joined is cached (and the file saved). +pub(super) fn player_joined(id: u128, name: &str) { + if let Some(cache) = USER_CACHE.lock().unwrap().as_mut() { + cache.add(NameAndId { + id, + name: name.to_owned(), + }); + } +} /// Log4j's console pattern: `[HH:mm:ss] [thread/LEVEL]: message`. pub(super) fn log(level: &str, message: &str) { @@ -276,6 +290,78 @@ impl Lists { } } +/// The world presets of 26.3's `worldgen/world_preset`. +const WORLD_PRESETS: [&str; 6] = [ + "minecraft:normal", + "minecraft:flat", + "minecraft:large_biomes", + "minecraft:amplified", + "minecraft:single_biome_surface", + "minecraft:debug_all_block_states", +]; + +/// Identifier.tryParse: `namespace:path`, or a path in `minecraft`. +fn parse_identifier(text: &str) -> Option { + let (namespace, path) = text.split_once(':').unwrap_or(("minecraft", text)); + let valid = |s: &str, extra: &[char]| { + s.chars() + .all(|c| matches!(c, 'a'..='z' | '0'..='9' | '_' | '.' | '-') || extra.contains(&c)) + }; + (valid(namespace, &[]) && valid(path, &['/'])).then(|| format!("{namespace}:{path}")) +} + +impl Game<'_> { + /// DedicatedServerProperties.createDimensions for a world that doesn't + /// exist yet: `level-type`'s preset, a flat world's `generator-settings` + /// and `generate-structures`, written before the world opens so that + /// streaming reads them. Horizon generates the normal and flat presets. + fn write_world_gen(&self, dir: &std::path::Path, props: &ServerProperties) -> Result<()> { + let level_type = &props.level_type; + let preset = parse_identifier(level_type) + .filter(|id| WORLD_PRESETS.contains(&id.as_str())) + .unwrap_or_else(|| { + log_from( + "Worker-Main-1", + "WARN", + &format!( + "Failed to parse level-type {level_type}, defaulting to minecraft:normal" + ), + ); + "minecraft:normal".to_owned() + }); + let flat = preset == "minecraft:flat"; + if !flat && preset != "minecraft:normal" { + log_from( + "Worker-Main-1", + "WARN", + &format!( + "Horizon doesn't generate the {preset} world preset yet: using minecraft:normal" + ), + ); + } + let settings = if flat { + let biomes = &self.res.biomes; + let (settings, errors) = horizon_client::flatgen::settings_from_json( + &props.generator_settings, + |b| self.pack.assets.registry.default_state(b).is_some(), + |b| biomes.get(biomes.id(b)).name == b, + ); + for e in errors { + log_from("Worker-Main-1", "ERROR", &e); + } + settings + } else { + None + }; + let options = horizon_client::save::WorldGen { + flat, + structures: props.generate_structures, + bonus_chest: false, + }; + horizon_client::save::write_world_gen_settings_with(dir, props.seed, options, settings) + } +} + /// PlayerList.BAN_DATE_FORMAT ("yyyy-MM-dd 'at' HH:mm:ss z"), in UTC. fn ban_date(millis: i64) -> String { let s = format_date(millis); @@ -316,8 +402,32 @@ struct ServerState { /// When the last passes of the loop ended, for the tick rate horizon-server shows. ticks: std::collections::VecDeque, paused: bool, + /// `broadcast-console-to-ops`. + broadcast_console: bool, } +/// The dedicated-only commands' replies vanilla sends with `broadcast` +/// (`sendSuccess(..., true)`): the operators hear of them. +const BROADCAST: &[&str] = &[ + "commands.ban.success", + "commands.banip.info", + "commands.banip.success", + "commands.deop.success", + "commands.kick.success", + "commands.op.success", + "commands.pardon.success", + "commands.pardonip.success", + "commands.save.disabled", + "commands.save.enabled", + "commands.save.success", + "commands.stop.stopping", + "commands.whitelist.add.success", + "commands.whitelist.disabled", + "commands.whitelist.enabled", + "commands.whitelist.reloaded", + "commands.whitelist.remove.success", +]; + impl Game<'_> { /// DedicatedServer.initServer and MinecraftServer.runServer. pub(super) fn run_dedicated(&mut self) -> Result<()> { @@ -331,6 +441,13 @@ impl Game<'_> { .get() .and_then(|m| m.lock().unwrap().take()) .ok_or("dedicated server not prepared")?; + // Main's WorldLoader: a new world's dimensions come from + // server.properties before the server starts. + let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); + let new_world = !world_dir.join("level.dat").exists(); + if new_world { + self.write_world_gen(&world_dir, &props)?; + } // The console thread starts first, as in initServer. let (tx, console) = mpsc::channel(); std::thread::Builder::new() @@ -348,6 +465,26 @@ impl Game<'_> { line.clear(); } })?; + // Main: Services.create loads the universe's usercache.json. + let (mut cache, warnings) = UserCache::load(universe.join("usercache.json")); + for warning in warnings { + log_from("main", "WARN", &warning); + } + // DedicatedServer.initServer: names nobody has resolve offline only without authentication. + cache.resolve_offline_users = !props.online_mode; + *USER_CACHE.lock().unwrap() = Some(cache); + // Services.create: the services' public keys, fetched in the + // background (they check players' chat keys). + let secure_chat = Arc::new(horizon_client::lan::SecureChat::new( + props.enforce_secure_profile && props.online_mode, + || { + let discovery = profiles::discovery_url(); + profiles::fetch_profile_key_keys(&discovery).unwrap_or_else(|e| { + ::log::error!("{e}"); + Vec::new() + }) + }, + )); log("INFO", "Starting minecraft server version 26.3"); log("INFO", "Loading properties"); let game_mode = props.game_mode; @@ -403,9 +540,7 @@ impl Game<'_> { lists.enforce_whitelist = props.enforce_whitelist; let lists = Arc::new(Mutex::new(lists)); log("INFO", &format!("Preparing level \"{level_name}\"")); - let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); let folder = world_dir.to_string_lossy().into_owned(); - let new_world = !world_dir.join("level.dat").exists(); self.open_world( &folder, Some(&level_name), @@ -448,8 +583,7 @@ impl Game<'_> { enable_status: props.enable_status, hide_online_players: props.hide_online_players, favicon, - // DedicatedServer.enforceSecureProfile needs online mode. - enforces_secure_chat: false, + secure_chat: Some(secure_chat), accepts_transfers: props.accepts_transfers, announce: false, listen: true, @@ -513,6 +647,7 @@ impl Game<'_> { empty_ticks: 0, ticks: Default::default(), paused: false, + broadcast_console: props.broadcast_console_to_ops, }; let pause_after = props.pause_when_empty_seconds * 20; let idle_timeout = props.player_idle_timeout; @@ -520,7 +655,7 @@ impl Game<'_> { while !state.stop { let tick_start = Instant::now(); while let Ok(line) = state.console.try_recv() { - self.console_command(&mut state, &line); + self.console_line(&mut state, &line); } self.poll_server_control(&mut state); let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len()); @@ -543,18 +678,12 @@ impl Game<'_> { ); self.save_game()?; } - self.update_dedicated_streaming(); - self.update_world(); - if paused { - // MinecraftServer.tickServer: only the connections run. - self.tick_lan(); - } else { - if !state.autosave { - // `save-off`: the periodic save inside the tick is skipped. - self.ticks = self.ticks.max(1); - } - self.tick()?; + if !paused && !state.autosave { + // `save-off`: the periodic save inside the tick is skipped. + self.ticks = self.ticks.max(1); } + // MinecraftServer.tickServer: while paused only the connections run. + self.tick_server(paused)?; if idle_timeout > 0 { self.kick_idle(idle_timeout); } @@ -595,7 +724,13 @@ impl Game<'_> { let center = self .lan .as_ref() - .and_then(|h| h.hub.guests.iter().find(|g| g.placed).map(|g| g.chunk())) + .and_then(|h| { + h.hub + .guests + .iter() + .find(|g| h.hub.here(g)) + .map(|g| g.chunk()) + }) .or_else(|| { self.spawn .map(|s| ((s.x.floor() as i32) >> 4, (s.z.floor() as i32) >> 4)) @@ -641,28 +776,63 @@ impl Game<'_> { host.hub.resend_commands(); } - /// A known player by name: online first, else the offline profile. - fn resolve(&self, name: &str) -> NameAndId { - self.lan - .as_ref() - .and_then(|h| { - h.hub - .guests - .iter() - .find(|g| g.name.eq_ignore_ascii_case(name)) - }) - .map_or_else( - || NameAndId::offline(name), - |g| NameAndId { - id: g.uuid, - name: g.name.clone(), - }, - ) + /// A player on the server, by name. + fn online_player(&self, name: &str) -> Option { + let hub = &self.lan.as_ref()?.hub; + let g = hub + .guests + .iter() + .find(|g| g.name.eq_ignore_ascii_case(name))?; + Some(NameAndId { + id: g.uuid, + name: g.name.clone(), + }) } - /// MinecraftServer.sendSystemMessage: what the console is told. - fn console_reply(&self, text: Text) { + /// GameProfileArgument for a name: the user cache, else the profile + /// service, else (offline) the offline player. None, told to the console: + /// no such player. + fn resolve(&self, name: &str) -> Option { + let found = USER_CACHE.lock().unwrap().as_mut().and_then(|cache| { + cache.get_by_name(name, |lower| { + let found = profiles::find_by_name(&profiles::discovery_url(), lower); + if found.is_none() { + log("WARN", &format!("Couldn't find profile with name: {lower}")); + } + found + }) + }); + if found.is_none() { + let unknown = Text::translate("argument.player.unknown", &[]); + log("INFO", &format!("System chat: {}", unknown.plain())); + } + found + } + + /// MinecraftServer.sendSystemMessage: what the console is told; while + /// the console runs a command, the replies vanilla broadcasts go to the + /// operators too. + fn console_reply(&mut self, text: Text) { log("INFO", &format!("System chat: {}", text.plain())); + if self.console_broadcast.is_some() + && text + .translation_key() + .is_some_and(|k| BROADCAST.contains(&k)) + { + self.broadcast_to_admins(text); + } + } + + /// One console line, then the operators' share of its feedback. + fn console_line(&mut self, state: &mut ServerState, line: &str) { + self.console_broadcast = Some(state.broadcast_console); + self.console_command(state, line); + self.console_broadcast = None; + if let Some(mut host) = self.lan.take() { + self.send_admin_feedback(&mut host, None); + self.lan = Some(host); + } + self.admin_feedback.clear(); } /// DedicatedServer.handleConsoleInputs: one console line, run as the @@ -740,7 +910,9 @@ impl Game<'_> { )); } "op" | "deop" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0]) else { + return; + }; let level = 4; let changed = { let mut l = state.lists.lock().unwrap(); @@ -770,7 +942,9 @@ impl Game<'_> { } "whitelist" => self.console_whitelist(state, &rest), "ban" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0]) else { + return; + }; let reason = (rest.len() > 1).then(|| rest[1..].join(" ")); let added = state.lists.lock().unwrap().bans.add(BanEntry::new( user.clone(), @@ -860,7 +1034,9 @@ impl Game<'_> { } } "pardon" if !rest.is_empty() => { - let user = self.resolve(rest[0]); + let Some(user) = self.resolve(rest[0]) else { + return; + }; let removed = state.lists.lock().unwrap().bans.remove(&user); let key = if removed { "commands.pardon.success" @@ -926,15 +1102,10 @@ impl Game<'_> { } } "kick" if !rest.is_empty() => { - let user = self.resolve(rest[0]); - let online = self - .lan - .as_ref() - .is_some_and(|h| h.hub.guests.iter().any(|g| g.uuid == user.id)); - if !online { + let Some(user) = self.online_player(rest[0]) else { self.console_reply(Text::translate("argument.entity.notfound.player", &[])); return; - } + }; let reason = if rest.len() > 1 { Tag::String(JavaString::from(rest[1..].join(" ").as_str())) } else { @@ -1014,7 +1185,9 @@ impl Game<'_> { self.console_reply(Text::translate("commands.whitelist.reloaded", &[])); } ["add", name] | ["remove", name] => { - let user = self.resolve(name); + let Some(user) = self.resolve(name) else { + return; + }; let mut l = state.lists.lock().unwrap(); let (ok, key) = if rest[0] == "add" { if l.white.contains(&user) { diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index ee8170bc5..fbad3cfc7 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -318,8 +318,18 @@ impl Game<'_> { } else { self.dispense_from(origin, state)?; // CrafterBlockEntity.serverTick, the crafting animation running down. + let mut crafters: Vec<(i32, i32, i32)> = self + .world + .block_entities + .iter() + .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) + .map(|(p, _)| *p) + .collect(); + crafters.sort_unstable(); for _ in 0..case["ticks"].as_u64().unwrap_or(0) { - self.tick_crafters(); + for &p in &crafters { + self.tick_crafter(p); + } } } diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index ff91df583..e76eb16fb 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -74,6 +74,8 @@ impl Respawn { } #[derive(Clone, Debug)] pub(super) struct Crystal { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub position: Vec3, pub show_bottom: bool, /// EndCrystal.time (the bob and spin), starting random. @@ -553,6 +555,7 @@ impl Game<'_> { } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: at, show_bottom: true, time, @@ -2301,6 +2304,7 @@ impl Crystal { pub(super) fn from_nbt(tag: &Tag, time: i32) -> Option { let (position, _, _) = horizon_client::entity_nbt::boat_from_nbt(tag)?; Some(Self { + id: 0, position, show_bottom: !matches!(tag.get("ShowBottom"), Some(Tag::Byte(0))), time, @@ -2403,6 +2407,7 @@ impl Game<'_> { } let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: Vec3::new(x + 0.5, y, z + 0.5), show_bottom: false, time, @@ -2665,6 +2670,7 @@ impl Game<'_> { .retain(|c| c.position.distance_squared(at) > 0.01); let time = self.world.random.next_int_bound(100_000).unwrap_or(0); self.crystals.push(Crystal { + id: 0, position: at, show_bottom: true, time, diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index 71ab13378..b710f4e73 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -49,3 +49,64 @@ impl Game<'_> { } } } + +/// Entity.shouldRenderAtSqrDistance's default range: 64 times the bounding +/// box's mean edge, scaled by the entity distance option. +pub(super) fn default_range(size: glam::DVec3, view_scale: f32) -> f64 { + let edge = (size.x + size.y + size.z) / 3.0; + let edge = if edge.is_nan() { 1.0 } else { edge }; + edge * 64.0 * f64::from(view_scale) +} + +impl Game<'_> { + /// EntityRenderer.shouldRender: the entity within `range` blocks of the + /// camera, measured from its current `position`, and its culling box + /// (`lo`..`hi`, interpolated, in world space) grown by 0.5 in the view. + pub(super) fn entity_in_view( + &self, + camera: glam::DVec3, + position: glam::DVec3, + range: f64, + lo: glam::DVec3, + hi: glam::DVec3, + ) -> bool { + if (position - camera).length_squared() >= range * range { + return false; + } + self.view_frustum.as_ref().is_none_or(|view| { + view.intersects( + (lo - camera - glam::DVec3::splat(0.5)).as_vec3(), + (hi - camera + glam::DVec3::splat(0.5)).as_vec3(), + ) + }) + } +} + +/// An entity's position as a `DVec3`. +pub(super) fn at(p: horizon_core::geometry::Vec3) -> glam::DVec3 { + glam::DVec3::new(p.x, p.y, p.z) +} + +impl Game<'_> { + /// `entity_in_view` for an entity whose box stands on its position, + /// `width` wide and `height` tall, interpolated by `alpha` and grown by + /// `grow` (a renderer's getBoundingBoxForCulling). + #[allow(clippy::too_many_arguments)] + pub(super) fn standing_entity_in_view( + &self, + camera: glam::DVec3, + previous: glam::DVec3, + position: glam::DVec3, + alpha: f64, + width: f64, + height: f64, + range: f64, + grow: f64, + ) -> bool { + let p = previous.lerp(position, alpha); + let half = glam::DVec3::new(width / 2.0 + grow, grow, width / 2.0 + grow); + let lo = p - half; + let hi = p + glam::DVec3::new(half.x, height + grow, half.z); + self.entity_in_view(camera, position, range, lo, hi) + } +} diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index 16a003c04..f10a3b738 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -23,7 +23,7 @@ impl Game<'_> { .guests .iter() .filter(|g| { - g.placed + host.hub.here(g) && g.loaded && !g.dead && !g.creative() diff --git a/crates/horizon-client/src/game/fireworks.rs b/crates/horizon-client/src/game/fireworks.rs index 0e074025f..85fccc2de 100644 --- a/crates/horizon-client/src/game/fireworks.rs +++ b/crates/horizon-client/src/game/fireworks.rs @@ -18,21 +18,46 @@ use horizon_core::{ }; pub(super) struct Rocket { - position: Vec3, + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, + pub(super) position: Vec3, previous: Vec3, - velocity: Vec3, + pub(super) velocity: Vec3, life: i32, lifetime: i32, explosions: Vec, /// Boosting the player (attachedToEntity). - attached: bool, + pub(super) attached: bool, /// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on /// the first block it hits. - angled: bool, + pub(super) angled: bool, /// `DATA_ID_FIREWORKS_ITEM`: the stack it was launched from. - item: ItemStack, + pub(super) item: ItemStack, } impl Rocket { + /// A rocket a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, velocity: Vec3) -> Self { + let item = ItemStack::new("minecraft:firework_rocket", 1); + let (_, explosions) = fireworks_of(&item); + Self { + id, + position, + previous: position, + velocity, + life: 0, + lifetime: i32::MAX, + explosions, + attached: false, + angled: false, + item, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.life += 1; + self.position = step(self.position); + } /// Position and motion (the dispenser parity fixture). pub(super) fn motion(&self) -> (Vec3, Vec3) { (self.position, self.velocity) @@ -56,6 +81,7 @@ impl Game<'_> { + r.next_int_bound(6).unwrap_or(0) + r.next_int_bound(7).unwrap_or(0); Rocket { + id: 0, position: at, previous: at, velocity, @@ -253,6 +279,20 @@ impl Game<'_> { pub(super) fn rocket_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let orientation = glam::Mat4::from_quat(self.camera_orientation()); for r in self.rockets.iter().filter(|r| !r.attached) { + // FireworkRocketEntity.shouldRenderAtSqrDistance: within 64 blocks; + // EntityRenderer.shouldRender: its 0.25 box in the view. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(r.previous), + super::entity_culling::at(r.position), + alpha, + 0.25, + 0.25, + 64.0, + 0.0, + ) { + continue; + } let p = glam::DVec3::new( r.previous.x + (r.position.x - r.previous.x) * alpha, r.previous.y + (r.position.y - r.previous.y) * alpha, diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 7825d6514..64047b4f7 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -55,7 +55,13 @@ impl Game<'_> { .fov_player() .map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect)); let target = self.zoomed_fov_target(target); - let eye = self.player.as_ref().map(|p| p.dimensions.eye_height); + let eye = self.player.as_ref().map(|p| { + if self.sleeping.is_some() { + 0.2 + } else { + p.dimensions.eye_height + } + }); self.view.tick(eye, target); } /// The player's `deathTime` while dead or dying. @@ -106,7 +112,7 @@ impl Game<'_> { let hurt = &p.health.hurt; let state = BobState { living: Some(HurtBob { - hurt_time: hurt.hurt_time as f32 - partial, + hurt_time: p.health.hurt_animation_time as f32 - partial, hurt_duration: hurt.hurt_duration, hurt_dir: 0.0, death_time: self.death_time().map(|t| t as f32 + partial), diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 3ffa0e67e..2977ad483 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -304,9 +304,27 @@ impl Game<'_> { let sprites = &self.atlas.sprites; let mut maps: Vec<(i32, glam::Mat4, u32)> = Vec::new(); let mut items: Vec<(ItemStack, u32, glam::Mat4, u8)> = Vec::new(); + // ItemFrame.shouldRenderAtSqrDistance: 1024 blocks at 100%. + let range = 16.0 * 64.0 * f64::from(self.settings.entity_distance); for f in &self.item_frames { let entity_start = out.len(); let map = f.item.as_ref().and_then(super::maps::map_id); + // EntityRenderer.shouldRender: its box (a block wide with a map), + // measured from the box's centre. + let (lo, hi) = f.bounds(); + let (mut lo, mut hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); + if map.is_some() { + let s = f.step(); + for i in 0..3 { + if s[i] == 0 { + let c = (lo[i] + hi[i]) / 2.0; + (lo[i], hi[i]) = (c - 0.5, c + 0.5); + } + } + } + if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { + continue; + } let s = f.step(); // Pose: to the block centre, then X/Y rotation by facing. let (x_rot, y_rot) = if s[1] == 0 { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index a932913af..19e66174b 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -67,7 +67,7 @@ impl Game<'_> { /// attack clicks since the last tick and the held attack button. pub(super) fn tick_local_hand(&mut self) -> Result<()> { let attack_clicks = std::mem::take(&mut self.attack_clicks); - if self.screen == Screen::Playing && self.title.is_none() { + if self.screen == Screen::Playing && self.title.is_none() && self.sleeping.is_none() { let mut clicks = std::mem::take(&mut self.clicks); // keyAttack.isDown(); playing implies the grabbed mouse here // (scripts under --control hold buttons without grabbing it). diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index 7b5f3cced..b2c0a2e7f 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -28,7 +28,7 @@ use std::{ path::Path, sync::{ Arc, - atomic::{AtomicBool, AtomicU16, AtomicU32, Ordering}, + atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, Ordering}, mpsc::{Receiver, Sender, channel, sync_channel}, }, thread::JoinHandle, @@ -45,6 +45,10 @@ struct Flags { /// while it is not. published: AtomicU16, smoothed_tick_ms: AtomicU32, + /// `options.renderDistance` and `options.simulationDistance`, which the + /// server follows while it runs (IntegratedServer.tickServer). + render_distance: AtomicI32, + simulation_distance: AtomicI32, } /// Work the window hands its server thread (`MinecraftServer.execute`). @@ -66,6 +70,13 @@ impl Integrated { pub fn set_paused(&self, paused: bool) { self.flags.paused.store(paused, Ordering::Relaxed); } + /// The window's render and simulation distances, for the server to follow. + pub fn set_distances(&self, render: i32, simulation: i32) { + self.flags.render_distance.store(render, Ordering::Relaxed); + self.flags + .simulation_distance + .store(simulation, Ordering::Relaxed); + } /// `IntegratedServer.getPort` while `isPublished`. pub fn published(&self) -> Option { Some(self.flags.published.load(Ordering::Relaxed)).filter(|&p| p != 0) @@ -192,6 +203,12 @@ impl Game<'_> { options.dev_mods.clear(); let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); + flags + .render_distance + .store(settings.render_distance, Ordering::Relaxed); + flags + .simulation_distance + .store(settings.simulation_distance, Ordering::Relaxed); let (ready_tx, ready) = channel(); let (tasks, server_tasks) = channel(); let server_flags = flags.clone(); @@ -249,7 +266,9 @@ impl Game<'_> { launch.create.as_ref(), )?; let saved = Box::new(self.level.clone()); - let view_distance = self.settings.render_distance.clamp(2, 32); + // Math.max(2, options.renderDistance): past vanilla's 32 when the + // window's render distance is (Horizon's options go to 64). + let view_distance = self.settings.render_distance.max(2); let config = HubConfig { default_game_mode: self.level.mode(), // Only the owner until it is opened to the LAN. @@ -257,7 +276,7 @@ impl Game<'_> { force_game_mode: false, hardcore: self.level.hardcore, view_distance, - simulation_distance: self.settings.simulation_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), dimension: self.dim.id().to_owned(), seed: self.level.seed, max_players: MAX_PLAYERS, @@ -314,14 +333,13 @@ impl Game<'_> { let mut next = Instant::now(); while !flags.stop.load(Ordering::Relaxed) { self.run_tasks(); - self.update_dedicated_streaming(); - self.update_world(); if flags.paused.load(Ordering::Relaxed) { // Only the connections run. - self.tick_lan(); + self.tick_server(true)?; } else { + self.follow_distances(&flags); let started = Instant::now(); - self.tick()?; + self.tick_server(false)?; self.debug_charts.log_tick(started, started.elapsed()); flags.smoothed_tick_ms.store( self.debug_charts.smoothed_tick_ms.to_bits(), @@ -440,6 +458,28 @@ impl Game<'_> { } /// Publish or unpublish for real, once the hub is in its place (a /// player's `/publish` runs while it is out). + /// IntegratedServer.tickServer: the server follows the window's render + /// and simulation distances when they change. + fn follow_distances(&mut self, flags: &Flags) { + let Some(host) = self.lan.as_mut() else { + return; + }; + let view = flags.render_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.view_distance; + if view != old { + log::info!("Changing view distance to {view}, from {old}"); + host.hub.set_view_distance(view); + self.settings.render_distance = view; + } + let simulation = flags.simulation_distance.load(Ordering::Relaxed).max(2); + let old = host.hub.config.simulation_distance; + if simulation != old { + log::info!("Changing simulation distance to {simulation}, from {old}"); + host.hub.set_simulation_distance(simulation); + self.settings.simulation_distance = simulation; + } + } + fn apply_publish(&mut self) { if self.lan.is_none() { return; diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index aae200b50..b05f4fbf5 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -213,7 +213,7 @@ impl Game<'_> { owner.is_local_player = true; owner.is_view_entity = true; if let (Some((slot, ticks)), Some(stack)) = (self.using, stack) - && self.inventory.get(slot).and_then(Option::as_ref) == Some(stack) + && self.stack_in(slot) == Some(stack) { let view = item_render::stack_view(stack); let duration = use_duration(&self.pack.item_renderer.models.components(&view)); diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index 235ad7c24..ba7d2b786 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -140,63 +140,53 @@ impl Game<'_> { pub(super) fn jukebox_removed(&mut self, pos: [i32; 3]) { self.stop_song(pos); } - /// `JukeboxSongPlayer.tick` for every playing jukebox. - pub(super) fn tick_jukeboxes(&mut self) { - let playing: Vec<((i32, i32, i32), String, i64)> = self - .world - .block_entities - .iter() - .filter_map(|(k, e)| match e { - BlockEntity::Jukebox(j) if j.playing => { - let song = self - .res - .items - .get(&j.record.as_ref()?.item)? - .jukebox_song - .clone()?; - Some((*k, song, j.ticks)) - } - _ => None, - }) - .collect(); - for (key, song, ticks) in playing { - let pos = [key.0, key.1, key.2]; - let Some(s) = self.res.items.songs.get(&song).cloned() else { - continue; - }; - if s.finished(ticks) { - if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { - j.playing = false; - j.ticks = 0; - } - self.stop_song(pos); - self.jukebox_changed(pos); - continue; - } - if !self.jukebox_sounds.contains_key(&key) && ticks == 0 { - self.start_song(pos, &song); - } - if ticks % 20 == 0 { - let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0; - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 1.2, - f64::from(pos[2]) + 0.5, - ]; - self.particles.add( - &ParticleOptions::simple(ParticleType::Note), - at, - [color, 0.0, 0.0], - ); - } + /// `JukeboxSongPlayer.tick` of the jukebox at `key`, while it plays. + pub(super) fn tick_jukebox(&mut self, key: (i32, i32, i32)) { + let playing = match self.world.block_entities.get(&key) { + Some(BlockEntity::Jukebox(j)) if j.playing => j.record.as_ref().and_then(|r| { + let song = self.res.items.get(&r.item)?.jukebox_song.clone()?; + Some((song, j.ticks)) + }), + _ => None, + }; + let Some((song, ticks)) = playing else { + return; + }; + let pos = [key.0, key.1, key.2]; + let Some(s) = self.res.items.songs.get(&song).cloned() else { + return; + }; + if s.finished(ticks) { if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { - j.ticks += 1; + j.playing = false; + j.ticks = 0; } + self.stop_song(pos); + self.jukebox_changed(pos); + return; + } + if !self.jukebox_sounds.contains_key(&key) && ticks == 0 { + self.start_song(pos, &song); + } + if ticks % 20 == 0 { + let color = f64::from(self.world.random.next_int_bound(4).unwrap_or(0)) / 24.0; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 1.2, + f64::from(pos[2]) + 0.5, + ]; + self.particles.add( + &ParticleOptions::simple(ParticleType::Note), + at, + [color, 0.0, 0.0], + ); + } + if let Some(BlockEntity::Jukebox(j)) = self.world.block_entities.get_mut(&key) { + j.ticks += 1; } - self.update_song_volumes(); } /// Let go of songs that ended or whose jukebox stopped. - fn update_song_volumes(&mut self) { + pub(super) fn update_song_volumes(&mut self) { let sounds: Vec<_> = self .jukebox_sounds .iter() diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 078083006..114330e51 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -52,11 +52,15 @@ pub(super) struct LanHost { /// Blocks broken this tick (their sound is a level event for the guests). pub broken: Vec<[f64; 3]>, /// Hurt and death state of the mobs guests see. - mob_state: HashMap, + mob_state: HashMap>, /// The guest each mob sees as its player, when not the host (game/lan_mobs.rs). pub mob_players: HashMap, /// An integrated server's owner (game/integrated.rs). pub owner: Option, + /// The players' locator bars (game/lan_waypoints.rs), and the guests who + /// are dead, whose respawn replaces their waypoint. + pub waypoints: lan::waypoints::Waypoints, + pub waypoint_dead: std::collections::HashSet, } /// The player who owns an integrated server's world: a guest whose state is @@ -69,7 +73,7 @@ pub(super) struct Owner { } /// A stable UUID for an entity that has none. -fn entity_uuid(id: u32) -> u128 { +pub(super) fn entity_uuid(id: u32) -> u128 { 0x4856_5a4e_0000_0000_0000_0000_0000_0000u128 | u128::from(id) } @@ -140,11 +144,15 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { meta.push((3, serializer::BOOLEAN, Value::Bool(true))); } } - if m.health < m.kind.max_health { - meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0)))); + // LivingEntity.DATA_HEALTH_ID: defined as 1, then set to the max health. + let health = m.health.max(0.0); + if health != 1.0 { + meta.push((9, serializer::FLOAT, Value::Float(health))); } - if kind == "minecraft:rabbit" && m.no_ai { - meta.push((15, serializer::BYTE, Value::Byte(1))); + // Mob.DATA_MOB_FLAGS_ID: no AI 1, left-handed 2. + let flags = i8::from(m.no_ai) | i8::from(m.extra.left_handed) << 1; + if flags != 0 { + meta.push((15, serializer::BYTE, Value::Byte(flags))); } if m.is_baby() && let Some(index) = baby_index(kind) @@ -258,7 +266,7 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> { meta.push(( 16, serializer::OPTIONAL_BLOCK_STATE, - Value::Id(i32::from(state.0 as u16)), + Value::Id(state.0 as i32), )); } } @@ -359,6 +367,12 @@ impl Game<'_> { "open": true, "host": h.host_name, "port": h.settings.port, + // The server's own world: its finished chunks and how many it + // has generated or loaded so far. + "world": { + "chunks": self.world.chunks.len(), + "generated": self.streaming.generated_total, + }, "guests": h.hub.guests.iter().map(|g| json!({ "name": g.name, "position": g.position, @@ -366,6 +380,7 @@ impl Game<'_> { "loaded": g.loaded, "game_mode": g.game_mode, "sneaking": g.sneaking, + "sleeping": g.bed, "health": g.health, // FoodData: food level, saturation and exhaustion. "food": [ @@ -502,6 +517,8 @@ impl Game<'_> { mob_state: HashMap::new(), mob_players: HashMap::new(), owner: None, + waypoints: Default::default(), + waypoint_dead: Default::default(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -706,9 +723,9 @@ impl Game<'_> { }) } - /// Mobs and items as the entities guests track. - fn lan_entities(&self, hub: &mut Hub) -> Vec { - let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len()); + /// The entities guests track: mobs, items and the rest (game/lan_entities.rs). + fn lan_entities(&self, host_entity: Option, hub: &mut Hub) -> Vec { + let mut out = Vec::with_capacity(self.mobs.len() + self.dropped.len() + self.orbs.len()); for m in self.mobs.iter().filter(|m| !m.removed) { let kind = m.kind.id.as_str(); let meta = mob_meta(m, hub); @@ -727,6 +744,7 @@ impl Game<'_> { data: 0, meta, equipment, + precise: false, }); } for d in &self.dropped { @@ -744,8 +762,28 @@ impl Game<'_> { data: 0, meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], equipment: Vec::new(), + precise: false, }); } + for o in &self.orbs { + out.push(EntityState { + id: o.id as i32, + uuid: entity_uuid(o.id), + kind: "minecraft:experience_orb".to_owned(), + position: [o.position.x, o.position.y, o.position.z], + yaw: 0.0, + pitch: 0.0, + head_yaw: 0.0, + on_ground: o.on_ground, + velocity: [o.velocity.x, o.velocity.y, o.velocity.z], + data: 0, + // ExperienceOrb.DATA_VALUE. + meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], + equipment: Vec::new(), + precise: false, + }); + } + self.lan_object_states(host_entity, hub, &mut out); out } @@ -756,12 +794,19 @@ impl Game<'_> { }; // What the tick sends a guest goes to its connection at the end. let holding = lan::Holding::start(); + // The host's own commands' broadcastToAdmins lines. + if !self.admin_feedback.is_empty() { + self.send_admin_feedback(&mut host, None); + } let state = self.lan_host_state(&host); // A dedicated server runs the hub without a host player. if state.is_some() || host.hub.config.dedicated { let has_guests = !host.hub.guests.is_empty(); let entities = if has_guests { - self.lan_entities(&mut host.hub) + let host_entity = state.as_ref().map(|s| s.entity_id); + self.lan_assign_ids(); + self.lan_riding(host_entity, &mut host.hub.riding); + self.lan_entities(host_entity, &mut host.hub) } else { Vec::new() }; @@ -782,8 +827,25 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; - host.hub.tick(&mut ctx) + host.hub.movement_checks = ( + self.ui.rules.bool("player_movement_check"), + self.ui.rules.bool("elytra_movement_check"), + ); + // A server with several levels runs a pass for each + // (`tick_server`): the network is read once, before the first. + let pass = self.level_pass; + let mut events = if pass.first { + host.hub.poll(&mut ctx) + } else { + Vec::new() + }; + events.extend(host.hub.tick_level(&mut ctx)); + if pass.last { + host.hub.end_tick(); + } + events }; if let Some(state) = &state && host.host_mode != state.game_mode @@ -793,12 +855,16 @@ impl Game<'_> { } for event in events { match event { + event @ (HostEvent::Chat { .. } | HostEvent::Warn(_) | HostEvent::Error(_)) => { + self.lan_log_event(event); + } HostEvent::Joined(conn) => { self.lan_guest_joined(&mut host, conn, state.as_ref(), &entities, spawn); if self.options.dedicated.is_some() && let Some(g) = host.hub.guest(conn) { // PlayerList.placeNewPlayer, then the broadcast join message. + super::dedicated::player_joined(g.uuid, &g.name); let [x, y, z] = g.position; super::dedicated::log( "INFO", @@ -823,7 +889,15 @@ impl Game<'_> { if let Some(pos) = guest.menu.as_ref().and_then(|m| m.pos) && !guest.spectator() { - self.container_openers_changed(pos, false); + // In the level they were in. + let back = self.dim; + let theirs = super::Dim::from_id(&guest.dimension); + if self.enter_level(Some(&mut host), theirs).is_ok() { + self.container_openers_changed(pos, false); + } + if let Err(e) = self.enter_level(Some(&mut host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } self.lan_crafting_left(&mut host, &mut guest); self.save_guest(&host, &guest); @@ -840,11 +914,6 @@ impl Game<'_> { ); } } - // MinecraftServer.logChatMessage of an unsigned message. - HostEvent::Chat(line) if self.options.dedicated.is_some() => { - super::dedicated::log("INFO", &format!("[Not Secure] {line}")); - } - HostEvent::Chat(line) => self.system_message(Text::literal(line)), HostEvent::Packet(conn, packet) => { self.lan_guest_packet(&mut host, conn, *packet); } @@ -857,10 +926,9 @@ impl Game<'_> { self.lan_swings(&mut host); self.lan_update_streaming(&host); self.lan_update_models(&mut host); + self.lan_update_waypoints(&mut host, state.as_ref()); drop(holding); - for g in &host.hub.guests { - g.sender.flush(); - } + lan::flush_all(host.hub.guests.iter().map(|g| &g.sender)); self.lan = Some(host); } @@ -875,6 +943,7 @@ impl Game<'_> { let default_mode = host.hub.config.default_game_mode; let force = host.hub.config.force_game_mode; let root = self.world_root.clone(); + let in_place = host.hub.config.dimension.clone(); let owner = host.owner.as_mut(); let Some(g) = host.hub.guest_mut(conn) else { return; @@ -897,8 +966,29 @@ impl Game<'_> { g.previous_position = spawn; g.health = 20.0; g.food = 20; + g.dimension = super::Dim::Overworld.id().to_owned(); + } + // A server places each player in their own level + // (`PlayerList.placeNewPlayer`); the in-frame game has one. + let back = self.dim; + let level = super::Dim::from_id(&g.dimension); + let elsewhere = self.options.dedicated.is_some() && level != back; + if !elsewhere { + g.dimension = in_place; } self.load_guest_records(host, conn); + let theirs; + let entities = if elsewhere { + if let Err(e) = self.enter_level(Some(host), level) { + log::error!("could not open {}: {e}", level.id()); + return; + } + // A dedicated server has no host player. + theirs = self.lan_entities(None, &mut host.hub); + &theirs[..] + } else { + entities + }; let mut ctx = TickCtx { world: &mut self.world, host: state, @@ -910,8 +1000,12 @@ impl Game<'_> { clock_rate: self.ui.clock.rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; host.hub.place_new_player(conn, &mut ctx); + if elsewhere && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Level events the game queued, for the guests (`process_level_events`). @@ -932,7 +1026,7 @@ impl Game<'_> { /// `Level.blockEvent` for the guests (`ClientboundBlockEventPacket`). pub(super) fn lan_block_event(&mut self, pos: [i32; 3], b0: i32, b1: i32) { if self.audio.capture.is_some() { - let state = self.world.block(pos[0], pos[1], pos[2]).0 as u16; + let state = self.world.block(pos[0], pos[1], pos[2]).0; self.lan_block_events.push((pos, b0, b1, state)); } } @@ -966,7 +1060,11 @@ impl Game<'_> { let mut seen = HashMap::new(); for m in &self.mobs { let dead = !m.alive(); - let old = host.mob_state.get(&m.id).copied(); + let old = host + .mob_state + .get(&self.dim) + .and_then(|s| s.get(&m.id)) + .copied(); let at = [m.position.x, m.position.y, m.position.z]; if m.hurt_time > old.map_or(0, |o| o.0) && !dead { host.hub.entity_event(m.id as i32, 2, at); @@ -976,19 +1074,25 @@ impl Game<'_> { } seen.insert(m.id, (m.hurt_time, dead)); } - host.mob_state = seen; + host.mob_state.insert(self.dim, seen); } /// Keep the chunks around every guest loaded. fn lan_update_streaming(&mut self, host: &LanHost) { + // DistanceManager.PlayerTicketTracker: every chunk within the server's + // view distance (Chebyshev) of a player holds a PLAYER_LOADING ticket + // at the entity-ticking level (31), whatever the player asked for; + // levels rise by one a chunk, so FULL (33) reaches two chunks past + // it. An extra area finishes its chunks out to its radius + 1. That + // covers what the player tracks (`ChunkTrackingView`, within its view + // distance + 1) and those chunks' lit neighbours. + let radius = host.hub.config.view_distance + 1; self.streaming.extra = host .hub .guests .iter() - .filter(|g| g.placed) - // The tracked square's corners and their lit neighbours lie - // within (view distance + 2) * √2 of the player's chunk. - .map(|g| (g.chunk(), (g.view_distance + 2) * 3 / 2 + 1)) + .filter(|g| host.hub.here(g)) + .map(|g| (g.chunk(), radius)) .collect(); } @@ -1099,3 +1203,24 @@ impl Game<'_> { } } } + +impl Game<'_> { + /// A hub's chat and log lines: a dedicated server logs them + /// (MinecraftServer.logChatMessage, `[Not Secure]` for unsigned or + /// expired messages); a LAN host shows the chat. + pub(super) fn lan_log_event(&mut self, event: HostEvent) { + let dedicated = self.options.dedicated.is_some(); + match event { + HostEvent::Chat { line, secure } if dedicated => { + let tag = if secure { "" } else { "[Not Secure] " }; + super::dedicated::log("INFO", &format!("{tag}{line}")); + } + HostEvent::Chat { line, .. } => self.system_message(Text::literal(line)), + HostEvent::Warn(line) if dedicated => super::dedicated::log("WARN", &line), + HostEvent::Warn(line) => log::warn!("{line}"), + HostEvent::Error(line) if dedicated => super::dedicated::log("ERROR", &line), + HostEvent::Error(line) => log::error!("{line}"), + _ => {} + } + } +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 1d3433cf0..ced435d8d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -18,7 +18,7 @@ use horizon_client::{ }, motion::{MotionEvent, MotionWorld, PlayerMotion}, }; -use horizon_core::geometry::Vec3; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_protocol::{ packets::play::{self, Clientbound as C, Serverbound as S}, text::literal, @@ -54,6 +54,10 @@ pub(super) struct GuestPlay { /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. pub(super) stats: super::stats::Stats, last_inventory: u64, + /// `Entity.portalProcess` and `portalCooldown` (game/server_travel.rs). + pub(super) portal: horizon_client::nether_portal::PortalState, + /// `Player.takeXpDelay`: ticks until the next orb can be taken. + xp_delay: u32, } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -140,13 +144,20 @@ impl Game<'_> { total: g.xp_total, }, ); - let sneak = self.keys.contains(&KeyCode::ShiftLeft); + // The host's held keys stay theirs: the guest holds only sneak, and a + // screen the guest opens (`keys.clear()`) leaves the host walking. + let host_keys = std::mem::take(&mut self.keys); if g.sneaking { self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); } + // The window's screens are the host's: a sign, book, command block or + // mount menu the guest's action opens is not drawn over the host's + // world (#687). The guest's client opens its own. let screen = std::mem::replace(&mut self.screen, Screen::Playing); + let host_sign = self.sign_edit.take(); + let host_book = self.book.take(); + let host_command_block = self.command_block_screen.take(); + let host_mount_menu = std::mem::take(&mut self.mount_menu); // The host's crafting grid stays theirs; a crafting table the guest // opens shows as the 3x3 size. let craft_size = std::mem::replace(&mut self.craft_size, 2); @@ -163,6 +174,16 @@ impl Game<'_> { self.right = play.using.is_some() || self.using.is_some(); let riding = self.riding.take(); let host_station = self.station.take(); + // The guest's bed, sleep counter and respawn point; the host's + // respawn point, anchor and action bar stay theirs. + let sleeping = std::mem::replace(&mut self.sleeping, g.bed); + let sleep_timer = std::mem::replace(&mut self.sleep_timer, g.sleep_timer); + let spawn = std::mem::replace( + &mut self.spawn, + g.spawn.map(|s| Vec3::new(s[0], s[1], s[2])), + ); + let respawn = (self.respawn_config.take(), self.level.spawn); + let message = self.message.take(); // The guest's own ender inventory; one the host has open goes back // into the host's while the guest acts. let host_ender = self.ender_open; @@ -182,6 +203,9 @@ impl Game<'_> { self.lan_acting_uuid = Some(g.uuid); let result = f(self); + for packet in std::mem::take(&mut self.guest_packets) { + host.hub.send_to(conn, &packet); + } self.lan_acting = None; self.lan_acting_name = None; self.lan_acting_uuid = None; @@ -194,6 +218,12 @@ impl Game<'_> { let opened_table = std::mem::replace(&mut self.craft_size, craft_size) == 3; self.craft_grid = craft_grid; let opened_station = std::mem::replace(&mut self.station, host_station); + let bed = std::mem::replace(&mut self.sleeping, sleeping); + let guest_sleep_timer = std::mem::replace(&mut self.sleep_timer, sleep_timer); + let guest_spawn = std::mem::replace(&mut self.spawn, spawn).map(|s| [s.x, s.y, s.z]); + (self.respawn_config, self.level.spawn) = respawn; + // ServerPlayer.displayClientMessage(_, true): the guest's action bar. + let guest_message = std::mem::replace(&mut self.message, message); self.riding = riding; self.left = left; self.right = right; @@ -205,12 +235,21 @@ impl Game<'_> { play.swing = std::mem::replace(&mut self.swing, swing); self.container = container; self.screen = screen; - if sneak { - self.keys.insert(KeyCode::ShiftLeft); - } else { - self.keys.remove(&KeyCode::ShiftLeft); - } + self.sign_edit = host_sign; + self.book = host_book; + self.command_block_screen = host_command_block; + self.mount_menu = host_mount_menu; + self.keys = host_keys; let g = &mut host.hub.guests[i]; + let fell_asleep = bed.is_some() && g.bed.is_none(); + (g.bed, g.sleep_timer, g.spawn) = (bed, guest_sleep_timer, guest_spawn); + g.sleeping = g.bed.is_some(); + if let Some((text, _)) = guest_message { + g.send(&C::SystemChat(play::SystemChat { + content: literal(&text), + overlay: true, + })); + } std::mem::swap(&mut self.ender_items, &mut g.ender_items); std::mem::swap(&mut self.adv.progress, &mut g.advancements); std::mem::swap(&mut self.adv.changed, &mut g.advancements_changed); @@ -260,6 +299,19 @@ impl Game<'_> { } } let g = &mut host.hub.guests[i]; + if let Some(head) = g.bed.filter(|_| fell_asleep) { + // LivingEntity.startSleeping: in the bed, still. + let at = [ + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ]; + g.position = at; + if let Some(m) = g.motion.as_mut() { + m.position = Vec3::new(at[0], at[1], at[2]); + m.velocity = Vec3::ZERO; + } + } if new_mode != g.game_mode { let conn = g.conn; host.hub.set_game_mode(conn, new_mode); @@ -282,6 +334,32 @@ impl Game<'_> { Some(result) } + /// `ServerLevel.players()` in turn: the host's own player, then each + /// guest in the level in place with their state swapped in (`as_guest`). + /// What reaches the players around a point (a beacon's powers, a splash + /// potion, a warden's darkness, an elder guardian's curse) lands on each + /// of them, not only on the host. A server has no player of its own. + /// Inside a guest's action (the hub taken) only that player is in place. + pub(super) fn for_each_player(&mut self, mut f: impl FnMut(&mut Self)) { + if self.player.is_some() { + f(self); + } + let Some(mut host) = self.lan.take() else { + return; + }; + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) + .map(|g| g.conn) + .collect(); + for conn in conns { + self.as_guest(&mut host, conn, &mut f); + } + self.lan = Some(host); + } + /// The game mode fields without `set_mode`'s side effects on the host. fn set_mode_raw(&mut self, id: i32) { use horizon_client::command::args::GameMode; @@ -561,7 +639,8 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } - S::ChatCommand(c) => self.guest_command(host, conn, &c.command), + S::ChatCommand(c) => self.guest_chat_command(host, conn, &c.command), + S::ChatCommandSigned(p) => self.guest_signed_command(host, conn, p), S::ChangeDifficulty(p) if host.hub.guests[gi].permission >= 2 => { if !self.level.difficulty_locked && (0..=3).contains(&p.difficulty) { self.ui.difficulty = if self.level.hardcore { @@ -650,12 +729,7 @@ impl Game<'_> { }), ); } - } - } - S::Unknown(8, payload) => { - // A signed command: the text comes first. - if let Ok(text) = horizon_protocol::buf::Reader::new(&payload).string(32767) { - self.guest_command(host, conn, &text); + self.send_admin_feedback(host, Some(conn)); } } S::Unknown(id, payload) @@ -663,6 +737,7 @@ impl Game<'_> { { self.guest_suggestions(host, conn, &payload); } + S::PlaceRecipe(p) => self.lan_place_recipe(host, conn, &p), S::ClientCommand(c) if c.action == 0 => self.guest_respawn(host, conn), // ServerStatsCounter.sendStats. S::ClientCommand(c) if c.action == 1 => { @@ -781,7 +856,18 @@ impl Game<'_> { } /// Commands.performCommand for a guest with command access. - fn guest_command(&mut self, host: &mut LanHost, conn: u32, command: &str) { + /// Commands.performCommand for a guest, with the message arguments it + /// signed (none after an unsigned command packet). + pub(super) fn guest_command( + &mut self, + host: &mut LanHost, + conn: u32, + command: &str, + signed: Option>, + ) { + if self.guest_message_command(host, conn, command, signed.as_ref()) { + return; + } // ListPlayersCommand needs no permission and lists every player. let words: Vec<&str> = command.trim_start_matches('/').split(' ').collect(); if words[0] == "list" && (words.len() == 1 || words[1..] == ["uuids"]) { @@ -851,6 +937,8 @@ impl Game<'_> { .map(|t| horizon_client::lan::data::component_nbt(&t.component())) .collect::>() }); + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(host); for content in lines.unwrap_or_default() { host.hub.send_to( conn, @@ -860,6 +948,41 @@ impl Game<'_> { }), ); } + self.send_admin_feedback(host, Some(conn)); + } + + /// The `broadcastToAdmins` lines a command queued (`source`: the guest + /// whose it was; none for the host's or the console's): every other + /// operator gets them, and the console logs them as the server's own + /// system messages (MinecraftServer.sendSystemMessage). + pub(super) fn send_admin_feedback(&mut self, host: &mut LanHost, source: Option) { + // PlayerList.isOp for the host of a world open to LAN: the owner when + // the world allows commands, everyone when the LAN does. + let host_op = source.is_some() + && !host.hub.config.dedicated + && (self.allow_commands() || host.hub.config.guest_commands); + for (line, ops, console) in std::mem::take(&mut self.admin_feedback) { + if ops { + let content = horizon_client::lan::data::component_nbt(&line.component()); + for g in host + .hub + .guests + .iter() + .filter(|g| Some(g.conn) != source && g.permission > 0) + { + g.send(&C::SystemChat(play::SystemChat { + content: content.clone(), + overlay: false, + })); + } + if host_op { + self.system_message(line.clone()); + } + } + if console { + super::dedicated::log("INFO", &format!("System chat: {}", line.plain())); + } + } } /// ServerGamePacketListenerImpl.handleCustomCommandSuggestions: the @@ -903,14 +1026,34 @@ impl Game<'_> { } fn guest_respawn(&mut self, host: &mut LanHost, conn: u32) { - let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; + // The guest's own bed, else the world spawn: never the host's bed. + let world = self + .level + .world_spawn + .map(|[x, y, z]| [f64::from(x) + 0.5, f64::from(y), f64::from(z) + 0.5]); + let spawn = host.hub.guests[i] + .spawn + .or(world) + .or(self.spawn.map(|s| [s.x, s.y, s.z])) + .unwrap_or([0.5, 80.0, 0.5]); if !host.hub.guests[i].dead { return; } - self.respawn_level(host); + // PlayerList.respawn: a server's player comes back in the Overworld, + // where the world spawn is (respawn anchors and beds aside). + let back = self.dim; + let away = self.options.dedicated.is_some() + && host.hub.guests[i].dimension != super::Dim::Overworld.id(); + if away { + self.server_trips.retain(|t| !t.is(conn)); + if let Err(e) = self.enter_level(Some(host), super::Dim::Overworld) { + log::error!("could not open the Overworld: {e}"); + return; + } + } let g = &mut host.hub.guests[i]; g.dead = false; g.health = 20.0; @@ -944,8 +1087,12 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), }; host.hub.respawn(i, spawn, &ctx); + if away && let Err(e) = self.enter_level(Some(host), back) { + log::error!("could not reopen {}: {e}", back.id()); + } } /// Per tick, for every guest: dig, use items, pick up drops, die. @@ -956,13 +1103,14 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded) + .filter(|g| host.hub.here(g) && g.loaded) .map(|g| g.conn) .collect(); for conn in conns { let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { continue; }; + self.guest_sleep_tick(host, gi); if host.hub.guests[gi].dead || self.on_server_trip(conn) { continue; } @@ -1005,6 +1153,7 @@ impl Game<'_> { host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); self.guest_pickups(host, gi); + self.guest_orbs(host, gi); let g = &mut host.hub.guests[gi]; if g.health <= 0.0 && !g.dead { g.dead = true; @@ -1028,6 +1177,62 @@ impl Game<'_> { } } + /// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a + /// sleeper who died or whose bed is gone. + fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) { + let g = &mut host.hub.guests[gi]; + g.sleep_timer = super::tick_sleep_timer(g.sleep_timer, g.bed.is_some()); + if let Some(head) = g.bed { + let block = self.world.block(head[0], head[1], head[2]); + let bed = self.res.facts.get(block).name.ends_with("_bed"); + if g.dead || g.health <= 0.0 || !bed { + host.hub.wake(gi); + } + } + } + + /// `SleepStatus.areEnoughSleeping` and `areEnoughDeepSleeping` over the + /// host's player and the guests: of the players not in spectator mode, + /// players_sleeping_percentage of them (at least one) are in bed, and as + /// many have slept 100 ticks. + pub(super) fn enough_slept(&self) -> bool { + let (mut active, mut sleeping, mut deep) = (0i64, 0i64, 0i64); + let mut count = |in_bed: bool, timer: u32| { + active += 1; + if in_bed { + sleeping += 1; + if timer >= 100 { + deep += 1; + } + } + }; + if self.player.is_some() && !self.spectator() { + count(self.sleeping.is_some(), self.sleep_timer); + } + if let Some(host) = self.lan.as_ref() { + for g in host + .hub + .guests + .iter() + .filter(|g| g.placed && !g.spectator()) + { + count(g.bed.is_some(), g.sleep_timer); + } + } + let percent = i64::from(self.ui.rules.int("players_sleeping_percentage").max(0)); + let needed = ((active * percent + 99) / 100).max(1); + sleeping >= needed && deep >= needed + } + + /// `ServerLevel.wakeUpAllPlayers` for the guests. + pub(super) fn wake_guests(&mut self) { + if let Some(host) = self.lan.as_mut() { + for i in 0..host.hub.guests.len() { + host.hub.wake(i); + } + } + } + /// `PlayerList.broadcastSystemMessage` of the advancements guests made /// (their own actions, commands and ticks). fn announce_guest_advancements(&mut self, host: &mut LanHost) { @@ -1306,6 +1511,79 @@ impl Game<'_> { } } + /// `Player.tick`'s takeXpDelay and `Player.aiStep`'s touch of the + /// experience orbs in the guest's box grown by 1, 0.5, 1: one of them at + /// random, at most every 2 ticks (`ExperienceOrb.playerTouch`), repairs + /// with Mending and gives the rest as points. Everyone near hears it. + fn guest_orbs(&mut self, host: &mut LanHost, gi: usize) { + let g = &host.hub.guests[gi]; + // Player's standing and crouching boxes: 1.8 and 1.5 high. + let height = if g.sneaking { 1.5 } else { 1.8 }; + let (conn, id, at) = (g.conn, g.entity_id, g.position); + let unable = g.spectator() || g.dead || g.health <= 0.0; + let play = host.play.entry(conn).or_default(); + if play.xp_delay > 0 { + play.xp_delay -= 1; + } + if unable || play.xp_delay > 0 { + return; + } + let (min, max) = ( + [at[0] - 1.3, at[1] - 0.5, at[2] - 1.3], + [at[0] + 1.3, at[1] + height + 0.5, at[2] + 1.3], + ); + let touching: Vec = self + .orbs + .iter() + .enumerate() + .filter(|(_, o)| { + o.position.x + 0.25 > min[0] + && o.position.x - 0.25 < max[0] + && o.position.y + 0.5 > min[1] + && o.position.y < max[1] + && o.position.z + 0.25 > min[2] + && o.position.z - 0.25 < max[2] + }) + .map(|(i, _)| i) + .collect(); + if touching.is_empty() { + return; + } + // Util.getRandom(orbs, random). + let pick = self + .world + .random + .next_int_bound(touching.len() as i32) + .unwrap_or(0) as usize; + let orb = self.orbs.remove(touching[pick]); + play.xp_delay = 2; + host.hub.take_item(orb.id as i32, id, 1, at); + // ClientPacketListener.handleTakeItemEntity's sound, at the orb. + let pitch = (self.world.random.next_float() - self.world.random.next_float()) * 0.35 + 0.9; + let p = orb.position; + self.audio.play( + "minecraft:entity.experience_orb.pickup", + Some([p.x, p.y, p.z]), + 0.1, + pitch, + ); + let value = orb.value; + if let Some(target) = super::pickups::guest_target(host, id as u32) { + use super::pickups::{Collector, Taken}; + self.add_pickup_toward( + Taken::Orb(Box::new(orb)), + Collector::Guest(id as u32), + target, + ); + } + self.as_guest(host, conn, |game| { + let rest = game.mending(value); + if rest > 0 { + game.give_orb_points(rest); + } + }); + } + /// The host's own `ItemPickupParticle` toward the guest's model. fn guest_pickup( &mut self, @@ -1348,6 +1626,9 @@ impl Game<'_> { let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { continue; }; + if !host.hub.here(g) { + continue; + } let (id, at) = (g.entity_id, g.position); let play = host.play.get_mut(&conn).expect("play"); let swinging = play.swing.swinging() && play.swing.ticks == 0; diff --git a/crates/horizon-client/src/game/lan_chat.rs b/crates/horizon-client/src/game/lan_chat.rs new file mode 100644 index 000000000..f678480ab --- /dev/null +++ b/crates/horizon-client/src/game/lan_chat.rs @@ -0,0 +1,194 @@ +//! A guest's commands that carry chat: the unsigned and signed command +//! packets (ServerGamePacketListenerImpl.handleChatCommand and +//! handleSignedChatCommand), and the message commands whose text they sign +//! (SayCommand, EmoteCommands, MsgCommand), relayed by the hub as chat. +use super::{Game, lan::LanHost}; +use horizon_client::{ + command::{Arg, ArgType, NodeKind, ParseResults, vanilla}, + lan::{ + data::component_nbt, + hub::{HostEvent, chat::ChatMessage}, + }, + text::{self, Text}, +}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// The signing context of a command: each message argument as the chain +/// let it through, by argument name (CommandSigningContext.SignedArguments). +type Signed = Vec<(String, ChatMessage)>; + +impl Game<'_> { + /// CommandDispatcher.parse with the guest's permission level. + fn parse_as(&mut self, permission: u8, command: &str) -> ParseResults { + let level = std::mem::replace(&mut self.ui.registries.permission, permission); + let parse = vanilla::game_dispatcher().parse(command, &self.ui.registries); + self.ui.registries.permission = level; + parse + } + + /// SignableCommand.of: the command's message arguments, by name, with + /// their text, not past a redirect to the root (`execute ... run`). + fn signable_arguments(&mut self, permission: u8, command: &str) -> Vec<(String, String)> { + let parse = self.parse_as(permission, command); + let nodes = &vanilla::game_dispatcher().nodes; + let root = parse.context.root; + let mut out = Vec::new(); + let mut context = Some(&parse.context); + while let Some(c) = context { + for &(node, (start, end)) in &c.nodes { + if let NodeKind::Argument { + ty: ArgType::Message, + name, + } = &nodes[node].kind + && let Some(text) = command.get(start..end) + { + out.push((name.clone(), text.to_owned())); + } + } + context = c.child.as_deref().filter(|child| child.root != root); + } + out + } + + /// handleChatCommand (performUnsignedChatCommand): refused when the + /// server enforces secure chat and the command has a message to sign. + pub(super) fn guest_chat_command(&mut self, host: &mut LanHost, conn: u32, command: &str) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + if !host.hub.try_handle_chat(i, command, true) { + return; + } + let permission = host.hub.guests[i].permission; + if host.hub.enforces_secure_chat() + && !self.signable_arguments(permission, command).is_empty() + { + let name = host.hub.guests[i].name.clone(); + self.lan_log_event(HostEvent::Error(format!( + "Received unsigned command packet from {name}, but the command requires signable arguments: {command}" + ))); + let failure = Text::translate("chat.disabled.invalid_command_signature", &[]) + .with_color(text::RED); + host.hub.guests[i].send(&C::SystemChat(play::SystemChat { + content: component_nbt(&failure.component()), + overlay: false, + })); + return; + } + self.guest_command(host, conn, command, None); + } + + /// handleSignedChatCommand: the acknowledgements, then each message + /// argument through the sender's chain, then the command with them. + pub(super) fn guest_signed_command( + &mut self, + host: &mut LanHost, + conn: u32, + p: play::ChatCommandSigned, + ) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let mut events = Vec::new(); + let mut signed = None; + if let Some(last_seen) = host.hub.apply_last_seen(i, &p.last_seen, &mut events) + && host.hub.try_handle_chat(i, &p.command, true) + { + let permission = host.hub.guests[i].permission; + let parsed = self.signable_arguments(permission, &p.command); + match host + .hub + .signed_arguments(i, &p, &parsed, &last_seen, &mut events) + { + Ok(arguments) => signed = Some(arguments), + Err(e) => host.hub.decode_failure(i, e, &mut events), + } + } + for event in events { + self.lan_log_event(event); + } + if let Some(signed) = signed { + self.guest_command(host, conn, &p.command, Some(signed)); + } + } + + /// SayCommand, EmoteCommands and MsgCommand for a guest: chat to the + /// players, signed when the guest signed it (a disguised chat after an + /// unsigned command packet). False when the command is another one, or + /// one this can't run (selectors other than `@s` and `@a`), for the + /// game's dispatcher to handle. + pub(super) fn guest_message_command( + &mut self, + host: &mut LanHost, + conn: u32, + command: &str, + signed: Option<&Signed>, + ) -> bool { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return false; + }; + let parse = self.parse_as(host.hub.guests[i].permission, command); + let Ok((context, id)) = parse.executable() else { + return false; + }; + let argument = if id == "me" { "action" } else { "message" }; + let (Some(Arg::Str(text)), true) = + (context.get(argument), matches!(id, "say" | "me" | "msg")) + else { + return false; + }; + let message = signed.and_then(|s| { + s.iter() + .find(|(n, _)| n == argument) + .map(|(_, m)| m.clone()) + }); + let mut events = Vec::new(); + if id == "msg" { + let Some(Arg::Entity(selector)) = context.get("targets") else { + return false; + }; + let raw = context + .args + .iter() + .rev() + .find(|a| a.name == "targets") + .and_then(|a| command.get(a.range.0..a.range.1)); + let guests = &host.hub.guests; + let placed = |k: &usize| guests[*k].placed; + let targets: Vec = match (raw, &selector.player_name, selector.uuid) { + (Some("@s"), ..) => vec![i], + (Some("@a"), ..) => (0..guests.len()).filter(placed).collect(), + (_, Some(name), _) => (0..guests.len()) + .filter(|&k| placed(&k) && guests[k].name.eq_ignore_ascii_case(name)) + .collect(), + (_, None, Some(uuid)) => (0..guests.len()) + .filter(|&k| placed(&k) && guests[k].uuid == uuid) + .collect(), + _ => return false, + }; + if targets.is_empty() { + let failure = Text::empty() + .append(Text::translate("argument.entity.notfound.player", &[])) + .with_color(text::RED); + host.hub.guests[i].send(&C::SystemChat(play::SystemChat { + content: component_nbt(&failure.component()), + overlay: false, + })); + return true; + } + host.hub.whisper(i, &targets, message, text); + } else { + let chat_type = if id == "say" { + "say_command" + } else { + "emote_command" + }; + host.hub + .broadcast_command_chat(i, chat_type, message, text, &mut events); + } + for event in events { + self.lan_log_event(event); + } + true + } +} diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 9841fa879..1f16a9c74 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -225,6 +225,86 @@ impl Game<'_> { true } + /// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe + /// book places a known recipe in their inventory grid or crafting table + /// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items + /// are missing. + pub(super) fn lan_place_recipe( + &mut self, + host: &mut LanHost, + conn: u32, + p: &horizon_protocol::packets::recipes::PlaceRecipe, + ) { + use horizon_client::menu::place::PostPlace; + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let g = &host.hub.guests[gi]; + if g.spectator() { + return; + } + let Some(id) = self + .res + .stations + .recipe_index + .recipe_of_display(p.recipe) + .map(str::to_owned) + else { + return; + }; + // An unknown or impossible recipe is refused outright. + if !g.recipe_book.knows(&id) + || self + .res + .recipes + .placement(&id) + .is_none_or(|placement| placement.impossible()) + { + return; + } + let creative = g.creative(); + let placed = if p.container == 0 { + let crafting = host.play.entry(conn).or_default(); + let mut menu = crafting + .crafting + .inventory + .take() + .unwrap_or_else(|| Box::new(Menu::new(Kind::Inventory))); + let grid = host.hub.guests[gi].craft_grid.clone(); + let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { + for (k, s) in grid.into_iter().enumerate() { + menu.set_slot(env, 1 + k, s); + } + menu.place_recipe(env, &id, p.use_max, creative, None) + }); + let g = &mut host.hub.guests[gi]; + for k in 0..4 { + g.craft_grid[k] = menu.slot(1 + k).cloned(); + } + g.craft_result = menu.slot(0).cloned(); + host.play.entry(conn).or_default().crafting.inventory = Some(menu); + host.hub.send_inventory(gi); + placed + } else { + let Some((window, state, mut menu)) = host + .play + .get_mut(&conn) + .and_then(|play| play.crafting.table.take_if(|(w, _, _)| *w == p.container)) + else { + return; + }; + let placed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { + menu.place_recipe(env, &id, p.use_max, creative, None) + }); + host.play.entry(conn).or_default().crafting.table = Some((window, state, menu)); + self.lan_send_table_content(host, conn); + placed + }; + if placed == PostPlace::Ghost { + host.hub.send_ghost_recipe(conn, p.container, &id); + } + } + /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs new file mode 100644 index 000000000..3ea172482 --- /dev/null +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -0,0 +1,449 @@ +//! The entities beyond mobs and items that a server tracks to its clients +//! (`ChunkMap.TrackedEntity`, `ServerEntity`): boats, minecarts, armor +//! stands, item frames, paintings and the entities Horizon keeps without +//! simulating them, each as vanilla pairs it (`getAddEntityPacket` and the +//! synched data that differs from the defaults), and who rides what. +use super::Game; +use horizon_client::lan::{ + entity::{EntityState, Riding}, + hub::Hub, +}; +use horizon_protocol::entity_data::{Value, serializer}; +use horizon_world::nbt::Tag; + +/// `ArmorStand`'s default poses (head, body, left arm, right arm, left leg, +/// right leg), DATA_HEAD_POSE to DATA_RIGHT_LEG_POSE (entries 16 to 21), +/// under their `Pose` keys. +const STAND_POSES: [(&str, [f32; 3]); 6] = [ + ("Head", [0.0, 0.0, 0.0]), + ("Body", [0.0, 0.0, 0.0]), + ("LeftArm", [-10.0, 0.0, -10.0]), + ("RightArm", [-15.0, 0.0, 10.0]), + ("LeftLeg", [-1.0, 0.0, -1.0]), + ("RightLeg", [1.0, 0.0, 1.0]), +]; + +fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> EntityState { + EntityState { + id: id as i32, + uuid: super::lan::entity_uuid(id), + kind: kind.to_owned(), + position, + yaw, + pitch: 0.0, + head_yaw: 0.0, + on_ground, + velocity: [0.0; 3], + data: 0, + meta: Vec::new(), + equipment: Vec::new(), + precise: false, + } +} + +/// `VehicleEntity`'s DATA_ID_HURT, DATA_ID_HURTDIR and DATA_ID_DAMAGE +/// (entries 8 to 10) when they differ from their defaults (0, 1, 0). +fn vehicle_meta(hurt_time: i32, hurt_dir: i32, damage: f32) -> Vec<(u8, i32, Value)> { + let mut meta = Vec::new(); + if hurt_time != 0 { + meta.push((8, serializer::INT, Value::Int(hurt_time))); + } + if hurt_dir != 1 { + meta.push((9, serializer::INT, Value::Int(hurt_dir))); + } + if damage != 0.0 { + meta.push((10, serializer::FLOAT, Value::Float(damage))); + } + meta +} + +/// An armor stand's pose from its compound (`ArmorStandPose`), each part +/// that differs from the default. +fn stand_poses(raw: Option<&Tag>) -> Vec<(u8, i32, Value)> { + let Some(pose) = raw.and_then(|t| t.get("Pose")) else { + return Vec::new(); + }; + let mut meta = Vec::new(); + for (i, (key, default)) in STAND_POSES.iter().enumerate() { + let Some(Tag::List(values)) = pose.get(key) else { + continue; + }; + let mut r = *default; + for (k, v) in values.iter().take(3).enumerate() { + if let Tag::Float(bits) = v { + r[k] = f32::from_bits(*bits); + } + } + if r != *default { + meta.push(( + 16 + i as u8, + serializer::ROTATIONS, + Value::Floats(r.to_vec()), + )); + } + } + meta +} + +impl Game<'_> { + /// Who rides what (`Entity.getPassengers`): mobs on mobs, and the + /// host in its boat or minecart. + pub(super) fn lan_riding(&self, host_entity: Option, riding: &mut Riding) { + riding.clear(); + for m in self.mobs.iter().filter(|m| !m.removed) { + if let Some(vehicle) = m.extra.mount { + riding.add(vehicle as i32, m.id as i32); + } + } + if let (Some(host), Some(vehicle)) = (host_entity, self.riding) { + riding.add(vehicle as i32, host); + } + } + + /// Boats, minecarts, armor stands, item frames, paintings and the + /// entities kept unsimulated, as guests track them. + pub(super) fn lan_object_states( + &self, + host_entity: Option, + hub: &mut Hub, + out: &mut Vec, + ) { + for b in &self.boats { + let p = b.position; + let mut e = state(b.id, &b.entity_type(), [p.x, p.y, p.z], b.yaw, b.on_ground); + e.velocity = [b.velocity.x, b.velocity.y, b.velocity.z]; + e.meta = vehicle_meta(b.hurt_time, b.hurt_dir, b.damage); + // AbstractBoat.DATA_ID_PADDLE_LEFT and DATA_ID_PADDLE_RIGHT. + for (k, paddling) in b.paddling.iter().enumerate() { + if *paddling { + e.meta + .push((11 + k as u8, serializer::BOOLEAN, Value::Bool(true))); + } + } + out.push(e); + } + for c in &self.carts { + let p = c.position; + let mut e = state(c.id, c.kind.id(), [p.x, p.y, p.z], c.yaw, c.on_ground()); + e.velocity = [c.velocity.x, c.velocity.y, c.velocity.z]; + e.meta = vehicle_meta(c.hurt_time, c.hurt_dir, c.damage); + match c.kind { + // MinecartFurnace.DATA_ID_FUEL. + super::minecarts::CartKind::Furnace if c.fuel > 0 => { + e.meta.push((13, serializer::BOOLEAN, Value::Bool(true))); + } + // MinecartCommandBlock.DATA_ID_COMMAND_NAME. + super::minecarts::CartKind::CommandBlock => { + if let Some(Tag::String(command)) = + self.persist.raw.get(&c.id).and_then(|t| t.get("Command")) + { + let command = command.to_string_lossy(); + if !command.is_empty() { + e.meta + .push((13, serializer::STRING, Value::String(command))); + } + } + } + _ => {} + } + out.push(e); + } + for a in &self.armor_stands { + let p = a.position; + let mut e = state( + a.id, + "minecraft:armor_stand", + [p.x, p.y, p.z], + a.yaw, + a.on_ground, + ); + e.head_yaw = a.yaw; + e.velocity = [a.velocity.x, a.velocity.y, a.velocity.z]; + if a.fire_ticks > 0 { + e.meta.push((0, serializer::BYTE, Value::Byte(1))); + } + // LivingEntity.DATA_HEALTH_ID: 1 until the stand's max health is set. + e.meta.push((9, serializer::FLOAT, Value::Float(a.health))); + // ArmorStand.DATA_CLIENT_FLAGS: small 1, arms 4, no base plate 8, marker 16. + let flags = i8::from(a.small) + | i8::from(a.show_arms) << 2 + | i8::from(a.no_base_plate) << 3 + | i8::from(a.marker) << 4; + if flags != 0 { + e.meta.push((15, serializer::BYTE, Value::Byte(flags))); + } + e.meta.extend(stand_poses(self.persist.raw.get(&a.id))); + // Stored main hand, off hand, feet, legs, chest, head: the wire's slots 0 to 5. + for (slot, item) in a.equipment.iter().enumerate() { + if item.is_some() { + e.equipment.push((slot as u8, hub.stack(item))); + } + } + out.push(e); + } + for f in &self.item_frames { + // ItemFrame.getAddEntityPacket: the block it hangs in and its direction. + let mut e = state(f.id, f.kind(), f.pos.map(f64::from), 0.0, false); + e.pitch = match f.facing { + 0 => 90.0, + 1 => -90.0, + _ => 0.0, + }; + e.yaw = match f.facing { + 2 => 180.0, + 4 => 90.0, + 5 => 270.0, + _ => 0.0, + }; + e.data = i32::from(f.facing); + // HangingEntity.DATA_DIRECTION, south by default. + if f.facing != 3 { + e.meta + .push((8, serializer::DIRECTION, Value::Id(i32::from(f.facing)))); + } + if f.item.is_some() { + e.meta + .push((9, serializer::ITEM_STACK, Value::Item(hub.stack(&f.item)))); + } + if f.rotation != 0 { + e.meta + .push((10, serializer::INT, Value::Int(i32::from(f.rotation)))); + } + out.push(e); + } + for p in &self.paintings { + let mut e = state(p.id, "minecraft:painting", p.pos.map(f64::from), 0.0, false); + // Direction.get2DDataValue (south 0, west 1, north 2, east 3) to its + // 3D data value and yaw. + let facing = [3, 4, 2, 5][usize::from(p.facing & 3)]; + e.yaw = f32::from(p.facing & 3) * 90.0; + e.data = facing; + if facing != 3 { + e.meta.push((8, serializer::DIRECTION, Value::Id(facing))); + } + // Painting.DATA_PAINTING_VARIANT_ID, a registry holder (id + 1), + // set unless it is the registry's first variant (VariantUtils.getAny). + if let Some(id) = hub.registry_id("minecraft:painting_variant", &p.variant) + && id != 0 + { + e.meta + .push((9, serializer::PAINTING_VARIANT, Value::Id(id + 1))); + } + out.push(e); + } + self.lan_projectile_states(host_entity, hub, out); + for o in &self.others { + let p = o.position; + let mut e = state(o.id, &o.kind, [p.x, p.y, p.z], o.yaw, false); + e.pitch = o.pitch; + e.head_yaw = o.yaw; + out.push(e); + } + } +} + +impl Game<'_> { + /// Gives the entities Horizon keeps without an id one (`Entity.id`, from + /// the same counter as the rest) before they are first tracked. + pub(super) fn lan_assign_ids(&mut self) { + let next = &mut self.next_entity; + let mut give = |id: &mut u32| { + if *id == 0 { + *next += 1; + *id = *next; + } + }; + self.tnts.iter_mut().for_each(|t| give(&mut t.id)); + self.falling.iter_mut().for_each(|f| give(&mut f.id)); + self.creatures + .projectiles + .iter_mut() + .for_each(|p| give(&mut p.id)); + self.tridents.iter_mut().for_each(|t| give(&mut t.id)); + self.rockets.iter_mut().for_each(|r| give(&mut r.id)); + self.crystals.iter_mut().for_each(|c| give(&mut c.id)); + } + + /// Primed TNT, falling blocks, projectiles, tridents, firework rockets and + /// end crystals, as guests track them. + fn lan_projectile_states( + &self, + host_entity: Option, + hub: &mut Hub, + out: &mut Vec, + ) { + let owner = |who: Option| match who { + Some(horizon_client::mobs::Who::Mob(id)) => id as i32, + Some(horizon_client::mobs::Who::Player) => host_entity.unwrap_or(0), + None => 0, + }; + let at = |p: horizon_core::geometry::Vec3| [p.x, p.y, p.z]; + for t in self.tnts.iter().filter(|t| t.id != 0) { + let mut e = state(t.id, "minecraft:tnt", at(t.position), 0.0, t.on_ground); + e.velocity = at(t.velocity); + // PrimedTnt.DATA_FUSE_ID, 80 by default; requiresPrecisePosition + // while it touches a block. + if t.fuse != 80 { + e.meta.push((8, serializer::INT, Value::Int(t.fuse))); + } + e.precise = t.on_ground; + out.push(e); + } + for f in self.falling.iter().filter(|f| f.id != 0) { + let mut e = state(f.id, "minecraft:falling_block", at(f.position), 0.0, false); + e.velocity = at(f.velocity); + // getAddEntityPacket: the block state; DATA_START_POS. + e.data = f.state.0 as i32; + if f.no_gravity { + e.meta.push((5, serializer::BOOLEAN, Value::Bool(true))); + } + let start = [f.start_pos.x, f.start_pos.y, f.start_pos.z]; + if start != [0; 3] { + e.meta.push((8, serializer::BLOCK_POS, Value::Pos(start))); + } + out.push(e); + } + for p in self.creatures.projectiles.iter().filter(|p| p.id != 0) { + use horizon_client::projectiles::ProjectileKind as K; + let kind = match &p.kind { + K::Arrow { .. } => "minecraft:arrow", + K::Snowball => "minecraft:snowball", + K::Egg => "minecraft:egg", + K::EnderPearl => "minecraft:ender_pearl", + K::SmallFireball => "minecraft:small_fireball", + K::LargeFireball { .. } => "minecraft:fireball", + K::LlamaSpit => "minecraft:llama_spit", + K::WindCharge => "minecraft:wind_charge", + K::BreezeWindCharge => "minecraft:breeze_wind_charge", + K::ShulkerBullet { .. } => "minecraft:shulker_bullet", + K::WitherSkull { .. } => "minecraft:wither_skull", + K::Potion { .. } => "minecraft:splash_potion", + }; + let mut e = state(p.id, kind, at(p.position), p.yaw, false); + e.pitch = p.pitch; + e.velocity = at(p.velocity); + e.data = owner(p.owner); + match &p.kind { + K::Arrow { critical, .. } => { + let a = p.arrow.as_deref(); + e.meta.extend(arrow_meta( + *critical, + a.is_some_and(|a| a.no_physics), + a.map_or(0, |a| a.pierce), + a.is_some_and(|a| a.in_ground) || p.stuck, + )); + } + // WitherSkull.DATA_DANGEROUS. + K::WitherSkull { dangerous: true } => { + e.meta.push((8, serializer::BOOLEAN, Value::Bool(true))); + } + _ => {} + } + out.push(e); + } + for t in self.tridents.iter().filter(|t| t.id != 0) { + let mut e = state(t.id, "minecraft:trident", at(t.position), t.yaw, false); + e.pitch = t.pitch; + e.velocity = at(t.velocity); + e.meta = arrow_meta(false, t.no_physics, 0, t.in_ground); + // ThrownTrident.ID_LOYALTY and ID_FOIL. + if t.loyalty != 0 { + e.meta + .push((11, serializer::BYTE, Value::Byte(t.loyalty as i8))); + } + if t.stack.has_any_enchantments() { + e.meta.push((12, serializer::BOOLEAN, Value::Bool(true))); + } + out.push(e); + } + for r in self.rockets.iter().filter(|r| r.id != 0) { + let mut e = state( + r.id, + "minecraft:firework_rocket", + at(r.position), + 0.0, + false, + ); + e.velocity = at(r.velocity); + // DATA_ID_FIREWORKS_ITEM once set from a stack, DATA_ATTACHED_TO_TARGET, + // DATA_SHOT_AT_ANGLE. + let plain = &*r.item.item == "minecraft:firework_rocket" + && r.item.count == 1 + && r.item.extra.is_none(); + if !plain { + e.meta.push(( + 8, + serializer::ITEM_STACK, + Value::Item(hub.stack(&Some(r.item.clone()))), + )); + } + if r.attached + && let Some(host) = host_entity + { + e.meta + .push((9, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(host + 1))); + } + if r.angled { + e.meta.push((10, serializer::BOOLEAN, Value::Bool(true))); + } + out.push(e); + } + for c in self.crystals.iter().filter(|c| c.id != 0) { + let mut e = state(c.id, "minecraft:end_crystal", at(c.position), 0.0, false); + // EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM (true by default). + if c.beam.is_some() { + e.meta + .push((8, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(c.beam))); + } + if !c.show_bottom { + e.meta.push((9, serializer::BOOLEAN, Value::Bool(false))); + } + out.push(e); + } + } +} + +/// `AbstractArrow`'s ID_FLAGS (critical 1, no physics 2), PIERCE_LEVEL and +/// IN_GROUND, when they differ from the defaults. +fn arrow_meta( + critical: bool, + no_physics: bool, + pierce: u8, + in_ground: bool, +) -> Vec<(u8, i32, Value)> { + let mut meta = Vec::new(); + let flags = i8::from(critical) | i8::from(no_physics) << 1; + if flags != 0 { + meta.push((8, serializer::BYTE, Value::Byte(flags))); + } + if pierce != 0 { + meta.push((9, serializer::BYTE, Value::Byte(pierce as i8))); + } + if in_ground { + meta.push((10, serializer::BOOLEAN, Value::Bool(true))); + } + meta +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn armor_stand_poses_send_only_what_differs() { + let tag = + horizon_world::nbt::parse_snbt("{Pose:{Head:[10f,20f,0f],LeftArm:[-10f,0f,-10f]}}") + .unwrap() + .0; + let meta = stand_poses(Some(&tag)); + assert_eq!( + meta, + vec![( + 16, + serializer::ROTATIONS, + Value::Floats(vec![10.0, 20.0, 0.0]) + )] + ); + assert!(stand_poses(None).is_empty()); + } +} diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 7cef7cda6..99888058c 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -92,7 +92,7 @@ impl Game<'_> { .hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead) .map(|g| { let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); (g.conn, g.uuid, moved) @@ -107,6 +107,7 @@ impl Game<'_> { v.velocity = Vec3::new(moved[0], moved[1], moved[2]); v.uuid = horizon_client::lan::playerdata::uuid_ints(uuid); v.allies = Default::default(); + v.remote = true; views.push((conn, v)); } } @@ -138,7 +139,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .map(|g| (Who::Mob(g.entity_id as u32), guest_bounds(g))) .collect() } @@ -209,9 +210,12 @@ pub(super) struct Present { impl Game<'_> { /// Every guest in the world (`ServerLevel.getPlayers` past the host). pub(super) fn lan_present(&self) -> Vec { - let guests = self.lan.iter().flat_map(|h| &h.hub.guests); + let guests = self + .lan + .iter() + .flat_map(|h| h.hub.guests.iter().filter(|g| h.hub.here(g))); guests - .filter(|g| g.placed && g.loaded) + .filter(|g| g.loaded) .map(|g| { let [x, y, z] = g.position; Present { @@ -271,6 +275,7 @@ mod tests { hero: false, uuid: [0; 4], allies: Default::default(), + remote: false, } } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index bd10241ff..1bdf9146a 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -32,7 +32,7 @@ impl Game<'_> { host.hub .guests .iter() - .filter(|g| g.placed && g.loaded && !g.dead && !g.spectator()) + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) .filter_map(|g| Some((g.conn, ray_box(eye, dir, reach, guest_bounds(g))?))) .min_by(|a, b| a.1.total_cmp(&b.1)) } @@ -64,7 +64,7 @@ impl Game<'_> { host.hub .guests .iter() - .find(|g| g.entity_id == id && g.conn != conn && g.placed && !g.dead) + .find(|g| g.entity_id == id && g.conn != conn && host.hub.here(g) && !g.dead) .map(|g| Victim::Guest(g.conn)) } diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index d6bfc4141..ee6b55d16 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -372,7 +372,7 @@ impl Game<'_> { .hub .guests .iter() - .find(|g| g.conn == conn) + .find(|g| g.conn == conn && host.hub.here(g)) .map(|g| uuid_words(g.uuid)) else { continue; diff --git a/crates/horizon-client/src/game/lan_waypoints.rs b/crates/horizon-client/src/game/lan_waypoints.rs new file mode 100644 index 000000000..0d0ab69e4 --- /dev/null +++ b/crates/horizon-client/src/game/lan_waypoints.rs @@ -0,0 +1,95 @@ +//! The locator bar of the players on a served world (lan/waypoints.rs): what +//! each player looks like to the waypoint manager this tick. +use super::{Game, lan::LanHost}; +use horizon_client::{ + items::ItemStack, + lan::{ + hub::HostState, + waypoints::{self, HIDING_HEADS, Icon, PLAYER_RANGE}, + }, +}; + +/// `waypoint_transmit_range`: hidden by crouching, invisibility or a head worn. +fn transmit_range(crouching: bool, invisible: bool, head: Option<&ItemStack>) -> f64 { + let hiding_head = head.is_some_and(|s| HIDING_HEADS.contains(&&*s.item)); + if crouching || invisible || hiding_head { + 0.0 + } else { + PLAYER_RANGE + } +} + +impl Game<'_> { + /// The player's team and its colour, as the locator bar shows it. + fn waypoint_team(&self, name: &str) -> Option<(String, Option)> { + let team = self.score.board.players_team(name)?; + let color = team.color.as_deref().and_then(waypoints::team_rgb); + Some((team.name.clone(), color)) + } + + pub(super) fn lan_update_waypoints(&mut self, host: &mut LanHost, state: Option<&HostState>) { + let mut players = Vec::new(); + if let Some(h) = state { + let icon = self + .cmds + .waypoint_icons + .get(&super::commands::Target::Player) + .map(|i| Icon { + style: i.style.clone(), + color: i.color, + }) + .unwrap_or_default(); + players.push(waypoints::Player { + uuid: h.uuid, + conn: None, + position: h.position, + spectator: self.spectator(), + transmit_range: transmit_range( + h.sneaking, + self.potions.effects.get("invisibility").is_some(), + h.equipment[5].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: false, + view_distance: host.hub.config.view_distance, + team: self.waypoint_team(&h.name), + icon, + }); + } + let mut respawned = Vec::new(); + for g in host.hub.guests.iter().filter(|g| g.placed) { + // PlayerList.respawn makes a new ServerPlayer. + if g.dead { + host.waypoint_dead.insert(g.uuid); + } else if host.waypoint_dead.remove(&g.uuid) { + respawned.push(g.uuid); + } + // Player.updatePlayerPose: the shift key crouches unless flying. + let crouching = g.sneaking && !g.flying && !g.fall_flying && !g.sleeping; + players.push(waypoints::Player { + uuid: g.uuid, + conn: Some(g.conn), + position: g.position, + spectator: g.spectator(), + transmit_range: transmit_range( + crouching, + g.effects.get("invisibility").is_some(), + g.armor[0].as_ref(), + ), + receive_range: PLAYER_RANGE, + first_tick: g.ticks == 0, + view_distance: g.view_distance, + team: self.waypoint_team(&g.name), + icon: Icon::default(), + }); + } + host.waypoint_dead + .retain(|uuid| players.iter().any(|p| p.uuid == *uuid)); + let locator_bar = self.ui.rules.bool("locator_bar"); + for (conn, packet) in host.waypoints.tick(&players, &respawned, locator_bar) { + if let Some(g) = host.hub.guest(conn) { + g.send(&packet); + } + } + } +} diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs new file mode 100644 index 000000000..3a84e2f78 --- /dev/null +++ b/crates/horizon-client/src/game/levels.rs @@ -0,0 +1,350 @@ +//! A server's levels, one per dimension (`MinecraftServer.levels`). +//! +//! The game's tick code reads one level: the one in place, held in `Game`'s +//! own fields (the world, its streaming and save, block ticks, entities). +//! A server (the dedicated server and single player's server thread) keeps +//! the other dimensions' levels here and ticks each one that has players by +//! swapping it into place (`enter_level`), the way `as_guest` swaps a player +//! in, so the tick code runs unchanged, one level at a time. The in-frame +//! game holds one level, which follows its player (`enter_dimension`). +//! +//! Shared by every level, as vanilla's derived levels share the +//! Overworld's level data: the game time, the day time and the weather, the +//! game rules, the scoreboard, the maps and the entities waiting to arrive +//! through a portal. + +use super::{ + Dim, ExperienceOrb, FallingBlock, Game, ItemEntity, Mob, boats, commands, + creaking::CreakingState, dragon, fireworks, lan::LanHost, lightning, machines, minecarts, + ominous_item_spawner, persist, raids::Raiding, sculk::SculkState, tnt, trident, +}; +use horizon_client::{ + Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, +}; +use horizon_world::level::{LevelEvent, Ticks}; +use std::{collections::HashMap, sync::Arc}; + +/// Server ticks a level other than the Overworld stays loaded with no player +/// in it, before it is saved and closed (vanilla unloads a level's chunks +/// once no ticket holds them; the Overworld stays loaded). +const IDLE_TICKS: u32 = 300; + +/// A level that is not in place: every per-level field of `Game`. +pub(super) struct Parked { + world: World, + streaming: Streaming, + save: Arc, + block_ticks: Ticks, + tick_chunks: TickChunkMembership, + random_tick_sections: RandomTickSections, + level_events: Vec, + falling: Vec, + paintings: Vec, + item_frames: Vec, + armor_stands: Vec, + others: Vec, + boats: Vec, + carts: Vec, + jukebox_sounds: HashMap<(i32, i32, i32), u64>, + bolts: Vec, + crystals: Vec, + dragon: Option, + dragon_fireballs: Vec, + breath_clouds: Vec, + tridents: Vec, + rockets: Vec, + ominous_spawners: Vec, + tnts: Vec, + hoppers: HashMap<(i32, i32, i32), machines::HopperState>, + mobs: Vec, + projectiles: Vec, + dropped: Vec, + orbs: Vec, + persist: persist::EntityMemory, + lectern_pulses: Vec<((i32, i32, i32), i32)>, + lid_openers: HashMap<(i32, i32, i32), i32>, + lan_events: Vec<(i32, [i32; 3], i32, Option)>, + lan_block_events: Vec<([i32; 3], i32, i32, u32)>, + lan_entity_events: Vec<(i32, i8, [f64; 3])>, + /// Only the per-level parts of these are used (`swap_level`). + anims: BlockEntityAnims, + raiding: Raiding, + sculk: SculkState, + creaking: CreakingState, + /// Server ticks since a player was last in the level. + idle: u32, +} + +/// Which passes of the server tick the level in place runs: the first +/// reads the network (`Hub::poll`), the last ends the tick for every player +/// (`Hub::end_tick`). A tick with one level is both. +#[derive(Clone, Copy)] +pub(super) struct Pass { + pub first: bool, + pub last: bool, +} + +impl Default for Pass { + fn default() -> Self { + Self { + first: true, + last: true, + } + } +} + +/// The levels not in place, by dimension. +#[derive(Default)] +pub(super) struct Levels { + parked: HashMap, +} + +impl Game<'_> { + /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). + fn open_level(&self, dim: Dim) -> Result { + let (streaming, save) = + self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?; + let mut world = World::new(self.res.facts.air, self.level.seed); + world.fast_lava = dim == Dim::Nether; + Ok(Parked { + world, + streaming, + save, + block_ticks: Ticks::new(self.level.seed as i32), + tick_chunks: Default::default(), + random_tick_sections: Default::default(), + level_events: Vec::new(), + falling: Vec::new(), + paintings: Vec::new(), + item_frames: Vec::new(), + armor_stands: Vec::new(), + others: Vec::new(), + boats: Vec::new(), + carts: Vec::new(), + jukebox_sounds: HashMap::new(), + bolts: Vec::new(), + crystals: Vec::new(), + dragon: None, + dragon_fireballs: Vec::new(), + breath_clouds: Vec::new(), + tridents: Vec::new(), + rockets: Vec::new(), + ominous_spawners: Vec::new(), + tnts: Vec::new(), + hoppers: HashMap::new(), + mobs: Vec::new(), + projectiles: Vec::new(), + dropped: Vec::new(), + orbs: Vec::new(), + persist: Default::default(), + lectern_pulses: Vec::new(), + lid_openers: HashMap::new(), + lan_events: Vec::new(), + lan_block_events: Vec::new(), + lan_entity_events: Vec::new(), + anims: Default::default(), + raiding: Default::default(), + sculk: Default::default(), + creaking: Default::default(), + idle: 0, + }) + } + + /// Exchange the level in place with `p`. + fn swap_level(&mut self, p: &mut Parked) { + use std::mem::swap; + swap(&mut self.world, &mut p.world); + swap(&mut self.streaming, &mut p.streaming); + swap(&mut self.save, &mut p.save); + swap(&mut self.block_ticks, &mut p.block_ticks); + swap(&mut self.tick_chunks, &mut p.tick_chunks); + swap(&mut self.random_tick_sections, &mut p.random_tick_sections); + swap(&mut self.level_events, &mut p.level_events); + swap(&mut self.falling, &mut p.falling); + swap(&mut self.paintings, &mut p.paintings); + swap(&mut self.item_frames, &mut p.item_frames); + swap(&mut self.armor_stands, &mut p.armor_stands); + swap(&mut self.others, &mut p.others); + swap(&mut self.boats, &mut p.boats); + swap(&mut self.carts, &mut p.carts); + swap(&mut self.jukebox_sounds, &mut p.jukebox_sounds); + swap(&mut self.bolts, &mut p.bolts); + swap(&mut self.crystals, &mut p.crystals); + swap(&mut self.dragon, &mut p.dragon); + swap(&mut self.dragon_fireballs, &mut p.dragon_fireballs); + swap(&mut self.breath_clouds, &mut p.breath_clouds); + swap(&mut self.tridents, &mut p.tridents); + swap(&mut self.rockets, &mut p.rockets); + swap(&mut self.ominous_spawners, &mut p.ominous_spawners); + swap(&mut self.tnts, &mut p.tnts); + swap(&mut self.hoppers, &mut p.hoppers); + swap(&mut self.mobs, &mut p.mobs); + swap(&mut self.creatures.projectiles, &mut p.projectiles); + swap(&mut self.dropped, &mut p.dropped); + swap(&mut self.orbs, &mut p.orbs); + swap(&mut self.persist, &mut p.persist); + swap(&mut self.lectern_pulses, &mut p.lectern_pulses); + swap(&mut self.lid_openers, &mut p.lid_openers); + swap(&mut self.lan_events, &mut p.lan_events); + swap(&mut self.lan_block_events, &mut p.lan_block_events); + swap(&mut self.lan_entity_events, &mut p.lan_entity_events); + let (a, b) = (&mut self.be_anims, &mut p.anims); + swap(&mut a.chests, &mut b.chests); + swap(&mut a.books, &mut b.books); + swap(&mut a.shulkers, &mut b.shulkers); + swap(&mut a.bells, &mut b.bells); + swap(&mut a.conduits, &mut b.conduits); + swap(&mut a.skulls, &mut b.skulls); + swap(&mut a.pots, &mut b.pots); + swap(&mut a.gateways, &mut b.gateways); + swap(&mut a.gateway_servers, &mut b.gateway_servers); + self.raiding.swap_level(&mut p.raiding); + self.sculk.swap_level(&mut p.sculk); + self.creaking.swap_level(&mut p.creaking); + // What only the client draws starts over. + self.particles.clear(); + self.pickups.clear(); + } + + /// Put `target`'s level in place, opening it first if it is not loaded. + /// The level that was in place is kept with the others; the shared + /// clock and weather go with the swap. `host` is the hub when the caller + /// holds it (`self.lan` is taken during the network tick). + pub(super) fn enter_level(&mut self, host: Option<&mut LanHost>, target: Dim) -> Result<()> { + // The in-frame game keeps its one level (`enter_dimension`). + if self.options.dedicated.is_none() { + return Ok(()); + } + if target != self.dim { + let (mut p, opened) = match self.levels.parked.remove(&target) { + Some(p) => (p, false), + None => (self.open_level(target)?, true), + }; + p.world.game_time = self.world.game_time; + p.world.day_time = self.world.day_time; + p.world.weather = self.world.weather; + // The sculk tables' watched blocks are built once per game. + p.world.watched = std::mem::take(&mut self.world.watched); + self.swap_level(&mut p); + p.idle = 0; + let left = std::mem::replace(&mut self.dim, target); + self.levels.parked.insert(left, p); + if opened { + // The new streaming's radius and meshing options. + self.apply_settings(); + } + } + let host = match host { + Some(h) => Some(h), + None => self.lan.as_mut(), + }; + if let Some(h) = host { + h.hub.set_dimension(target.id()); + } + Ok(()) + } + + /// One server tick (`MinecraftServer.tickServer`): each level with + /// players in turn (`tickChildren`), its chunks streamed and loaded and + /// its world ticked. The first pass reads the network and runs the + /// tick's shared parts (the clock, the weather, functions, the autosave); + /// the next ones only their level. While `paused`, only the connections + /// run. + pub(super) fn tick_server(&mut self, paused: bool) -> Result<()> { + let dims = self.levels_to_tick(); + let n = dims.len(); + let mut result = Ok(()); + for (k, dim) in dims.into_iter().enumerate() { + if let Err(e) = self.enter_level(None, dim) { + result = Err(e); + break; + } + self.level_pass = Pass { + first: k == 0, + last: k + 1 == n, + }; + self.update_dedicated_streaming(); + self.update_world(); + result = if paused { + self.tick_lan(); + Ok(()) + } else if k == 0 { + self.tick() + } else { + let running = self.clock.world_runs(); + if running { + self.tick_weather_effects(); + } + self.tick_world(running) + }; + if result.is_err() { + break; + } + } + self.level_pass = Pass::default(); + result?; + self.close_idle_levels() + } + + /// The levels this server tick runs, in `MinecraftServer.levels` order + /// (the Overworld, the Nether, the End): every level with a player in + /// it, or the Overworld while nobody is online. + pub(super) fn levels_to_tick(&self) -> Vec { + let guests = self + .lan + .as_ref() + .map_or(&[][..], |h| h.hub.guests.as_slice()); + let mut dims: Vec = [Dim::Overworld, Dim::Nether, Dim::End] + .into_iter() + .filter(|d| guests.iter().any(|g| g.dimension == d.id())) + .collect(); + if dims.is_empty() { + dims.push(Dim::Overworld); + } + dims + } + + /// Count the parked levels' empty ticks, and save and close the ones + /// (other than the Overworld) nobody has been in for a while. + pub(super) fn close_idle_levels(&mut self) -> Result<()> { + let occupied = self.levels_to_tick(); + let mut closing = Vec::new(); + for (dim, p) in &mut self.levels.parked { + if occupied.contains(dim) { + p.idle = 0; + continue; + } + p.idle += 1; + if *dim != Dim::Overworld && p.idle >= IDLE_TICKS { + closing.push(*dim); + } + } + if closing.is_empty() { + return Ok(()); + } + let back = self.dim; + for dim in closing { + self.enter_level(None, dim)?; + self.save_level(true)?; + self.enter_level(None, back)?; + self.levels.parked.remove(&dim); + } + Ok(()) + } + + /// Save every parked level (`MinecraftServer.saveAllChunks`); the level + /// in place is the caller's to save. + pub(super) fn save_parked_levels(&mut self, wait: bool) -> Result<()> { + if self.levels.parked.is_empty() { + return Ok(()); + } + let back = self.dim; + let dims: Vec = self.levels.parked.keys().copied().collect(); + for dim in dims { + self.enter_level(None, dim)?; + self.save_level(wait)?; + } + self.enter_level(None, back) + } +} diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index 0d334d248..d46928060 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -7,7 +7,7 @@ use super::Game; mod crafter; use horizon_client::{ Result, - containers::BlockEntity, + containers::{BlockEntity, HOPPER_SLOTS}, items::{ItemStack, Items}, world::World, }; @@ -497,36 +497,35 @@ impl Game<'_> { } } } - /// Every hopper's `pushItemsTick`, in a stable position order. - pub(super) fn tick_hoppers(&mut self) -> Result<()> { + /// `HopperBlockEntity.pushItemsTick` of the hopper at `pos`, if its block + /// is still a hopper (`BlockEntityType.isValid`). + pub(super) fn tick_hopper(&mut self, pos: Pos) { let hopper = self - .pack - .assets - .registry - .default_state("minecraft:hopper") - .map(|s| self.res.facts.get(s).name.clone()); - let Some(hopper) = hopper else { return Ok(()) }; - let mut positions: Vec = self - .world - .block_entities - .keys() - .copied() - .filter(|p| self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == hopper) - .collect(); - positions.sort_unstable(); - self.hoppers - .retain(|p, _| positions.binary_search(p).is_ok()); - let time = self.world.game_time; - for pos in positions { - let state = self.hoppers.entry(pos).or_default(); - state.cooldown -= 1; - state.ticked = time; - if state.cooldown <= 0 { - state.cooldown = 0; - self.hopper_try_move_items(pos); - } + .res + .facts + .get(self.world.block(pos.0, pos.1, pos.2)) + .name + .as_ref() + == "minecraft:hopper"; + if !hopper { + self.hoppers.remove(&pos); + return; } - Ok(()) + let time = self.world.game_time; + let state = self.hoppers.entry(pos).or_default(); + state.cooldown -= 1; + state.ticked = time; + if state.cooldown <= 0 { + state.cooldown = 0; + self.hopper_try_move_items(pos); + } + } + /// Drops the cooldowns of hoppers whose block entity is gone. + pub(super) fn forget_gone_hoppers(&mut self) { + let entities = &self.world.block_entities; + self.hoppers.retain(|p, _| { + matches!(entities.get(p), Some(BlockEntity::Chest(items)) if items.len() == HOPPER_SLOTS) + }); } /// `HopperBlockEntity.tryMoveItems` with `suckInItems`. pub(super) fn hopper_try_move_items(&mut self, pos: Pos) { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 11ca70d5d..5642e5c2a 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -56,44 +56,33 @@ impl Game<'_> { _ => None, } } - /// `CrafterBlockEntity.serverTick` for every crafter, and the powered - /// flag following the block state. - pub(in crate::game) fn tick_crafters(&mut self) { - let positions: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Crafter(_))) - .map(|(p, _)| *p) - .collect(); - let mut positions = positions; - positions.sort_unstable(); - for pos in positions { - let state = self.world.block(pos.0, pos.1, pos.2); - let triggered = self.containers().prop(state, "triggered") == Some("true"); - let mut finished = false; - if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) { - // CrafterBlock.neighborChanged sets the flag with the state; a - // loaded crafter keeps its saved flag until then. - if c.state_triggered.is_some_and(|t| t != triggered) { - c.triggered = triggered; - } - c.state_triggered = Some(triggered); - let remaining = c.crafting_ticks - 1; - if remaining >= 0 { - c.crafting_ticks = remaining; - finished = remaining == 0; - } + /// `CrafterBlockEntity.serverTick` of the crafter at `pos`, and the + /// powered flag following the block state. + pub(in crate::game) fn tick_crafter(&mut self, pos: Pos) { + let state = self.world.block(pos.0, pos.1, pos.2); + let triggered = self.containers().prop(state, "triggered") == Some("true"); + let mut finished = false; + if let Some(BlockEntity::Crafter(c)) = self.world.block_entities.get_mut(&pos) { + // CrafterBlock.neighborChanged sets the flag with the state; a + // loaded crafter keeps its saved flag until then. + if c.state_triggered.is_some_and(|t| t != triggered) { + c.triggered = triggered; } - if finished { - self.set_bool_prop( - pos, - "crafting", - false, - horizon_world::level::flags::UPDATE_ALL, - ); + c.state_triggered = Some(triggered); + let remaining = c.crafting_ticks - 1; + if remaining >= 0 { + c.crafting_ticks = remaining; + finished = remaining == 0; } } + if finished { + self.set_bool_prop( + pos, + "crafting", + false, + horizon_world::level::flags::UPDATE_ALL, + ); + } } /// `CrafterBlock.dispenseFrom` (the scheduled tick after a redstone pulse). pub(super) fn crafter_dispense(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index de42c4907..1e0b42b50 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -17,7 +17,6 @@ use horizon_client::{ }; use horizon_core::{ geometry::{Aabb, Vec3}, - position::BlockPos, random::RandomSource, }; use horizon_world::registry::BlockStateId; @@ -91,6 +90,10 @@ pub(super) struct Minecart { } const WIDTH: f64 = 0.98; const HEIGHT: f64 = 0.7; +/// AbstractMinecart.getDefaultDisplayOffset, in sixteenths of a block. +fn display_offset(kind: CartKind) -> f64 { + if kind == CartKind::Hopper { 1.0 } else { 6.0 } +} /// The minecart's passenger attachment minus Player.DEFAULT_VEHICLE_ATTACHMENT. const SEAT: f64 = 0.1875 - 0.6; /// The placeholder container key under which an open cart's items live. @@ -154,6 +157,10 @@ pub(super) struct Rail { powered: bool, } impl Minecart { + /// `Entity.onGround`. + pub(super) fn on_ground(&self) -> bool { + self.on_ground + } pub fn new(id: u32, kind: CartKind, position: Vec3) -> Self { Self { id, @@ -1139,16 +1146,17 @@ impl Game<'_> { } } } - /// A block model's faces under `m` (block space 0..1), lit flat. + /// Baked block faces with terrain shade or block-item diffuse lighting. pub(super) fn block_model_vertices( &self, state: BlockStateId, - seed_pos: BlockPos, + seed: i64, m: glam::Mat4, light: u32, + diffuse: bool, out: &mut Vec, ) { - let Ok(models) = self.pack.assets.model_catalog.collect(state, seed_pos) else { + let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else { return; }; for (_, model) in &models { @@ -1168,12 +1176,30 @@ impl Game<'_> { D::North | D::South => 204, D::West | D::East => 153, }; - let color = 0xFF00_0000 | shade << 16 | shade << 8 | shade; + let color = if diffuse { + u32::MAX + } else { + 0xFF00_0000 | shade << 16 | shade << 8 | shade + }; + let normal = if diffuse { + use horizon_client::item_render::{direction_vector, transform_normal}; + let n = transform_normal(m, direction_vector(face.quad.facing)); + let n = n.to_array().map(|v| (v.clamp(-1.0, 1.0) * 127.0) as i8); + [n[0], n[1], n[2], 127] + } else { + [0; 4] + }; + let light = if diffuse { + let emission = u32::from(face.quad.light_emission) * 16; + (light & 0xFF) | (light >> 8 & 0xFF).max(emission) << 8 + } else { + light + }; for k in 0..4 { let p = face.quad.positions[k]; let uv = face.quad.uv[k]; out.push(Vertex { - normal: [0; 4], + normal, pos: m.transform_point3(glam::Vec3::from_array(p)).to_array(), uv: [s.u0 + uv[0] * (s.u1 - s.u0), s.v0 + uv[1] * (s.v1 - s.v0)], layer: 0, @@ -1212,24 +1238,52 @@ impl Game<'_> { /// front and back points, pitched on slopes, with the display block. pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; + let Some(uv) = self + .atlas + .sprites + .get("entity/minecart/minecart") + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + else { + return; + }; + // Entity.shouldRenderAtSqrDistance: 64 times the bounding box's mean + // edge, scaled by the entity distance option. + let range = + (WIDTH + HEIGHT + WIDTH) / 3.0 * 64.0 * f64::from(self.settings.entity_distance); for c in &self.carts { let entity_start = out.len(); let Some(model) = self.cart_models.models.get(&c.kind) else { continue; }; - let Some(uv) = self - .atlas - .sprites - .get("entity/minecart/minecart") - .map(|r| [r.u0, r.v0, r.u1, r.v1]) - else { - continue; - }; let (x, y, z) = ( c.previous.x + (c.position.x - c.previous.x) * alpha, c.previous.y + (c.position.y - c.previous.y) * alpha, c.previous.z + (c.position.z - c.previous.z) * alpha, ); + // LevelExtractor.isEntityVisible: the cart the player rides always draws. + if self.riding != Some(c.id) { + let d = glam::DVec3::new(c.position.x, c.position.y, c.position.z) - camera; + if d.length_squared() >= range * range { + continue; + } + // EntityRenderer.shouldRender: the interpolated box grown by 0.5; + // AbstractMinecartRenderer.getBoundingBoxForCulling stretches it + // up by the display block's offset. + if let Some(view) = &self.view_frustum { + let top = HEIGHT + + if c.kind == CartKind::Rideable { + 0.0 + } else { + display_offset(c.kind) * 0.75 / 16.0 + }; + let p = glam::DVec3::new(x, y, z) - camera; + let lo = p - glam::DVec3::new(WIDTH / 2.0 + 0.5, 0.5, WIDTH / 2.0 + 0.5); + let hi = p + glam::DVec3::new(WIDTH / 2.0 + 0.5, top + 0.5, WIDTH / 2.0 + 0.5); + if !view.intersects(lo.as_vec3(), hi.as_vec3()) { + continue; + } + } + } let mut yaw = c.previous_yaw + ((c.yaw - c.previous_yaw + 180.0).rem_euclid(360.0) - 180.0) * a; let mut pitch = 0.0f32; @@ -1274,7 +1328,11 @@ impl Game<'_> { if let Some(state) = self.display_state(c) { let display = base * glam::Mat4::from_scale(glam::Vec3::splat(0.75)) - * glam::Mat4::from_translation(glam::Vec3::new(-0.5, (6.0 - 8.0) / 16.0, 0.5)) + * glam::Mat4::from_translation(glam::Vec3::new( + -0.5, + (display_offset(c.kind) as f32 - 8.0) / 16.0, + 0.5, + )) * glam::Mat4::from_rotation_y(90f32.to_radians()); if c.kind == CartKind::Chest { self.cart_chest(state, display, l, out); @@ -1297,7 +1355,7 @@ impl Game<'_> { * glam::Mat4::from_translation(glam::Vec3::splat(-0.5)); let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0; let start = out.len(); - self.block_model_vertices(state, BlockPos::default(), m, packed, out); + self.block_model_vertices(state, 0, m, packed, false, out); if flash { // submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light. for v in &mut out[start..] { @@ -1410,3 +1468,18 @@ impl Minecart { Some(c) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_offset_matches_vanilla_for_each_cart_kind() { + assert_eq!(display_offset(CartKind::Hopper), 1.0); + assert_eq!(display_offset(CartKind::Chest), 6.0); + assert_eq!(display_offset(CartKind::Furnace), 6.0); + assert_eq!(display_offset(CartKind::Tnt), 6.0); + assert_eq!(display_offset(CartKind::CommandBlock), 6.0); + assert_eq!(display_offset(CartKind::Rideable), 6.0); + } +} diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index c2246cf5b..8b2b2da40 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -257,20 +257,36 @@ impl Game<'_> { out: &mut Vec, ) { // ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint. - for (item, left) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { + for (item, off_hand) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] { let Some(item) = item else { continue }; + let left = off_hand != mob.extra.main_hand_left; let Some(t) = render::held_item_transform(mob, alpha as f32, camera, &self.res.mob_data, left) else { continue; }; - let slot = if left { + let slot = if off_hand { horizon_client::mobs::gear::OFF } else { horizon_client::mobs::gear::MAIN }; - let mut stack = ItemStack::new(item, 1); - if horizon_client::mobs::gear::enchanted(mob, slot) { + let local_player = self + .player_model + .as_ref() + .is_some_and(|p| p.id == mob.id && p.kind.id == mob.kind.id); + let mut stack = if local_player { + let Some(stack) = self.stack_in(if off_hand { + super::shield::OFFHAND_SLOT + } else { + self.selected + }) else { + continue; + }; + stack.clone() + } else { + ItemStack::new(item, 1) + }; + if !local_player && horizon_client::mobs::gear::enchanted(mob, slot) { // The gear's enchantments are not tracked, only that it has some. stack.enchant("minecraft:unbreaking", 1); } @@ -284,12 +300,13 @@ impl Game<'_> { ); // The local player's rod while its hook is out. owner.fishing_cast_with_this_item = self.cast_rod().is_some() - && self.main_hand_rod() != left + && self.main_hand_rod() != off_hand && self .player_model .as_ref() .is_some_and(|p| std::ptr::eq(p, mob)); - if !left && mob.extra.using_item > 0 { + owner.main_arm_left = mob.extra.main_hand_left; + if off_hand == mob.extra.using_off_hand && mob.extra.using_item > 0 { owner.using_this_item = true; owner.use_duration = 72_000; owner.use_item_remaining_ticks = 72_000 - mob.extra.using_item; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 571bbf5e0..80d26a823 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -206,7 +206,7 @@ impl NaturalLevel for GameLevel<'_, '_> { .chunks .get(&(x >> 4, z >> 4)) .and_then(|chunk| { - chunk.highest(world.air.0 as u16, |y| { + chunk.highest(world.air.0, |y| { spawn_selection::heightmap_blocks(self, kind, x, y, z) }) }) diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index ed0dccb06..d625f938b 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -225,6 +225,11 @@ impl Game<'_> { let _ = std::fs::create_dir_all(&dir); super::packs::open_folder(&dir); } + Event::OpenModFolder => { + let dir = Self::options_path().with_file_name(horizon_client::mod_list::DIR); + let _ = std::fs::create_dir_all(&dir); + super::packs::open_folder(&dir); + } } } Ok(()) diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 62d481b11..0c988c3b7 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -365,13 +365,6 @@ impl Game<'_> { self.close_book(); return Ok(()); } - if let Some(remote) = self.remote.as_mut() - && remote.chat_input.is_some() - { - remote.chat_input = None; - self.capture(true); - return Ok(()); - } self.key_pressed(KeyCode::Escape) } diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index 8f34d2b3a..5c623202b 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -31,7 +31,7 @@ use winit::{ dpi::PhysicalPosition, event::{DeviceId, ElementState, MouseButton, MouseScrollDelta, TouchPhase, WindowEvent}, event_loop::ActiveEventLoop, - keyboard::{KeyCode, NamedKey}, + keyboard::KeyCode, }; /// D-pad auto-repeat: the first step at once, the next after a pause. @@ -859,7 +859,6 @@ impl Game<'_> { || (self.screen == Screen::Creative && self.creative_screen.tab().search) || self.recipe_search_focused() || self.station_typing() - || self.remote_chat_open() } /// Open the on-screen keyboard over the focused field: Horizon's, or @@ -890,7 +889,7 @@ impl Game<'_> { && self.pad.in_use && menu.open_polls >= 3 && self.pad_focus_mode() - && (self.screen == Screen::Chat || self.sign_edit.is_some() || self.remote_chat_open()) + && (self.screen == Screen::Chat || self.sign_edit.is_some()) { self.pad.menu.osk_dismissed = true; self.pad_open_keyboard(); @@ -901,10 +900,10 @@ impl Game<'_> { /// the field that has focus. fn pad_osk_output(&mut self, out: osk::Output) { use osk::Output; - let (key, named, text) = match &out { - Output::Text(t) => (None, None, Some(t.as_str())), - Output::Backspace => (Some(KeyCode::Backspace), Some(NamedKey::Backspace), None), - Output::Enter => (Some(KeyCode::Enter), Some(NamedKey::Enter), None), + let (key, text) = match &out { + Output::Text(t) => (None, Some(t.as_str())), + Output::Backspace => (Some(KeyCode::Backspace), None), + Output::Enter => (Some(KeyCode::Enter), None), Output::Close => { self.pad.menu.osk = None; self.pad.menu.osk_dismissed = true; @@ -933,8 +932,6 @@ impl Game<'_> { if key != Some(KeyCode::Enter) { self.station_text(text, backspace); } - } else if self.remote_chat_open() { - self.remote_chat_input(named, text); } else if self.screen == Screen::WorldOptions { if key != Some(KeyCode::Enter) { self.world_options_text(text); @@ -985,8 +982,7 @@ impl Game<'_> { .menu .focus .is_some_and(|f| f.center().1 > batch.height / 2.0) - || self.screen == Screen::Chat - || self.remote_chat_open(); + || self.screen == Screen::Chat; let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index 2e5542ccc..c65dbbb89 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -255,6 +255,15 @@ impl Game<'_> { }; for p in &self.paintings { let entity_start = out.len(); + // EntityRenderer.shouldRender: the default range and its box, + // measured from the box's centre (HangingEntity's position). + let (lo, hi) = p.bounds(); + let (lo, hi) = (glam::DVec3::from(lo), glam::DVec3::from(hi)); + let range = + super::entity_culling::default_range(hi - lo, self.settings.entity_distance); + if !self.entity_in_view(camera, (lo + hi) / 2.0, range, lo, hi) { + continue; + } let Some(v) = self.painting_variants.get(&p.variant) else { continue; }; diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 96d879f13..53651dc6c 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -176,7 +176,13 @@ impl Game<'_> { self.dropped.push(e); } } - "minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)), + "minecraft:experience_orb" => { + for mut orb in entity_nbt::orbs_from_nbt(&tag) { + self.next_entity += 1; + orb.id = self.next_entity; + self.orbs.push(orb); + } + } "minecraft:arrow" => { if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt( &tag, @@ -196,6 +202,7 @@ impl Game<'_> { { let (no_gravity, drop_item) = entity_nbt::falling_block_flags(&tag); self.falling.push(FallingBlock { + id: 0, state, // DATA_START_POS is not persisted by vanilla. start_pos: horizon_core::position::BlockPos::default(), @@ -214,6 +221,23 @@ impl Game<'_> { }); } } + // PrimedTnt.readAdditionalSaveData: its fuse (80 when absent) and motion. + "minecraft:tnt" => { + if let Some(position) = entity_nbt::position(&tag) { + let fuse = match tag.get("fuse") { + Some(Tag::Short(f)) => i32::from(*f), + _ => 80, + }; + self.tnts.push(super::tnt::PrimedTnt { + id: 0, + position, + previous: position, + velocity: entity_nbt::motion(&tag), + fuse, + on_ground: matches!(tag.get("OnGround"), Some(Tag::Byte(1))), + }); + } + } k if super::boats::any_boat_wood(k) .is_some_and(|(wood, chest)| self.boat_models.has(wood, chest)) => { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index bb463547f..4214bdd70 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -201,7 +201,7 @@ impl Game<'_> { ) }; let p = self.player.as_ref()?; - let sleeping = self.sleeping.map(|(head, _)| { + let sleeping = self.sleeping.map(|head| { let state = self.world.block(head[0], head[1], head[2]); let props = self .pack @@ -305,6 +305,13 @@ impl Game<'_> { let (position, flying) = (p.position, p.flying || p.fall_flying); let (fall_flying, fly_ticks, velocity) = (p.fall_flying, p.fall_fly_ticks, p.velocity); let using = self.using.map(|(_, ticks)| ticks as i32 + 1).unwrap_or(0); + let using_off_hand = self + .using + .is_some_and(|(slot, _)| slot == super::shield::OFFHAND_SLOT); + let blocking = self + .using + .and_then(|(slot, _)| self.stack_in(slot)) + .is_some_and(|stack| self.blocks_attacks(stack).is_some()); let charged = self.inventory[self.selected] .as_ref() .is_some_and(|s| s.data().is_some_and(|d| !d.charged.is_empty())); @@ -313,13 +320,22 @@ impl Game<'_> { .map_or(25, |s| Self::charge_ticks(s).max(1)) as i32; let attack = (self.swing.old_animation, self.swing.animation); let swinging = self.swing.swinging(); + // currentSwing.hand().asArm(mainArm). + let swing_right_arm = swinging.then(|| { + (self.swing.attack_hand() == horizon_client::first_person::Hand::Main) + != self.settings.main_hand_left + }); + // LivingEntity.isVisuallySwimming and Entity.isInWater. + let visually_swimming = + p.pose == Pose::Swimming || (!p.fall_flying && p.pose == Pose::FallFlying); + let in_water = p.fluids.was_touching_water; let (yaw, pitch) = (self.yaw, self.pitch); let main = self.inventory[self.selected] .as_ref() .map(|s| s.item.clone()); let off = self.offhand.as_ref().map(|s| s.item.clone()); let riding = self.riding.is_some(); - let hurt = p.health.hurt.hurt_time; + let hurt = p.health.hurt_animation_time; let Some(m) = self.player_model.as_mut() else { return; }; @@ -375,9 +391,13 @@ impl Game<'_> { m.extra.fall_fly_ticks = fly_ticks; m.extra.main_hand_left = self.settings.main_hand_left; m.extra.using_item = using; + m.extra.using_off_hand = using_off_hand; + m.extra.blocking = blocking; m.extra.charged = charged; m.extra.ints[5] = charge_duration; m.extra.elytra.tick(fall_flying, crouching, velocity); + m.extra.swim.tick(visually_swimming, in_water); + m.extra.swing_right_arm = swing_right_arm; m.hurt_time = hurt; } /// Whether the player's own model shows in the world view. diff --git a/crates/horizon-client/src/game/pickups.rs b/crates/horizon-client/src/game/pickups.rs index 2729dc98f..1e19bcfc3 100644 --- a/crates/horizon-client/src/game/pickups.rs +++ b/crates/horizon-client/src/game/pickups.rs @@ -148,6 +148,7 @@ mod tests { fn orb_at(x: f64, y: f64, z: f64) -> Taken { let at = horizon_core::geometry::Vec3::new(x, y, z); Taken::Orb(Box::new(ExperienceOrb { + id: 0, position: at, previous: at, velocity: horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0), diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index a60926256..bc4f3b6bc 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -228,7 +228,7 @@ impl Game<'_> { } let (lasting, now) = PlayerEffects::potion_effects(stack.potion(), 1.0); for e in lasting { - self.potions.effects.add(e); + self.add_player_effect(e); } for a in now { self.apply_effect_action(a); @@ -249,7 +249,7 @@ impl Game<'_> { } true } - fn apply_effect_action(&mut self, action: EffectAction) { + pub(super) fn apply_effect_action(&mut self, action: EffectAction) { let creative = self.creative; let rules = self.world.health_rules; let Some(p) = self.player.as_mut() else { @@ -329,9 +329,24 @@ impl Game<'_> { } self.apply_effect_status(); } + /// Add an active effect to the player and update attributes / absorption. + pub(super) fn add_player_effect(&mut self, effect: EffectInstance) -> bool { + let id = effect.id; + let amp = effect.amplifier; + let changed = self.potions.effects.add(effect); + self.apply_effect_status(); + if id == "absorption" + && let Some(p) = self.player.as_mut() + { + let target = 4.0 * (amp + 1) as f32; + let current = p.health.absorption(); + let _ = p.set_health(current.max(target), true); + } + changed + } /// The effects' attribute modifiers, armor protection and status flags /// on `self.player`. - fn apply_effect_status(&mut self) { + pub(super) fn apply_effect_status(&mut self) { let modifiers = self.potions.effects.modifiers(); if modifiers != self.potions.applied && let Some(p) = self.player.as_mut() @@ -344,6 +359,12 @@ impl Game<'_> { } self.potions.applied = modifiers; } + if let Some(p) = self.player.as_mut() + && self.potions.effects.amplifier("absorption").is_none() + && p.health.absorption() > 0.0 + { + let _ = p.set_health(0.0, true); + } // EnchantmentHelper.getDamageProtection per damage type, recomputed on armor change. let armor: Vec> = self.armor.to_vec(); if self.potions.protection_for.as_ref() != Some(&armor) { @@ -467,6 +488,41 @@ impl Game<'_> { self.splash(&stack, at); } } + /// A splash potion's effects on the player in place, by their distance. + fn splash_on_player( + &mut self, + effects: &'static [(&'static str, i32, i32)], + at: Vec3, + scale: f64, + ) { + if let Some(p) = self.player.as_ref() { + let center = Vec3::new( + p.position.x, + p.position.y + f64::from(p.dimensions.height) / 2.0, + p.position.z, + ); + let d2 = + (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); + if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { + let intensity = 1.0 - d2.sqrt() / 4.0; + for (id, duration, amp) in effects { + let instant = brewing::effect(id).is_some_and(|e| e.instant); + if instant { + if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { + self.apply_effect_action(a); + } + } else { + let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; + if d > 20 + && let Some(e) = brewing::effect(id) + { + self.add_player_effect(EffectInstance::new(e.id, d, *amp)); + } + } + } + } + } + } /// `ThrownSplashPotion.onHitAsPotion` (lingering clouds apply as a weaker splash). fn splash(&mut self, stack: &ItemStack, at: Vec3) { if &*stack.item == "minecraft:experience_bottle" { @@ -527,34 +583,9 @@ impl Game<'_> { let Some(def) = stack.potion().and_then(brewing::potion) else { return; }; - // The player. - if let Some(p) = self.player.as_ref() { - let center = Vec3::new( - p.position.x, - p.position.y + f64::from(p.dimensions.height) / 2.0, - p.position.z, - ); - let d2 = - (center.x - at.x).powi(2) + (center.y - at.y).powi(2) + (center.z - at.z).powi(2); - if d2 < 16.0 && (center.y - at.y).abs() <= 2.0 + f64::from(p.dimensions.height) { - let intensity = 1.0 - d2.sqrt() / 4.0; - for (id, duration, amp) in def.effects { - let instant = brewing::effect(id).is_some_and(|e| e.instant); - if instant { - if let Some(a) = horizon_client::effects::instant(id, *amp, intensity) { - self.apply_effect_action(a); - } - } else { - let d = (intensity * f64::from(*duration) * scale + 0.5) as i32; - if d > 20 - && let Some(e) = brewing::effect(id) - { - self.potions.effects.add(EffectInstance::new(e.id, d, *amp)); - } - } - } - } - } + // Every player in range (`ThrownSplashPotion.applySplash` over + // `LivingEntity`s, the players among them). + self.for_each_player(|g| g.splash_on_player(def.effects, at, scale)); // Mobs take the instant effects (undead invert healing and harming). let undead = &self.res.stations.enchantments.entity_tags; let mut hits = Vec::new(); diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 63f45c1c5..25a440af3 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -39,6 +39,17 @@ pub(super) struct Raiding { homes: HashMap>)>, } +impl Raiding { + /// Exchange the level-held parts (`ServerLevel.getRaids`) with another + /// level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.raids, &mut other.raids); + std::mem::swap(&mut self.loaded, &mut other.loaded); + std::mem::swap(&mut self.bar_hurts, &mut other.bar_hurts); + std::mem::swap(&mut self.homes, &mut other.homes); + } +} + /// `SectionPos` of a block position. pub(super) fn section(p: [i32; 3]) -> (i32, i32, i32) { (p[0] >> 4, p[1] >> 4, p[2] >> 4) @@ -613,17 +624,17 @@ impl Game<'_> { raider::state_mut(m).ticks_outside_raid = ticks; } } - Action::Victory { heroes, amplifier } => { - let me = self.level.player_uuid; - if me.is_some_and(|u| heroes.contains(&u)) && !self.spectator() { + // Raid.tick on a victory: each hero who is still alive. + Action::Victory { heroes, amplifier } => self.for_each_player(|g| { + if heroes.contains(&g.acting_uuid()) && !g.spectator() { let mut effect = EffectInstance::new("hero_of_the_village", raid::HERO_DURATION, amplifier); effect.visible = false; - self.potions.effects.add(effect); - self.stats.custom("raid_win", 1); - self.trigger_player("minecraft:hero_of_the_village"); + g.potions.effects.add(effect); + g.stats.custom("raid_win", 1); + g.trigger_player("minecraft:hero_of_the_village"); } - } + }), } } /// `Raid.playSound`: the horn, 13 blocks away from the player toward the diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 67fc46b68..706c8d73e 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -110,7 +110,7 @@ fn sprite(name: &str) -> String { impl Game<'_> { /// The book the open screen has, if any. fn active_book(&self) -> Option { - if self.screen != Screen::Inventory || self.remote.is_some() || self.station.is_some() { + if self.screen != Screen::Inventory || self.station.is_some() { return None; } if self.mount_active() { @@ -262,6 +262,33 @@ impl Game<'_> { /// The items the book counts (`RecipeBookComponent.updateStackedContents`): /// the inventory and the menu's crafting slots, as the menu engine counts them. fn book_available(&mut self, _book: BookType) -> Stacked { + if self.remote.is_some() { + // A server's menu: the slots it last sent, counted the same way. + use horizon_client::menu::{Env, Kind, Menu}; + let table = self.craft_size == 3; + let grid: Vec<_> = (0..self.craft_size * self.craft_size) + .map(|k| self.slot_mut(100 + k).clone()) + .collect(); + let mut menu = Menu::new(if table { + Kind::Crafting + } else { + Kind::Inventory + }); + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + banners: &self.res.stations.banners, + trade: None, + }; + for i in 0..36 { + menu.set_player_item(i, self.inventory[i].clone()); + } + for (k, stack) in grid.into_iter().enumerate() { + menu.set_slot(&env, 1 + k, stack); + } + return menu.stacked_contents(&env); + } let mut out = Stacked::default(); let stock = &mut out; self.menu_session(|menu, env, _| { @@ -274,6 +301,10 @@ impl Game<'_> { /// replacing batch (vanilla's server iterates an identity hash set; this /// one goes in id order), then each unlock and removal. fn sync_client_book(&mut self) { + // On a server the book is the server's packets' (remote_recipe_book_*). + if self.remote.is_some() { + return; + } let known = &self.level.recipe_book.recipes; let index = &self.res.stations.recipe_index; let ui = &mut self.recipe_ui; @@ -660,6 +691,10 @@ impl Game<'_> { } false } + /// How many displays the client's book holds. + pub(super) fn recipe_book_known(&self) -> usize { + self.recipe_ui.client.displays().len() + } /// The recipe book's buttons a controller can focus: the book button, /// recipes, page arrows, the craftable filter and the tabs (GUI pixels; /// the search box registers itself as a field). @@ -800,6 +835,18 @@ impl Game<'_> { else { return; }; + if self.remote.is_some() { + // The server places it and answers with the slots, or a ghost. + let container = self.remote_menu_id(); + self.send(horizon_protocol::packets::play::Serverbound::PlaceRecipe( + horizon_protocol::packets::recipes::PlaceRecipe { + container, + recipe: entry.display_id, + use_max, + }, + )); + return; + } let creative = self.creative; let mut post = None; let answer = &mut post; @@ -828,6 +875,80 @@ impl Game<'_> { } } + // ---- a server's recipe book ---- + + /// ClientboundRecipeBookAddPacket (`ClientRecipeBook.add`): the + /// displays join the book, highlighted when new, and the recipes whose + /// entries ask for it show the toast. + pub(super) fn remote_recipe_book_add( + &mut self, + p: horizon_protocol::packets::recipes::RecipeBookAdd, + ) { + let ui = &mut self.recipe_ui; + if p.replace { + ui.client.clear(); + } + let mut toast = Vec::new(); + for e in &p.entries { + ui.client.add(e.id); + if e.flags & 2 != 0 { + ui.client.highlight.insert(e.id); + } + if e.flags & 1 != 0 + && let Some(id) = self.res.stations.recipe_index.recipe_of_display(e.id) + && !toast.iter().any(|t| t == id) + { + toast.push(id.to_owned()); + } + } + // A local world opened later syncs its book from scratch. + ui.client_known = None; + ui.client_version += 1; + self.recipe_toast(&toast); + } + /// ClientboundRecipeBookRemovePacket. + pub(super) fn remote_recipe_book_remove( + &mut self, + p: horizon_protocol::packets::recipes::RecipeBookRemove, + ) { + for id in p.ids { + self.recipe_ui.client.remove(id); + } + self.recipe_ui.client_version += 1; + } + /// ClientboundRecipeBookSettingsPacket: each book's open and filter flags. + pub(super) fn remote_recipe_book_settings( + &mut self, + p: horizon_protocol::packets::recipes::RecipeBookSettings, + ) { + for (i, (open, filtering)) in p.books.into_iter().enumerate() { + self.level.recipe_book.open[i] = open; + self.level.recipe_book.filtering[i] = filtering; + } + } + /// ClientboundPlaceGhostRecipePacket: the recipe last placed, faded into + /// the open menu's grid. + pub(super) fn remote_ghost_recipe( + &mut self, + p: horizon_protocol::packets::recipes::PlaceGhostRecipe, + ) { + let open = self.remote_menu_id(); + let Some(book_type) = self.active_book() else { + return; + }; + if p.container != open { + return; + } + let entry = self.recipe_ui.last_placed.as_ref().and_then(|id| { + let book = self.recipe_ui.book.as_ref()?; + book.entry(id).cloned() + }); + if let Some(entry) = entry { + self.recipe_ui.ghost.clear(); + self.fill_ghost(book_type, &entry); + } + } + // ---- ghost recipe ---- /// `fillGhostRecipe`: the recipe's ingredients faded into the slots. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 05e1f81c3..474e943c0 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -9,20 +9,26 @@ use super::{Dim, Game, Mining, Screen}; use horizon_client::{ Result, - chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section}, + chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, Section, block_strategy}, containers::{BlockEntity, Furnace, FurnaceKind}, - entities::{Experience, ItemEntity}, + entities::{Experience, ExperienceOrb, ItemEntity}, hud::{HudBatch, rgba}, items::ItemStack, - mobs::{Mob, MobType}, + menu::Input, + mobs::{Mob, MobType, Who}, motion::{MotionWorld, PlayerMotion}, net::{Event, Session}, save::SaveDir, sprint::Keys, streaming::{ChunkGenerator, Proto, Streaming}, + tab_list::SPECTATOR, world::World, }; -use horizon_core::{geometry::Vec3, paletted::PalettedContainer, random::RandomSource}; +use horizon_core::{ + geometry::Vec3, + paletted::{PalettedContainer, Strategy}, + random::RandomSource, +}; use horizon_protocol::{ entity_data::{ITEM_ENTITY_ITEM, Value}, item::{Hashed, Stack}, @@ -34,13 +40,15 @@ use horizon_protocol::{ text::{Language, format_java, plain}, }; use horizon_world::{nbt::Tag, registry::BlockStateId}; -use std::{ - collections::HashMap, - sync::Arc, - time::{Duration, Instant}, -}; +use std::{collections::HashMap, sync::Arc, time::Instant}; use winit::{event::MouseButton, keyboard::KeyCode}; +/// A text component the server sent, for the HUD. +fn remote_text(tag: &Tag) -> horizon_client::text::Text { + use horizon_client::scoreboard::{comp_text, tag_to_json}; + comp_text(&tag_to_json(tag)) +} + /// Streaming needs a generator; a server world never generates. struct NoTerrain; impl ChunkGenerator for NoTerrain { @@ -61,8 +69,11 @@ struct Tracked { } /// Smooth an entity toward a new position over three ticks (InterpolationHandler). #[derive(Clone, Copy)] +/// `LinearInterpolationHandler`'s target: a position and rotation (yRot, +/// xRot) reached in `steps` ticks. struct Lerp { target: [f64; 3], + rotation: Option<(f32, f32)>, steps: u32, } @@ -71,7 +82,7 @@ pub(super) struct Remote { pub brand: String, builtin: Arc, lang: Arc, - registries: Arc, + pub(super) registries: Arc, joined: bool, status: String, entity_id: i32, @@ -89,6 +100,8 @@ pub(super) struct Remote { was_sprinting: bool, carried: Option, loaded_sent: bool, + /// The view distance last sent in ClientInformation. + sent_view: i8, /// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break), /// with the sequence of the last action that changed them and the state the server /// last said they have. Until the server acknowledges that sequence its block updates @@ -102,13 +115,15 @@ pub(super) struct Remote { use_target: Option<[i32; 3]>, entities: HashMap, lerps: HashMap, + /// `LivingEntity.lerpHeadTo`: the head yaw and the ticks left to reach it. + head_lerps: HashMap, /// Item entities waiting for their item data. pending_items: HashMap, health: (f32, i32, f32), game_mode: i32, pub chat: Vec<(String, Instant)>, - pub chat_input: Option, - action_bar: Option<(String, Instant)>, + /// The server's command tree (ClientboundCommandsPacket). + pub commands: Option, players: HashMap, /// `ClientPacketListener.playerInfoMap` as player-list entries, and /// which of them are listed. @@ -196,7 +211,7 @@ impl Game<'_> { .and_then(|p| Builtin::load(&p).ok()) .ok_or("Resources are incomplete: registries.json is missing or invalid. Click \"Prepare again\" in the launcher (or run horizon-prepare), then try again.")?; let lang = Arc::new(horizon_client::net::load_language(&root)); - let view = self.settings.render_distance.clamp(2, 32) as i8; + let view = client_view_distance(self.settings.render_distance); if local.is_none() { horizon_client::crash::set_detail( "Server", @@ -233,6 +248,8 @@ impl Game<'_> { self.player = None; self.spawn = None; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.creatures.projectiles.clear(); self.dropped.clear(); self.particles.clear(); @@ -281,6 +298,7 @@ impl Game<'_> { was_sprinting: false, carried: None, loaded_sent: false, + sent_view: view, predictions: HashMap::new(), menu: None, menu_title: None, @@ -288,12 +306,12 @@ impl Game<'_> { use_target: None, entities: HashMap::new(), lerps: HashMap::new(), + head_lerps: HashMap::new(), pending_items: HashMap::new(), health: (20.0, 20, 5.0), game_mode: 0, chat: Vec::new(), - chat_input: None, - action_bar: None, + commands: None, players: HashMap::new(), tab_players: HashMap::new(), skin_textures: HashMap::new(), @@ -350,6 +368,8 @@ impl Game<'_> { self.world = World::new(self.res.facts.air, 0); self.player = None; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); @@ -432,7 +452,7 @@ impl Game<'_> { .and_then(|i| i.id(name)) .unwrap_or(0) } - fn to_stack(&self, s: &Option) -> Option { + pub(super) fn to_stack(&self, s: &Option) -> Option { let s = s.as_ref()?; let mut out = ItemStack { item: self.item_name(s.item), @@ -470,6 +490,20 @@ impl Game<'_> { } } + /// The names in the server's player list, sorted. + pub(super) fn remote_online_names(&self) -> Option> { + let r = self.remote.as_ref()?; + let mut names: Vec = r.players.values().cloned().collect(); + names.sort(); + Some(names) + } + /// The open menu's window id (0: the inventory). + pub(super) fn remote_menu_id(&self) -> i32 { + self.remote + .as_ref() + .and_then(|r| r.menu.as_ref()) + .map_or(0, |m| m.0) + } /// The server's last `n` chat lines, newest first. pub(super) fn remote_chat(&self, n: usize) -> Option> { let r = self.remote.as_ref()?; @@ -531,8 +565,58 @@ impl Game<'_> { break; } } + self.send_suggestion_request(); Ok(()) } + /// ClientSuggestionProvider.customSuggestion: the chat's completion + /// request for an `ask_server` node goes to the server. + fn send_suggestion_request(&mut self) { + if self.remote.is_none() { + return; + } + let Some((id, command)) = self.ui.chat_screen.as_mut().and_then(|s| s.take_request()) + else { + return; + }; + let mut w = horizon_protocol::buf::Writer::new(); + w.varint(id); + w.string(&command); + self.send(S::Unknown( + horizon_protocol::ids::play::serverbound::COMMAND_SUGGESTION, + w.data, + )); + } + /// ClientboundCommandSuggestionsPacket: id, range start and length, then + /// each suggestion's text and optional tooltip. + fn handle_command_suggestions(&mut self, data: &[u8]) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + let mut r = horizon_protocol::buf::Reader::new(data); + let decoded = (|| { + let id = r.varint()?; + let start = r.varint()?; + let length = r.varint()?; + let n = r.count(usize::MAX)?; + let mut list = Vec::with_capacity(n.min(1000)); + for _ in 0..n { + let text = r.string(32767)?; + let tooltip = if r.bool()? { + Some(plain(&r.nbt()?, &lang)) + } else { + None + }; + list.push((text, tooltip)); + } + horizon_protocol::Result::Ok((id, start, length, list)) + })(); + if let Ok((id, start, length, list)) = decoded { + let range = (start.max(0) as usize, length.max(0) as usize); + self.chat_server_suggestions(id, range, list); + } + } fn set_registries(&mut self, registries: Arc) { let biomes: Vec = registries .registries @@ -581,12 +665,15 @@ impl Game<'_> { self.world.day_time = day; self.world.weather = weather; self.mobs.clear(); + self.clear_remote_objects(); + self.clear_remote_projectiles(); self.dropped.clear(); self.particles.clear(); self.pickups.clear(); if let Some(r) = self.remote.as_mut() { r.entities.clear(); r.lerps.clear(); + r.head_lerps.clear(); r.pending_items.clear(); // A new ClientLevel: a new chunk storage, centred on 0, 0. r.chunk_center = (0, 0); @@ -633,11 +720,31 @@ impl Game<'_> { if !(0..SECTIONS as i32).contains(&target) { continue; } - let strategy = BLOCK_STRATEGY; + // A global section is as wide as the server's registry: 16 bits + // from a vanilla server, wider from a Horizon host with the same + // content mods. Read it at that width, then widen it to ours. + let ours = block_strategy(); + let strategy = if ours.wire_has_palette(s.states.bits) { + ours + } else { + Strategy::blocks(s.states.bits) + }; let palette = s.states.palette.iter().map(|&p| p as u32).collect(); let words = s.states.data.iter().map(|&w| w as u64).collect(); - let blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) + let mut blocks = PalettedContainer::from_wire(strategy, s.states.bits, palette, words) .map_err(|e| e.to_string())?; + if strategy.global_bits != ours.global_bits { + let mut values = [0u32; 4096]; + blocks.unpack(&mut values); + // Ids past our registry (a host with mods we lack) read as air. + let limit = 1u64 << ours.global_bits; + for v in &mut values { + if u64::from(*v) >= limit { + *v = 0; + } + } + blocks = PalettedContainer::from_values(ours, &values); + } let mut section = Section { blocks, biomes: PalettedContainer::from_values(BIOME_STRATEGY, &cells), @@ -760,6 +867,7 @@ impl Game<'_> { 0 => { if me { self.sleeping = None; + self.sleep_timer = 100; } return; } @@ -868,17 +976,33 @@ impl Game<'_> { } } } - fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], yaw: f32, head: f32) { + /// `recreateFromPacket`: yRot and xRot from the packet, the body and head + /// both at its head yaw (LivingEntity). + fn spawn_entity(&mut self, id: i32, kind: &str, position: [f64; 3], rotation: [f32; 3]) { + let [yaw, pitch, head] = rotation; let at = Vec3::new(position[0], position[1], position[2]); let mob_type = if kind == "minecraft:player" { self.remote.as_ref().and_then(|r| r.player_type.clone()) } else { self.res.mob_types.get(kind).cloned() }; + if kind == "minecraft:experience_orb" { + // Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData. + self.orbs.retain(|o| o.id != id as u32); + self.orbs.push(ExperienceOrb { + id: id as u32, + position: at, + previous: at, + velocity: Vec3::ZERO, + value: 1, + age: 0, + on_ground: false, + }); + } if let Some(t) = mob_type { let mut mob = Mob::new(id as u32, t, at, head); - mob.body_yaw = yaw; - mob.previous_body_yaw = yaw; + (mob.yaw, mob.previous_yaw) = (yaw, yaw); + (mob.head_pitch, mob.previous_head_pitch) = (pitch, pitch); mob.persistent = true; self.mobs.retain(|m| m.id != id as u32); self.mobs.push(mob); @@ -903,14 +1027,21 @@ impl Game<'_> { rotation: Option<(f32, f32)>, on_ground: bool, ) { + let mob = self.mobs.iter_mut().find(|m| m.id == id as u32); if let Some(r) = self.remote.as_mut() { if let Some(t) = r.entities.get_mut(&id) { t.position = position; } + // AbstractInterpolationHandler.interpolateTo: without a rotation, + // the one it was heading for (or has). + let rotation = rotation + .or_else(|| r.lerps.get(&id).and_then(|l| l.rotation)) + .or_else(|| mob.as_ref().map(|m| (m.yaw, m.head_pitch))); r.lerps.insert( id, Lerp { target: position, + rotation, steps: 3, }, ); @@ -918,20 +1049,22 @@ impl Game<'_> { *p = position; } } - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id as u32) { + if let Some(m) = mob { m.on_ground = on_ground; - if let Some((yaw, pitch)) = rotation { - m.body_yaw = yaw; - m.head_pitch = pitch; - } } + self.turn_remote_object(id, rotation.map(|(yaw, _)| yaw), on_ground); + self.turn_remote_projectile(id, rotation); } fn remove_entity(&mut self, id: i32) { self.mobs.retain(|m| m.id != id as u32); + self.orbs.retain(|o| o.id != id as u32); self.dropped.retain(|d| d.id != id as u32); + self.remove_remote_object(id as u32); + self.remove_remote_projectile(id as u32); if let Some(r) = self.remote.as_mut() { r.entities.remove(&id); r.lerps.remove(&id); + r.head_lerps.remove(&id); r.pending_items.remove(&id); } } @@ -1023,10 +1156,12 @@ impl Game<'_> { self.streaming.radius = self.settings.render_distance.min(p.chunk_radius + 1).max(2); self.enter_remote_dimension(&p.spawn, false); + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() { + r.sent_view = view; + } self.send(S::ClientInformation( - horizon_protocol::packets::configuration::ClientInformation::new( - self.settings.render_distance.clamp(2, 32) as i8, - ), + horizon_protocol::packets::configuration::ClientInformation::new(view), )); } C::Respawn(p) => { @@ -1181,8 +1316,8 @@ impl Game<'_> { .map(str::to_owned) }) .unwrap_or_default(); - let yaw = horizon_protocol::buf::unpack_degrees(p.yaw); - let head = horizon_protocol::buf::unpack_degrees(p.head_yaw); + let rotation = + [p.yaw, p.pitch, p.head_yaw].map(horizon_protocol::buf::unpack_degrees); if let Some(r) = self.remote.as_mut() { if kind == "minecraft:player" { r.level_players.insert(p.id, p.uuid); @@ -1190,7 +1325,17 @@ impl Game<'_> { r.level_players.remove(&p.id); } } - self.spawn_entity(p.id, &kind, p.position, yaw, head); + self.spawn_entity(p.id, &kind, p.position, rotation); + if !self.spawn_remote_object(p.id, &kind, p.position, rotation[0], p.data) { + self.spawn_remote_projectile( + p.id, + &kind, + p.position, + (rotation[0], rotation[1]), + p.velocity, + p.data, + ); + } } C::RemoveEntities(p) => { for id in p.ids { @@ -1241,9 +1386,11 @@ impl Game<'_> { ]; self.move_entity(p.id, position, Some((p.yaw, p.pitch)), p.on_ground); } + // ClientPacketListener.handleRotateMob: lerpHeadTo(yHeadRot, 3). C::RotateHead(p) => { - if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { - m.yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + if let Some(r) = self.remote.as_mut() { + let yaw = horizon_protocol::buf::unpack_degrees(p.head_yaw); + r.head_lerps.insert(p.id, (yaw, 3)); } } C::SetEntityData(p) => { @@ -1271,17 +1418,39 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): this + // player lies down in the bed, or gets up. + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + for (index, _, value) in &p.values { + if let (14, Value::OptPos(bed)) = (index, value) { + if bed.is_some() && self.sleeping.is_none() { + self.sleep_timer = 0; + } + self.sleeping = *bed; + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value { self.remote_item_data(p.id, stack); } + // ExperienceOrb.DATA_VALUE (the icon's size). + if *index == 8 + && let Value::Int(v) = value + && let Some(o) = self.orbs.iter_mut().find(|o| o.id == p.id as u32) + { + o.value = (*v).max(0) as u32; + } } + self.remote_object_data(p.id, &p.values); + self.remote_projectile_data(p.id, &p.values); } // ClientPacketListener.handleSetEquipment: what a mob or another // player holds and wears (EquipmentSlot ordinals). C::SetEquipment(p) => { + self.remote_object_equipment(p.id, &p.slots); let items: Vec<(u8, Option>)> = p .slots .iter() @@ -1303,10 +1472,13 @@ impl Game<'_> { } } C::TakeItemEntity(p) => { - if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) + // An orb's sound comes from the server, at the orb. + let orb = self.orbs.iter().any(|o| o.id == p.item as u32); + if !orb + && self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) && let Some(eye) = self.eye_position() { let pitch = ((self.world.random.next_float() - self.world.random.next_float()) @@ -1317,17 +1489,20 @@ impl Game<'_> { .play("minecraft:entity.item.pickup", Some(eye), 0.2, pitch); } // ItemPickupParticle toward the collector (this player, another one or a mob). + let collector = if self + .remote + .as_ref() + .is_some_and(|r| r.entity_id == p.player) + { + super::pickups::Collector::Player + } else { + super::pickups::Collector::Mob(p.player as u32) + }; if let Some(item) = self.dropped.iter().find(|d| d.id == p.item as u32).cloned() { - let collector = if self - .remote - .as_ref() - .is_some_and(|r| r.entity_id == p.player) - { - super::pickups::Collector::Player - } else { - super::pickups::Collector::Mob(p.player as u32) - }; self.add_pickup(super::pickups::Taken::Item(Box::new(item)), collector); + } else if let Some(orb) = self.orbs.iter().find(|o| o.id == p.item as u32).cloned() + { + self.add_pickup(super::pickups::Taken::Orb(Box::new(orb)), collector); } self.remove_entity(p.item); } @@ -1439,6 +1614,21 @@ impl Game<'_> { } } C::GameEvent(p) => match p.event { + // GUARDIAN_ELDER_EFFECT: the apparition, and the curse sound + // unless the elder guardian is silent. + 10 => { + self.creatures.elder_apparition = super::mob_blocks::APPARITION_TICKS; + if p.param == 1.0 + && let Some(at) = self.player.as_ref().map(|m| m.position) + { + self.audio.play( + "minecraft:entity.elder_guardian.curse", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + } + } 1 => { self.world.weather.raining = true; self.world.weather.rain_level = (0.0, 0.0); @@ -1517,6 +1707,10 @@ impl Game<'_> { } } C::OpenScreen(p) => self.remote_open_screen(p), + C::RecipeBookAdd(p) => self.remote_recipe_book_add(p), + C::RecipeBookRemove(p) => self.remote_recipe_book_remove(p), + C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p), + C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p), C::MerchantOffers(p) => self.remote_merchant_offers(p), C::ContainerClose(_) => { if self.screen == Screen::Inventory { @@ -1525,6 +1719,20 @@ impl Game<'_> { self.capture(true); } } + C::Unknown(id, data) + if id == horizon_protocol::ids::play::clientbound::COMMAND_SUGGESTIONS => + { + self.handle_command_suggestions(&data); + } + C::Commands(p) => { + let tree = horizon_client::command::network::from_packet( + &p, + horizon_client::command::vanilla::dispatcher(), + ); + if let Some(r) = self.remote.as_mut() { + r.commands = Some(tree); + } + } C::SystemChat(p) => { let text = plain( &p.content, @@ -1534,10 +1742,9 @@ impl Game<'_> { .map(|r| r.lang.clone()) .unwrap_or_default(), ); + // ChatListener.handleOverlay. if p.overlay { - if let Some(r) = self.remote.as_mut() { - r.action_bar = Some((text, Instant::now())); - } + self.titles.set_overlay(remote_text(&p.content), false); } else { self.chat_line(text); } @@ -1768,15 +1975,16 @@ impl Game<'_> { self.stats.values.entry(ty).or_default().insert(key, count); } } - C::SetActionBarText(p) | C::SetTitleText(p) => { - let lang = self - .remote - .as_ref() - .map(|r| r.lang.clone()) - .unwrap_or_default(); - let text = plain(&p.text, &lang); - if let Some(r) = self.remote.as_mut() { - r.action_bar = Some((text, Instant::now())); + // ClientPacketListener.setActionBarText, setTitleText, + // setSubtitleText, setTitlesAnimation and handleTitlesClear. + C::SetActionBarText(p) => self.titles.set_overlay(remote_text(&p.text), false), + C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)), + C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)), + C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out), + C::ClearTitles(p) => { + self.titles.clear(); + if p.value { + self.titles.reset_times(); } } _ => {} @@ -2001,6 +2209,7 @@ impl Game<'_> { self.dropped.push(ItemEntity { health: 5, fire_ticks: 0, + thrower: None, id: id as u32, stack, position: at, @@ -2099,6 +2308,17 @@ impl Game<'_> { /// One client tick while connected (Minecraft.tick with a ClientLevel). pub(super) fn tick_remote(&mut self) -> Result<()> { self.ticks += 1; + // Options.broadcastOptions: a changed render distance is sent again. + let view = client_view_distance(self.settings.render_distance); + if let Some(r) = self.remote.as_mut() + && r.joined + && r.sent_view != view + { + r.sent_view = view; + self.send(S::ClientInformation( + horizon_protocol::packets::configuration::ClientInformation::new(view), + )); + } // Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances // the time only while the level runs normally. let running = self.clock.world_runs(); @@ -2124,7 +2344,12 @@ impl Game<'_> { self.tick_hand(); self.tick_particles(); self.tick_client_effects(); + // Player.tick's sleep counter (the darkening and the wake-up fade). + self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some()); + // Gui.tick: the titles, the action bar and the held item's name. + self.tick_hud(); let ghast_collisions = self.happy_ghast_player_collisions(); + let pushed = self.remote_pushes(); let Some(player) = self.player.as_mut() else { return Ok(()); }; @@ -2147,8 +2372,7 @@ impl Game<'_> { let Some(player) = self.player.as_mut() else { return Ok(()); }; - let chatting = self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()); - let playing = self.screen == Screen::Playing && !chatting; + let playing = self.screen == Screen::Playing; let held = |k| playing && self.keys.contains(&k); let keys = Keys { forward: held(KeyCode::KeyW), @@ -2176,7 +2400,16 @@ impl Game<'_> { ); player.yaw = self.yaw; let dead = self.screen == Screen::Dead; - if !dead { + // LivingEntity.isImmobile: a sleeper lies still in the bed. + if let Some(head) = self.sleeping { + player.position = Vec3::new( + f64::from(head[0]) + 0.5, + f64::from(head[1]) + 0.5625, + f64::from(head[2]) + 0.5, + ); + player.velocity = Vec3::ZERO; + } else if !dead { + player.velocity = player.velocity.add_vector(pushed); MotionWorld { entities: &ghast_collisions, player, @@ -2220,15 +2453,81 @@ impl Game<'_> { self.tick_player_model(); if !dead { self.remote_mining(); - if self.right && self.use_delay == 0 && playing { + // Minecraft.handleKeybinds: no new use while an item is in use. + if self.right && self.use_delay == 0 && playing && self.using.is_none() { self.remote_use(); self.use_delay = 4; } + self.remote_tick_using(); } self.remote_send_state(input); self.send(S::ClientTickEnd(Empty)); Ok(()) } + /// The local player's share of every touching entity's + /// `LivingEntity.pushEntities`: on a client `EntitySelector.pushableBy` + /// lets entities push only the local player, so the server never sends + /// these pushes. `doPush(player)` is `player.push(entity)`. + fn remote_pushes(&self) -> Vec3 { + let (Some(p), Some(r)) = (self.player.as_ref(), self.remote.as_ref()) else { + return Vec3::ZERO; + }; + // LivingEntity.isPushable: alive, no spectator, off ladders. + let feet = [ + p.position.x.floor() as i32, + p.position.y.floor() as i32, + p.position.z.floor() as i32, + ]; + if self.screen == Screen::Dead + || p.spectator + || self.block_in_tag("minecraft:climbable", &self.block_name(feet)) + { + return Vec3::ZERO; + } + let bounds = p.bounds(); + let teams = self.mob_teams(); + let mut push = Vec3::ZERO; + for m in &self.mobs { + let spectator = r + .level_players + .get(&(m.id as i32)) + .and_then(|uuid| r.tab_players.get(uuid)) + .is_some_and(|t| t.game_mode == SPECTATOR); + // Bats never push; a spectator has no physics; passengers of the + // same vehicle never push each other. + if !m.alive() + || spectator + || m.species() == horizon_client::mobs::Species::Bat + || self + .riding + .is_some_and(|v| v == m.id || m.extra.mount == Some(v)) + || !m.bounds().intersects(bounds) + || !horizon_client::scoreboard::pushable_by( + teams.of(Who::Mob(m.id)), + teams.of(Who::Player), + true, + ) + { + continue; + } + // Entity.push(Entity), `this` the player. + let (mut xa, mut za) = (m.position.x - p.position.x, m.position.z - p.position.z); + let mut dd = xa.abs().max(za.abs()); + if dd < f64::from(0.01_f32) { + continue; + } + dd = dd.sqrt(); + xa /= dd; + za /= dd; + let pow = (1.0 / dd).min(1.0); + xa *= pow; + za *= pow; + xa *= f64::from(0.05_f32); + za *= f64::from(0.05_f32); + push = Vec3::new(push.x - xa, push.y, push.z - za); + } + push + } /// ClientLevel.tickEntities; a frozen level only ticks the players /// (`TickRateManager.isEntityFrozen`). fn tick_remote_entities(&mut self, running: bool) { @@ -2236,14 +2535,18 @@ impl Game<'_> { return; }; let mut lerps = std::mem::take(&mut r.lerps); + let head_lerps = &mut r.head_lerps; let players = &r.level_players; for m in &mut self.mobs { - if !running && !players.contains_key(&(m.id as i32)) { + let player = players.contains_key(&(m.id as i32)); + if !running && !player { continue; } m.previous = m.position; m.previous_yaw = m.yaw; m.previous_body_yaw = m.body_yaw; + m.previous_head_yaw = m.head_yaw; + m.previous_head_pitch = m.head_pitch; m.previous_limb_speed = m.limb_speed; m.age += 1; if m.species() == horizon_client::mobs::Species::Rabbit { @@ -2258,6 +2561,7 @@ impl Game<'_> { if !m.alive() { m.death_time += 1; } + // Entity.commonTick: LinearInterpolationHandler.interpolate. if let Some(l) = lerps.get_mut(&(m.id as i32)) && l.steps > 0 { @@ -2267,8 +2571,27 @@ impl Game<'_> { m.position.y + (l.target[1] - m.position.y) / n, m.position.z + (l.target[2] - m.position.z) / n, ); + if let Some((yaw, pitch)) = l.rotation { + let alpha = 1.0 / l.steps as f32; + m.yaw += wrap_degrees(yaw - m.yaw) * alpha; + m.head_pitch += (pitch - m.head_pitch) * alpha; + } l.steps -= 1; } + // LivingEntity.aiStep: the head's own interpolation. + if let Some((yaw, steps)) = head_lerps.get_mut(&(m.id as i32)) + && *steps > 0 + { + m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; + *steps -= 1; + } + // LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl, + // a player's body following its walk and look. + if player { + remote_player_head_turn(m); + } else if m.alive() { + m.body_rotation_tick(); + } // WalkAnimationState.update from the horizontal distance moved. let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0); @@ -2278,6 +2601,21 @@ impl Game<'_> { horizon_client::mobs::rabbit::post_tick(m); } } + for o in self.orbs.iter_mut().filter(|_| running) { + o.previous = o.position; + o.age += 1; + if let Some(l) = lerps.get_mut(&(o.id as i32)) + && l.steps > 0 + { + let n = f64::from(l.steps); + o.position = Vec3::new( + o.position.x + (l.target[0] - o.position.x) / n, + o.position.y + (l.target[1] - o.position.y) / n, + o.position.z + (l.target[2] - o.position.z) / n, + ); + l.steps -= 1; + } + } for d in self.dropped.iter_mut().filter(|_| running) { d.previous = d.position; d.age += 1; @@ -2293,6 +2631,25 @@ impl Game<'_> { l.steps -= 1; } } + head_lerps.retain(|_, (_, steps)| *steps > 0); + if running { + // Boats, minecarts, armor stands, projectiles and the rest + // interpolate like mobs. + let mut step = |id: u32, at: Vec3| match lerps.get_mut(&(id as i32)) { + Some(l) if l.steps > 0 => { + let n = f64::from(l.steps); + l.steps -= 1; + Vec3::new( + at.x + (l.target[0] - at.x) / n, + at.y + (l.target[1] - at.y) / n, + at.z + (l.target[2] - at.z) / n, + ) + } + _ => at, + }; + self.tick_remote_objects(&mut step); + self.tick_remote_projectiles(&mut step); + } lerps.retain(|_, l| l.steps > 0); if let Some(r) = self.remote.as_mut() { for (id, l) in lerps { @@ -2418,8 +2775,7 @@ impl Game<'_> { if r.destroy_delay > 0 { r.destroy_delay -= 1; } - let chatting = r.chat_input.is_some(); - if !self.left || self.screen != Screen::Playing || chatting { + if !self.left || self.screen != Screen::Playing { self.stop_remote_mining(); self.mining = None; return; @@ -2602,8 +2958,16 @@ impl Game<'_> { location: [0.0, 1.0, 0.0], secondary: sneaking, })); - self.swing_arm(); - return; + // Player.interactOn: another player passes, and the held item is + // used instead (Minecraft.startUseItem). + let player = self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&id)); + if !player { + self.swing_arm(); + return; + } } if let Some(hit) = self.pick() { let seq = self.next_sequence(); @@ -2636,7 +3000,7 @@ impl Game<'_> { return; } } - if self.held().is_some() { + if let Some(held) = self.held().cloned() { let seq = self.next_sequence(); self.send(S::UseItem(play::UseItem { hand: 0, @@ -2644,11 +3008,49 @@ impl Game<'_> { yaw: self.yaw, pitch: self.pitch, })); + // MultiPlayerGameMode.useItem runs the use here too: food starts + // being eaten (Consumable.startConsuming). + if let Some(info) = self.res.items.get(&held.item).cloned() { + self.start_eating(&info); + } + } + } + /// `LivingEntity.updatingUsingItem` for food on a server client: the + /// eating animation and its crumbs. The server eats it and sends the + /// stack, the hunger and the sounds. + fn remote_tick_using(&mut self) { + let Some((slot, ticks)) = self.using else { + return; + }; + let stack = self.stack_in(slot).cloned(); + let food = stack + .as_ref() + .and_then(|s| self.res.items.get(&s.item)) + .is_some_and(|i| i.consumable && i.food.is_some()); + let (Some(stack), true) = (stack, food) else { + self.using = None; + return; + }; + if !self.right || slot != self.selected || self.screen != Screen::Playing { + self.using = None; + return; + } + // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. + let duration = 32; + let remaining = duration - ticks.min(duration); + if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { + self.eat_particles(&stack, 5); + } + if ticks + 1 >= duration { + self.using = None; + self.eat_particles(&stack, 16); + } else { + self.using = Some((slot, ticks + 1)); } } /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { - if self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) { + if self.screen == Screen::Chat { return Ok(()); } match button { @@ -2707,14 +3109,8 @@ impl Game<'_> { } match key { KeyCode::KeyT | KeyCode::Slash | KeyCode::Enter => { - let text = if key == KeyCode::Slash { "/" } else { "" }; - if let Some(r) = self.remote.as_mut() { - r.chat_input = Some(text.to_owned()); - } - self.keys.clear(); - self.left = false; - self.right = false; - self.capture(false); + // ChatScreen, over the server's command tree. + self.open_chat(if key == KeyCode::Slash { "/" } else { "" }); Ok(true) } KeyCode::KeyQ => { @@ -2751,84 +3147,6 @@ impl Game<'_> { _ => Ok(false), } } - pub(super) fn remote_chat_open(&self) -> bool { - self.remote.as_ref().is_some_and(|r| r.chat_input.is_some()) - } - /// ChatScreen: typing, Enter to send, Escape to cancel. - pub(super) fn remote_chat_key(&mut self, event: &winit::event::KeyEvent) { - use winit::keyboard::Key; - if event.state != winit::event::ElementState::Pressed { - return; - } - let shortcut = self.edit_shortcut(event); - let Some(r) = self.remote.as_mut() else { - return; - }; - let Some(input) = r.chat_input.as_mut() else { - return; - }; - // ChatScreen's input: an EditBox of 256. - const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0); - if let Some(shortcut) = shortcut { - Self::append_shortcut( - &mut self.text_selection, - &mut self.clipboard, - INPUT, - input, - shortcut, - 256, - ); - return; - } - // Logical keys: the text, not the scancode, decides (layouts, virtual keyboards). - let named = match &event.logical_key { - Key::Named(n) => Some(*n), - _ => None, - }; - self.remote_chat_input(named, event.text.as_deref()); - } - /// A named key or typed text in the chat input (the keyboard, or a - /// controller's on-screen keyboard). - pub(super) fn remote_chat_input( - &mut self, - named: Option, - text: Option<&str>, - ) { - use winit::keyboard::NamedKey; - const INPUT: horizon_client::clipboard::FieldId = ("remote.chat", 0); - let Some(r) = self.remote.as_mut() else { - return; - }; - let Some(input) = r.chat_input.as_mut() else { - return; - }; - match named { - Some(NamedKey::Escape) => { - r.chat_input = None; - self.capture(true); - } - Some(NamedKey::Backspace) => { - if !self.text_selection.take(INPUT, input) { - input.pop(); - } - } - Some(NamedKey::Enter) => { - let message = r.chat_input.take().unwrap_or_default(); - self.send_chat(&message); - self.capture(true); - } - _ => { - if let Some(text) = text { - self.text_selection.take(INPUT, input); - for c in text.chars().filter(|c| !c.is_control()) { - if input.chars().count() < 256 { - input.push(c); - } - } - } - } - } - } /// ClientPacketListener.sendChat / sendCommand (unsigned). pub(super) fn send_chat(&mut self, message: &str) { let message = message.trim(); @@ -2880,17 +3198,108 @@ impl Game<'_> { let Some(internal) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return; }; - let input = if self.has_shift_down() { 1 } else { 0 }; - self.remote_slot_click(internal, i8::from(right), input); + let input = if self.has_shift_down() { + Input::QuickMove + } else { + Input::Pickup + }; + self.remote_menu_ops(&[(Some(internal), i32::from(right), input)]); + } + /// The server's open menu: its window id and menu type (0, "inventory" + /// when none is open). + fn remote_menu(&self) -> (i32, String) { + match self.remote.as_ref().and_then(|r| r.menu.clone()) { + Some((id, name)) => (id, name), + None => (0, "inventory".to_owned()), + } + } + /// `MultiPlayerGameMode.handleContainerInput` for each click of `ops` on + /// the server's open menu (a quick craft drag is several): the verified + /// menu engine predicts them on this client's copy, then each goes out as + /// a `ContainerClick` with the slots it changed and the carried stack + /// after it; the server corrects anything it sees differently. A menu the + /// engine doesn't model sends the clicks unpredicted. False when a click's + /// slot isn't one of the menu's. + pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + let (container, menu) = self.remote_menu(); + let mut clicks = Vec::with_capacity(ops.len()); + for &(slot, button, input) in ops { + let slot = match slot { + None => -999, + Some(internal) => { + match (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)) { + Some(s) => s as i16, + None => return false, + } + } + }; + clicks.push((slot, button, input)); + } + // Unpredicted: nothing changed, the carried stack as it is. + let mut sent: Vec = clicks + .iter() + .map(|&(slot, button, input)| (slot, button, input, Vec::new(), self.carried.clone())) + .collect(); + // The engine's slot indices are the menu's own, as on the network. + self.menu_session(|m, env, _| { + let mut predicted = Vec::with_capacity(clicks.len()); + for &(slot, button, input) in &clicks { + let before = menu_items(m); + if m.click(env, i32::from(slot), button, input).is_err() { + // The server throws on it too: nothing is predicted. + return Some(false); + } + let changed = changed_slots(&before, m); + predicted.push((slot, button, input, changed, m.carried.clone())); + } + sent = predicted; + Some(true) + }); + self.send_clicks(container, sent); + true + } + /// A Shift double click on a server (`AbstractContainerScreen.mouseReleased`): + /// a predicted QUICK_MOVE for every slot the engine moves, each sent. + pub(super) fn remote_quick_move_all(&mut self, slot: usize, moved: &ItemStack) { + let (container, _) = self.remote_menu(); + let mut sent: Vec = Vec::new(); + self.menu_session(|m, env, to_menu| { + let clicked = to_menu(slot)?; + let mut before = menu_items(m); + let mut each = |m: &horizon_client::menu::Menu, t: usize| { + let changed = changed_slots(&before, m); + sent.push((t as i16, 0, Input::QuickMove, changed, m.carried.clone())); + before = menu_items(m); + }; + Some( + m.quick_move_all_each(env, clicked, moved, &mut each) + .is_ok(), + ) + }); + self.send_clicks(container, sent); + } + fn send_clicks(&mut self, container: i32, clicks: Vec) { + let state = self.remote.as_ref().map_or(0, |r| r.state_id); + let hashed = |g: &Self, s: &Option| g.to_network(s).map(|s| Hashed::of(&s)); + for (slot, button, input, changed, carried) in clicks { + let changed = changed.iter().map(|(i, s)| (*i, hashed(self, s))).collect(); + let carried = hashed(self, &carried); + self.send(S::ContainerClick(play::ContainerClick { + container, + state, + slot, + button: button as i8, + input: input_ordinal(input), + changed, + carried, + })); + } } /// A `ContainerClick` on game slot `internal` of the server's open menu /// (`input` is the ContainerInput ordinal). False when the menu has no /// such slot. pub(super) fn remote_slot_click(&mut self, internal: usize, button: i8, input: i32) -> bool { - let (container, menu) = match self.remote.as_ref().and_then(|r| r.menu.clone()) { - Some((id, name)) => (id, name), - None => (0, "inventory".to_owned()), - }; + let (container, menu) = self.remote_menu(); let slot = (0..64).find(|&s| Self::menu_slot(&menu, s) == Some(internal)); let Some(slot) = slot else { return false }; let carried = self.to_network(&self.carried).map(|s| Hashed::of(&s)); @@ -3134,6 +3543,15 @@ impl Game<'_> { .ok()?; Some((rows, r.menu_title.clone().unwrap_or_default())) } + /// ServerboundPlayerCommandPacket STOP_SLEEPING. + pub(super) fn remote_stop_sleeping(&mut self) { + let id = self.remote.as_ref().map_or(0, |r| r.entity_id); + self.send(S::PlayerCommand(play::PlayerCommand { + id, + action: 0, + data: 0, + })); + } pub(super) fn remote_respawn(&mut self) { self.send(S::ClientCommand(play::ClientCommand { action: 0 })); } @@ -3171,11 +3589,11 @@ impl Game<'_> { let Some(r) = &self.remote else { return }; let atlas = &self.atlas; let (w, h) = (batch.width, batch.height); - let open = r.chat_input.is_some(); + let open = self.screen == Screen::Chat; let now = Instant::now(); let mut y = h - 48.0; // Container screens cover the chat (vanilla draws them over the HUD). - let shown = if matches!(self.screen, Screen::Playing | Screen::Dead) { + let shown = if matches!(self.screen, Screen::Playing | Screen::Dead | Screen::Chat) { if open { 20 } else { 10 } } else { 0 @@ -3203,22 +3621,6 @@ impl Game<'_> { batch.text(atlas, text, 4.0, y, rgba(255, 255, 255, a), true); y -= 9.0; } - if let Some(input) = &r.chat_input { - batch.fill(atlas, 2.0, h - 14.0, w - 4.0, 12.0, rgba(0, 0, 0, 128)); - let blink = (self.started.elapsed().as_millis() / 300).is_multiple_of(2); - let shown = if blink { - format!("{input}_") - } else { - input.clone() - }; - batch.text(atlas, &shown, 4.0, h - 12.0, rgba(224, 224, 224, 255), true); - } - if let Some((text, at)) = &r.action_bar - && now.duration_since(*at) < Duration::from_secs(3) - { - let tw = HudBatch::text_width(atlas, text); - batch.text(atlas, text, (w - tw) / 2.0, h - 68.0, u32::MAX, true); - } if self.screen == Screen::Dead && let Some(message) = &r.death_message { @@ -3288,6 +3690,87 @@ impl Game<'_> { } } +/// `Mth.wrapDegrees`. +fn wrap_degrees(a: f32) -> f32 { + let a = a % 360.0; + if a >= 180.0 { + a - 360.0 + } else if a < -180.0 { + a + 360.0 + } else { + a + } +} + +/// `LivingEntity.tick`'s body target and `tickHeadTurn` for another player: +/// the body turns toward where it walks (backwards when walking back), or to +/// the look while the arm swings, and stays within 50 degrees of the look. +fn remote_player_head_turn(m: &mut Mob) { + let (dx, dz) = (m.position.x - m.previous.x, m.position.z - m.previous.z); + let mut target = m.body_yaw; + if (dx * dx + dz * dz) as f32 > 0.002_500_000_2 { + let walk = (dz.atan2(dx) as f32).to_degrees() - 90.0; + let facing = (wrap_degrees(m.yaw) - walk).abs(); + target = if 95.0 < facing && facing < 265.0 { + walk - 180.0 + } else { + walk + }; + } + if m.anim.attack_anim > 0.0 { + target = m.yaw; + } + m.body_yaw += wrap_degrees(target - m.body_yaw) * 0.3; + let head = wrap_degrees(m.yaw - m.body_yaw); + if head.abs() > 50.0 { + m.body_yaw += head - head.signum() * 50.0; + } +} + +/// A click sent to a server: its slot, button and input, the slots it +/// changed and the carried stack after it. +type Predicted = ( + i16, + i32, + Input, + Vec<(i16, Option)>, + Option, +); + +fn menu_items(m: &horizon_client::menu::Menu) -> Vec> { + (0..m.slot_count()).map(|i| m.slot(i).cloned()).collect() +} + +/// The slots whose stack is no longer `before`'s (`ItemStack.matches`). +fn changed_slots( + before: &[Option], + m: &horizon_client::menu::Menu, +) -> Vec<(i16, Option)> { + (0..m.slot_count()) + .filter(|&i| m.slot(i) != before.get(i).and_then(Option::as_ref)) + .map(|i| (i as i16, m.slot(i).cloned())) + .collect() +} + +/// ServerboundContainerClickPacket's `ContainerInput` ordinal. +pub(super) fn input_ordinal(input: Input) -> i32 { + match input { + Input::Pickup => 0, + Input::QuickMove => 1, + Input::Swap => 2, + Input::Clone => 3, + Input::Throw => 4, + Input::QuickCraft => 5, + Input::PickupAll => 6, + } +} + +/// The view distance a client asks for: its render distance, which Horizon +/// lets go past vanilla's 32 (a vanilla server still caps it at its own). +fn client_view_distance(render_distance: i32) -> i8 { + render_distance.clamp(2, i32::from(i8::MAX)) as i8 +} + #[cfg(test)] mod tests { use super::Game; diff --git a/crates/horizon-client/src/game/remote_objects.rs b/crates/horizon-client/src/game/remote_objects.rs new file mode 100644 index 000000000..12a15bc34 --- /dev/null +++ b/crates/horizon-client/src/game/remote_objects.rs @@ -0,0 +1,270 @@ +//! Boats, minecarts, armor stands, item frames and paintings on a server's +//! client (`ClientPacketListener.handleAddEntity`, `handleSetEntityData`, +//! `handleSetEquipment`): the server simulates them, the client places them +//! where it says and interpolates their moves like a mob's. +use super::Game; +use horizon_client::entities::{ArmorStand, ItemFrame, Painting}; +use horizon_core::geometry::Vec3; +use horizon_protocol::entity_data::Value; +use std::sync::Arc; + +impl Game<'_> { + /// `handleAddEntity` for an object type; false when `kind` isn't one. + /// Hanging entities come at their block, with their direction as the + /// spawn data (`Direction.from3DDataValue`). + pub(super) fn spawn_remote_object( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + yaw: f32, + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let block = position.map(|v| v.floor() as i32); + self.remove_remote_object(id); + if let Some(cart) = super::minecarts::CartKind::from_id(kind) { + let mut c = super::minecarts::Minecart::new(id, cart, at); + c.yaw = yaw; + c.previous_yaw = yaw; + self.carts.push(c); + } else if let Some((wood, chest)) = super::boats::any_boat_wood(kind) + && self.boat_models.has(wood, chest) + { + let mut b = super::boats::Boat::new(id, Arc::from(wood), at, yaw); + if chest { + b = b.with_chest(); + } + self.boats.push(b); + } else if kind == "minecraft:armor_stand" { + self.armor_stands.push(ArmorStand::new(id, at, yaw)); + } else if kind == "minecraft:item_frame" || kind == "minecraft:glow_item_frame" { + self.item_frames.push(ItemFrame { + id, + pos: block, + facing: data.clamp(0, 5) as u8, + glow: kind == "minecraft:glow_item_frame", + item: None, + rotation: 0, + drop_chance: 1.0, + fixed: false, + invisible: false, + check_interval: 0, + }); + } else if kind == "minecraft:painting" { + // The variant comes with the entity data; until then the + // registry's first one (VariantUtils.getAny). + let (variant, width, height) = self + .remote_painting_variant(0) + .map_or((Arc::from("minecraft:kebab"), 1, 1), |v| { + (v.id, v.width, v.height) + }); + // Direction 3D data value (north 2, south 3, west 4, east 5) to 2D. + let facing = match data { + 2 => 2, + 4 => 1, + 5 => 3, + _ => 0, + }; + self.paintings.push(Painting { + id, + pos: block, + facing, + variant, + width, + height, + check_interval: 0, + }); + } else { + return false; + } + true + } + + /// A `painting_variant` by its network id, from the server's registry. + fn remote_painting_variant(&self, id: i32) -> Option { + let r = self.remote.as_ref()?; + let name = r.registries.name("minecraft:painting_variant", id)?; + self.painting_variants.get(name).cloned() + } + + /// `handleSetEntityData` for an object: what changes how it looks. + pub(super) fn remote_object_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if self.item_frames.iter().any(|f| f.id == id) { + // HangingEntity.DATA_DIRECTION, ItemFrame.DATA_ITEM and DATA_ROTATION. + let item = match (index, value) { + (9, Value::Item(stack)) => Some(self.to_stack(stack)), + _ => None, + }; + let Some(f) = self.item_frames.iter_mut().find(|f| f.id == id) else { + continue; + }; + match (index, value) { + (8, Value::Id(d)) => f.facing = (*d).clamp(0, 5) as u8, + (10, Value::Int(r)) => f.rotation = r.rem_euclid(8) as u8, + _ => {} + } + if let Some(item) = item { + f.item = item; + } + } else if self.paintings.iter().any(|p| p.id == id) { + // Painting.DATA_PAINTING_VARIANT_ID: a registry holder (id + 1). + if let (9, Value::Id(holder)) = (index, value) + && let Some(v) = self.remote_painting_variant(holder - 1) + && let Some(p) = self.paintings.iter_mut().find(|p| p.id == id) + { + p.variant = v.id; + p.width = v.width; + p.height = v.height; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + match (index, value) { + (0, Value::Byte(flags)) => a.invisible = flags & 0x20 != 0, + (9, Value::Float(health)) => a.health = *health, + // ArmorStand.DATA_CLIENT_FLAGS. + (15, Value::Byte(flags)) => { + a.small = flags & 1 != 0; + a.show_arms = flags & 4 != 0; + a.no_base_plate = flags & 8 != 0; + a.marker = flags & 16 != 0; + } + _ => {} + } + } else if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + // VehicleEntity's hurt, direction and damage; the paddles. + match (index, value) { + (8, Value::Int(v)) => b.hurt_time = *v, + (9, Value::Int(v)) => b.hurt_dir = *v, + (10, Value::Float(v)) => b.damage = *v, + (11, Value::Bool(v)) => b.paddling[0] = *v, + (12, Value::Bool(v)) => b.paddling[1] = *v, + _ => {} + } + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + match (index, value) { + (8, Value::Int(v)) => c.hurt_time = *v, + (9, Value::Int(v)) => c.hurt_dir = *v, + (10, Value::Float(v)) => c.damage = *v, + _ => {} + } + } + } + } + + /// `handleSetEquipment` for an armor stand (EquipmentSlot ordinals 0 to + /// 5: main hand, off hand, feet, legs, chest, head, its storage order). + pub(super) fn remote_object_equipment( + &mut self, + id: i32, + slots: &[(u8, Option)], + ) { + if !self.armor_stands.iter().any(|a| a.id == id as u32) { + return; + } + let items: Vec<_> = slots + .iter() + .map(|(slot, stack)| (usize::from(*slot), self.to_stack(stack))) + .collect(); + if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id as u32) { + for (slot, item) in items { + if let Some(s) = a.equipment.get_mut(slot) { + *s = item; + } + } + } + } + + /// A move's rotation and ground state for an object. + pub(super) fn turn_remote_object(&mut self, id: i32, yaw: Option, on_ground: bool) { + let id = id as u32; + if let Some(b) = self.boats.iter_mut().find(|b| b.id == id) { + if let Some(yaw) = yaw { + b.yaw = yaw; + } + b.on_ground = on_ground; + } else if let Some(c) = self.carts.iter_mut().find(|c| c.id == id) { + if let Some(yaw) = yaw { + c.yaw = yaw; + } + } else if let Some(a) = self.armor_stands.iter_mut().find(|a| a.id == id) { + if let Some(yaw) = yaw { + a.yaw = yaw; + } + a.on_ground = on_ground; + } + } + + /// One tick of interpolation: `step` moves a position a step toward + /// the entity's last sent one, if it has a move in progress. + pub(super) fn tick_remote_objects(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for c in &mut self.carts { + c.previous = c.position; + c.previous_yaw = c.yaw; + c.position = step(c.id, c.position); + } + for b in &mut self.boats { + b.previous = b.position; + b.previous_yaw = b.yaw; + b.position = step(b.id, b.position); + } + for a in &mut self.armor_stands { + a.position = step(a.id, a.position); + } + } + + /// The boats, minecarts, armor stands, item frames and paintings in the + /// level (a server's client: the ones it was sent), for `status`. + pub(super) fn objects_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for b in &self.boats { + out.push(json!({"id": b.id, "kind": b.entity_type(), "position": at(b.position), "yaw": b.yaw})); + } + for c in &self.carts { + out.push( + json!({"id": c.id, "kind": c.kind.id(), "position": at(c.position), "yaw": c.yaw}), + ); + } + for a in &self.armor_stands { + let items: Vec<_> = a + .equipment + .iter() + .map(|i| i.as_ref().map(|i| &*i.item)) + .collect(); + out.push(json!({"id": a.id, "kind": "minecraft:armor_stand", "position": at(a.position), "yaw": a.yaw, + "small": a.small, "arms": a.show_arms, "no_base_plate": a.no_base_plate, "equipment": items})); + } + for f in &self.item_frames { + out.push( + json!({"id": f.id, "kind": f.kind(), "position": f.pos, "facing": f.facing, + "item": f.item.as_ref().map(|i| &*i.item), "rotation": f.rotation}), + ); + } + for p in &self.paintings { + out.push(json!({"id": p.id, "kind": "minecraft:painting", "position": p.pos, "facing": p.facing, + "variant": &*p.variant})); + } + out + } + + /// Every object a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_objects(&mut self) { + self.carts.clear(); + self.boats.clear(); + self.armor_stands.clear(); + self.item_frames.clear(); + self.paintings.clear(); + } + + pub(super) fn remove_remote_object(&mut self, id: u32) { + self.carts.retain(|c| c.id != id); + self.boats.retain(|b| b.id != id); + self.armor_stands.retain(|a| a.id != id); + self.item_frames.retain(|f| f.id != id); + self.paintings.retain(|p| p.id != id); + } +} diff --git a/crates/horizon-client/src/game/remote_projectiles.rs b/crates/horizon-client/src/game/remote_projectiles.rs new file mode 100644 index 000000000..23cbb1913 --- /dev/null +++ b/crates/horizon-client/src/game/remote_projectiles.rs @@ -0,0 +1,229 @@ +//! Primed TNT, falling blocks, projectiles, tridents, firework rockets and +//! end crystals on a server's client (`ClientPacketListener.handleAddEntity` +//! and `handleSetEntityData`): the server simulates them, the client draws +//! them where it says and interpolates their moves. +use super::{FallingBlock, Game}; +use horizon_client::projectiles::{Projectile, ProjectileKind}; +use horizon_core::{geometry::Vec3, position::BlockPos}; +use horizon_protocol::entity_data::Value; +use horizon_world::registry::BlockStateId; + +/// The projectile a type id names, as Horizon models it. +fn projectile_kind(kind: &str) -> Option { + Some(match kind { + "minecraft:arrow" | "minecraft:spectral_arrow" => ProjectileKind::Arrow { + base_damage: 2.0, + critical: false, + effect: None, + }, + "minecraft:snowball" => ProjectileKind::Snowball, + "minecraft:egg" => ProjectileKind::Egg, + "minecraft:ender_pearl" => ProjectileKind::EnderPearl, + "minecraft:small_fireball" => ProjectileKind::SmallFireball, + "minecraft:fireball" => ProjectileKind::LargeFireball { power: 1 }, + "minecraft:llama_spit" => ProjectileKind::LlamaSpit, + "minecraft:wind_charge" => ProjectileKind::WindCharge, + "minecraft:breeze_wind_charge" => ProjectileKind::BreezeWindCharge, + "minecraft:wither_skull" => ProjectileKind::WitherSkull { dangerous: false }, + _ => return None, + }) +} + +impl Game<'_> { + /// `handleAddEntity` for these types; false when `kind` isn't one. + pub(super) fn spawn_remote_projectile( + &mut self, + id: i32, + kind: &str, + position: [f64; 3], + rotation: (f32, f32), + velocity: [f64; 3], + data: i32, + ) -> bool { + let id = id as u32; + let at = Vec3::new(position[0], position[1], position[2]); + let velocity = Vec3::new(velocity[0], velocity[1], velocity[2]); + let (yaw, pitch) = rotation; + self.remove_remote_projectile(id); + match kind { + "minecraft:tnt" => self.tnts.push(super::tnt::PrimedTnt { + id, + position: at, + previous: at, + velocity, + fuse: 80, + on_ground: false, + }), + // FallingBlockEntity.recreateFromPacket: the block state is the data. + "minecraft:falling_block" => self.falling.push(FallingBlock { + id, + state: BlockStateId(data.max(0) as u32), + start_pos: BlockPos::default(), + position: at, + previous: at, + velocity, + age: 0, + no_gravity: false, + drop_item: false, + fall_distance: 0.0, + damage: Default::default(), + saved: None, + }), + "minecraft:trident" => { + let mut t = super::trident::ThrownTrident::remote(id, at, yaw, pitch); + t.velocity = velocity; + self.tridents.push(t); + } + "minecraft:firework_rocket" => { + self.rockets + .push(super::fireworks::Rocket::remote(id, at, velocity)); + } + "minecraft:end_crystal" => self.crystals.push(super::dragon::Crystal { + id, + position: at, + show_bottom: true, + time: 0, + beam: None, + invulnerable: false, + }), + _ => { + let Some(k) = projectile_kind(kind) else { + return false; + }; + let mut p = Projectile::new(k, at, None); + p.id = id; + p.velocity = velocity; + p.yaw = yaw; + p.pitch = pitch; + self.creatures.projectiles.push(p); + } + } + true + } + + /// `handleSetEntityData` for these types: what changes how they look. + pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) { + let id = id as u32; + for (index, _, value) in values { + if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id) { + // PrimedTnt.DATA_FUSE_ID. + if let (8, Value::Int(fuse)) = (index, value) { + t.fuse = *fuse; + } + } else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id) { + // FallingBlockEntity.DATA_START_POS (the model's seed). + if let (8, Value::Pos(p)) = (index, value) { + f.start_pos = BlockPos::new(p[0], p[1], p[2]); + } + } else if let Some(c) = self.crystals.iter_mut().find(|c| c.id == id) { + // EndCrystal.DATA_BEAM_TARGET and DATA_SHOW_BOTTOM. + match (index, value) { + (8, Value::OptPos(beam)) => c.beam = *beam, + (9, Value::Bool(show)) => c.show_bottom = *show, + _ => {} + } + } else if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + match (&mut p.kind, index, value) { + // AbstractArrow.ID_FLAGS (critical) and IN_GROUND. + (ProjectileKind::Arrow { critical, .. }, 8, Value::Byte(flags)) => { + *critical = flags & 1 != 0; + } + (ProjectileKind::Arrow { .. }, 10, Value::Bool(in_ground)) => { + p.stuck = *in_ground; + } + // WitherSkull.DATA_DANGEROUS. + (ProjectileKind::WitherSkull { dangerous }, 8, Value::Bool(d)) => { + *dangerous = *d; + } + _ => {} + } + } + } + } + + /// A move's rotation for a projectile or trident. + pub(super) fn turn_remote_projectile(&mut self, id: i32, rotation: Option<(f32, f32)>) { + let (id, Some((yaw, pitch))) = (id as u32, rotation) else { + return; + }; + if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| p.id == id) { + p.yaw = yaw; + p.pitch = pitch; + } else if let Some(t) = self.tridents.iter_mut().find(|t| t.id == id) { + t.yaw = yaw; + t.pitch = pitch; + } + } + + /// One tick of interpolation, as `tick_remote_objects`. + pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) { + for t in &mut self.tnts { + t.previous = t.position; + t.position = step(t.id, t.position); + } + for f in &mut self.falling { + f.previous = f.position; + f.age += 1; + f.position = step(f.id, f.position); + } + for p in &mut self.creatures.projectiles { + p.previous = p.position; + p.age += 1; + p.position = step(p.id, p.position); + } + for t in &mut self.tridents { + let id = t.id; + t.remote_step(|at| step(id, at)); + } + for r in &mut self.rockets { + let id = r.id; + r.remote_step(|at| step(id, at)); + } + for c in &mut self.crystals { + c.time += 1; + c.position = step(c.id, c.position); + } + } + + pub(super) fn remove_remote_projectile(&mut self, id: u32) { + self.tnts.retain(|t| t.id != id); + self.falling.retain(|f| f.id != id); + self.creatures.projectiles.retain(|p| p.id != id); + self.tridents.retain(|t| t.id != id); + self.rockets.retain(|r| r.id != id); + self.crystals.retain(|c| c.id != id); + } + + /// Every one a server sent (a new connection, level or dimension). + pub(super) fn clear_remote_projectiles(&mut self) { + self.tnts.clear(); + self.falling.clear(); + self.creatures.projectiles.clear(); + self.tridents.clear(); + self.rockets.clear(); + self.crystals.clear(); + } + + /// Their kind and place, for `status`. + pub(super) fn projectiles_status(&self) -> Vec { + use serde_json::json; + let at = |p: Vec3| [p.x, p.y, p.z]; + let mut out = Vec::new(); + for t in &self.tnts { + out.push(json!({"id": t.id, "kind": "minecraft:tnt", "position": at(t.position), "fuse": t.fuse})); + } + for f in &self.falling { + out.push(json!({"id": f.id, "kind": "minecraft:falling_block", "position": at(f.position), "state": f.state.0})); + } + for c in &self.crystals { + out.push(json!({"id": c.id, "kind": "minecraft:end_crystal", "position": at(c.position), "show_bottom": c.show_bottom})); + } + for t in &self.tridents { + out.push(json!({"id": t.id, "kind": "minecraft:trident", "position": at(t.position)})); + } + for p in &self.creatures.projectiles { + out.push(json!({"id": p.id, "kind": format!("{:?}", p.kind).split([' ', '{']).next().unwrap_or(""), "position": at(p.position)})); + } + out + } +} diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 10add4668..21a5aee46 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -11,6 +11,7 @@ pub const HELP: &[&str] = &[ "fill X1 Y1 Z1 X2 Y2 Z2 STATE fill a box with a block state without updates", "particle NAME X Y Z [DX DY DZ] [COUNT] spawn particles (vanilla /particle spread)", "signedit X Y Z [front|back] open the sign editor for the sign at X Y Z", + "section-draws [flat|indirect] how terrain sections are drawn (A/B checks); replies the mode", ]; impl Game<'_> { @@ -126,7 +127,7 @@ impl Game<'_> { let entity = horizon_client::containers::BlockEntity::for_block(&name) .filter(|e| matches!(e, horizon_client::containers::BlockEntity::Sign(_))) .ok_or("no sign there")?; - self.world.block_entities.entry(key).or_insert(entity); + self.world.block_entities.get_or_insert_with(key, || entity); self.open_sign_editor(key, words.get(4) != Some(&"back")); Ok(Some(json!({ "ok": true }))) } diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index 5a31dfd5c..aa94d5b17 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -324,7 +324,7 @@ impl Game<'_> { ) .unwrap_or_else(|_| VoxelShape::empty()) } - fn block_in_tag(&self, tag: &str, block: &str) -> bool { + pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool { self.res .items .block_tags diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 60894a14e..4e715c7b7 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -130,7 +130,7 @@ impl Game<'_> { /// `ScoreHolder.getScoreboardName`: the player's name, an entity's UUID. pub(super) fn holder_name(&mut self, t: Target) -> Option { match t { - Target::Player => Some(PLAYER_NAME.to_owned()), + Target::Player => Some(self.acting_player_name().to_owned()), Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), _ => None, } @@ -146,7 +146,7 @@ impl Game<'_> { } /// The entity with the given scoreboard name. fn target_of_holder(&self, name: &str) -> Option { - if name == PLAYER_NAME { + if name == self.acting_player_name() { return Some(Target::Player); } let uuid = uuid_from_text(name).filter(|_| name.len() == 36)?; @@ -379,8 +379,9 @@ impl Game<'_> { /// `ServerPlayer.die`: the death count. pub(super) fn score_player_died(&mut self) { let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; - board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, PLAYER_NAME, Some(&display), |v| { + board.for_all_objectives_with(sb::CRITERIA_DEATH_COUNT, &me, Some(&display), |v| { v.wrapping_add(1) }); // A respawned player has everything to record again. @@ -390,25 +391,21 @@ impl Game<'_> { pub(super) fn score_player_killed(&mut self, victim: Target) { let victim_name = self.holder_name(victim); let display = self.player_display_comp(); + let me = self.acting_player_name().to_owned(); let board = &mut self.score.board; let inc = |v: i32| v.wrapping_add(1); - board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(sb::CRITERIA_TOTAL_KILLS, &me, Some(&display), inc); if victim == Target::Player { - board.for_all_objectives_with( - sb::CRITERIA_PLAYER_KILLS, - PLAYER_NAME, - Some(&display), - inc, - ); + board.for_all_objectives_with(sb::CRITERIA_PLAYER_KILLS, &me, Some(&display), inc); } let color_of = |board: &Scoreboard, name: &str| board.players_team(name).and_then(|t| t.color.clone()); if let Some(victim_name) = victim_name { if let Some(color) = color_of(board, &victim_name) { let criteria = format!("teamkill.{color}"); - board.for_all_objectives_with(&criteria, PLAYER_NAME, Some(&display), inc); + board.for_all_objectives_with(&criteria, &me, Some(&display), inc); } - if let Some(color) = color_of(board, PLAYER_NAME) { + if let Some(color) = color_of(board, &me) { let criteria = format!("killedByTeam.{color}"); board.for_all_objectives(&criteria, &victim_name, inc); } @@ -430,7 +427,7 @@ impl Game<'_> { self.score.board.players_team(&uuid_text(*uuid)) } pub(super) fn player_team(&self) -> Option<&sb::Team> { - self.score.board.players_team(PLAYER_NAME) + self.score.board.players_team(self.acting_player_name()) } /// The teams of the player and of the mobs on one (empty without teams). pub(super) fn mob_teams(&self) -> horizon_client::mobs::Teams { @@ -464,16 +461,17 @@ impl Game<'_> { } /// `Player.getDisplayName`: the name with the team's prefix, suffix and colour. pub(super) fn player_display_comp(&self) -> Comp { - let name = literal(PLAYER_NAME); + let name = literal(self.acting_player_name()); match self.player_team() { Some(t) => t.formatted_name_comp(&name), None => name, } } pub(super) fn player_display_text(&self) -> Text { + let name = Text::literal(self.acting_player_name()); match self.player_team() { - Some(t) => t.formatted_name(Text::literal(PLAYER_NAME)), - None => Text::literal(PLAYER_NAME), + Some(t) => t.formatted_name(name), + None => name, } } @@ -600,9 +598,7 @@ impl Game<'_> { /// objective. pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) { use horizon_client::tab_list::{self, TabInputs}; - let chatting = self.remote.is_some() && self.remote_chat_open(); let key = self.screen == super::Screen::Playing - && !chatting && self.keys.contains(&winit::keyboard::KeyCode::Tab); let (players, online_mode, upside_down) = match self.remote_tab_players() { Some(remote) => remote, @@ -688,7 +684,7 @@ impl Env for GameEnv<'_, '_> { .collect() } fn named(&mut self, name: &str) -> Holder { - if name.eq_ignore_ascii_case(PLAYER_NAME) && self.g.player.is_some() { + if name.eq_ignore_ascii_case(self.g.acting_player_name()) && self.g.player.is_some() { return self .g .holder_for(Target::Player) @@ -705,7 +701,7 @@ impl Env for GameEnv<'_, '_> { None => Some(Target::Player), }?; let name = match entity { - Target::Player => PLAYER_NAME.to_owned(), + Target::Player => self.g.acting_player_name().to_owned(), Target::Mob(id) | Target::Item(id) => uuid_text(self.g.uuid_for(id)), _ => return None, }; diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 6901200f1..72a91d7da 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -6,13 +6,14 @@ use super::{Game, Result}; use horizon_client::{ containers::BlockEntity, + fast_hash::{FxHashMap, FxHashSet}, mobs::{Mob, Species, Who, warden}, particles::{ParticleOptions, ParticleType}, sculk::{self, Context, Info, SculkEntity, SculkKind, WardenSpawnTracker}, }; use horizon_core::{geometry::Direction, position::BlockPos, random::RandomSource}; use horizon_world::registry::BlockStateId; -use std::collections::{HashMap, HashSet}; +use std::collections::HashSet; use winit::keyboard::KeyCode; pub const HELP: &[&str] = &[ @@ -70,8 +71,9 @@ pub(super) struct SculkState { /// The sculk block entities in the order they were added. index: Index, pub known: HashSet<(i32, i32)>, - steps: HashMap, - damaged: HashMap, + // Keyed by mob ids the server gives out: the fast hasher is safe. + steps: FxHashMap, + damaged: FxHashMap, last_health: Option, /// The darkness effect's blend factor, previous and current tick. darkness: (f32, f32), @@ -80,6 +82,15 @@ pub(super) struct SculkState { ticks: u32, pub tracker_loaded: bool, } + +impl SculkState { + /// Exchange the level-held parts (its sculk block entities and the + /// chunks scanned for them) with another level's (game/levels.rs). + pub(super) fn swap_level(&mut self, other: &mut Self) { + std::mem::swap(&mut self.index, &mut other.index); + std::mem::swap(&mut self.known, &mut other.known); + } +} /// An insertion-ordered set of block positions (`Level.blockEntityTickers` /// keeps the order block entities were added in). #[derive(Default)] @@ -301,11 +312,11 @@ impl Game<'_> { self.world.watched = t.kinds.iter().map(|k| *k != 0).collect(); self.sculk.tables = t; } - fn kind_of_state(&self, state: u16) -> u8 { + fn kind_of_state(&self, state: u32) -> u8 { self.sculk .tables .kinds - .get(usize::from(state)) + .get(state as usize) .copied() .unwrap_or(0) } @@ -345,10 +356,10 @@ impl Game<'_> { // SculkShriekerBlockEntity.preRemoveSideEffects. if old_kind == KIND_SHRIEKER && let Some(BlockEntity::Sculk(e)) = self.world.block_entities.get(&key) - && self.shrieker_shrieking(BlockStateId(u32::from(old))) + && self.shrieker_shrieking(BlockStateId(old)) { let warning = e.warning_level; - self.shrieker_respond(key, BlockStateId(u32::from(old)), warning); + self.shrieker_respond(key, BlockStateId(old), warning); } if matches!( self.world.block_entities.get(&key), @@ -375,17 +386,14 @@ impl Game<'_> { let y0 = MIN_Y + s as i32 * 16; // Without a sculk state in its palette, no block of the section // is one: most sections are passed over without reading a block. - if !section - .blocks - .maybe_has(|v| u16::try_from(v).is_ok_and(|v| self.kind_of_state(v) != 0)) - { + if !section.blocks.maybe_has(|v| self.kind_of_state(v) != 0) { continue; } if section.blocks.uniform().is_some() { // A uniform section of sculk blocks does not exist. continue; } - let mut a = [0u16; 4096]; + let mut a = [0u32; 4096]; section.unpack(&mut a); for (i, v) in a.iter().enumerate() { if self.kind_of_state(*v) != 0 { @@ -855,12 +863,12 @@ impl Game<'_> { let state = self.world.block(key.0, key.1, key.2); let is_warden = matches!(who, Who::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); - match self.kind_of_state(state.0 as u16) { + match self.kind_of_state(state.0) { KIND_SENSOR | KIND_CALIBRATED => { if is_warden || !self.res.behaviours.sculk_sensor_can_activate(state) { continue; } - let calibrated = self.kind_of_state(state.0 as u16) == KIND_CALIBRATED; + let calibrated = self.kind_of_state(state.0) == KIND_CALIBRATED; if calibrated { let back = self.calibrated_signal(key); if back != 0 && back != 1 { @@ -1171,6 +1179,9 @@ impl Game<'_> { /// `Warden.applyDarknessAround` / `MobEffectUtil.addEffectToPlayersAround`. pub(super) fn apply_darkness(&mut self, at: [f64; 3], radius: f64) { + self.for_each_player(|g| g.darkness_on_player(at, radius)); + } + fn darkness_on_player(&mut self, at: [f64; 3], radius: f64) { if self.creative || self.spectator() { return; } @@ -1519,7 +1530,7 @@ impl Game<'_> { } } } - let alive: HashSet = self.mobs.iter().map(|m| m.id).collect(); + let alive: FxHashSet = self.mobs.iter().map(|m| m.id).collect(); self.sculk.damaged.retain(|id, _| alive.contains(id)); self.sculk.steps.retain(|who, _| match who { Who::Player => true, diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index d5b1e4d95..6c0ec48e7 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -1,59 +1,92 @@ -//! A server's player between dimensions. +//! A server's players between dimensions. //! -//! The server holds one level at a time, as the in-frame game does. While a -//! single player is online (single player on the server thread, or a world -//! with one player in it) that level follows the player through Nether and -//! End portals, and back to the Overworld when the player respawns. The swap -//! is the in-frame path's (`switch_level`, the portal plans, the arrival -//! search); the player hears it as `ServerPlayer.teleport` into another -//! level: a Respawn packet keeping all data, then a teleport to the exit once -//! the destination has loaded. With several players online the portals do -//! not take anyone yet: that needs the server to hold every level. +//! A server holds a level per dimension (game/levels.rs). A player who steps +//! into a Nether or End portal moves to the destination's level, which opens +//! if nobody was there: the swap is the in-frame path's portal plans and +//! arrival search, and the player hears it as `ServerPlayer.teleport` into +//! another level: a Respawn packet keeping all data, then a teleport to the +//! exit once the destination has loaded around them. -use super::nether_portal::PLAYER_DELAY; +use super::nether_portal::{PLAYER_DELAY, Plan}; use super::{Dim, Game, lan::LanHost}; use horizon_client::lan::hub::TickCtx; use horizon_core::{geometry::Vec3, position::BlockPos}; -/// A trip under way: the level has changed and its chunks are loading -/// around `target`. +/// A trip under way: the player is in the destination's level, whose +/// chunks are loading around `target`. pub(super) struct Trip { conn: u32, + dim: Dim, target: Vec3, - /// Through an End portal (or out of the End by respawning). + /// Through an End portal. end: bool, + /// The Nether portal plan, whose exit is found or built on arrival. + plan: Option, + /// Sent by a command: the player is already where it goes. + placed: bool, } -/// The lone player's box: Player's standing dimensions. +/// `TeleportCommand` into another level for a server's player: where, and +/// the rotation it sets (none keeps the player's). +pub(super) struct LevelTeleport { + pub conn: u32, + pub dim: Dim, + pub at: [f64; 3], + pub rotation: Option<[f32; 2]>, +} + +/// A player's box: Player's standing dimensions. const WIDTH: f64 = 0.6; const HEIGHT: f64 = 1.8; +impl Trip { + pub(super) fn is(&self, conn: u32) -> bool { + self.conn == conn + } +} + impl Game<'_> { /// Whether `conn` is between two levels: the server leaves its body /// alone until it arrives. pub(super) fn on_server_trip(&self, conn: u32) -> bool { - self.server_trip.as_ref().is_some_and(|t| t.conn == conn) + self.server_trips.iter().any(|t| t.conn == conn) } - /// Per server tick, after the guests' own: `Entity.handlePortal` for the - /// lone player (Nether portals count up their transition time, End - /// portals take it at once), or the arrival of the trip under way. + /// Per server tick in each level, after the guests' own: the arrivals of + /// the trips into this level, then `Entity.handlePortal` for each player + /// in it (Nether portals count up their transition time, End portals + /// take them at once). pub(super) fn tick_server_travel(&mut self, host: &mut LanHost) { if self.options.dedicated.is_none() { return; } - if self.server_trip.is_some() { - self.arrive_server_trip(host); - return; + self.arrive_server_trips(host); + let conns: Vec = host + .hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| g.conn) + .collect(); + for conn in conns { + if self.on_server_trip(conn) { + continue; + } + // `Entity.portalProcess` and `portalCooldown` are the player's own. + let mut portal = host.play.entry(conn).or_default().portal; + std::mem::swap(&mut self.portals.player, &mut portal); + self.handle_server_portal(host, conn); + std::mem::swap(&mut self.portals.player, &mut portal); + host.play.entry(conn).or_default().portal = portal; } - let [g] = host.hub.guests.as_slice() else { + } + + /// `Entity.handlePortal` for one player, whose portal state is in place. + fn handle_server_portal(&mut self, host: &mut LanHost, conn: u32) { + let Some(g) = host.hub.guest(conn) else { return; }; - if !g.placed || !g.loaded || g.dead || g.spectator() { - return; - } - let (conn, at, invulnerable, sleeping) = ( - g.conn, + let (at, invulnerable, sleeping) = ( Vec3::new(g.position[0], g.position[1], g.position[2]), g.creative(), g.sleeping, @@ -70,7 +103,7 @@ impl Game<'_> { } else { Dim::End }; - self.start_server_trip(host, conn, target, true); + self.start_server_trip(host, conn, target, None); } // Entity.setAsInsidePortal while cooling down restarts the cooldown. self.portals.player.cooldown = 10; @@ -93,11 +126,10 @@ impl Game<'_> { if !self.may_enter(plan.dim) { return; } - self.portals.travel = Some(plan); - self.start_server_trip(host, conn, plan.dim, false); + self.start_server_trip(host, conn, plan.dim, Some(plan)); } - /// A Nether portal block the lone player's box is in. + /// A Nether portal block a player's box is in. fn nether_portal_inside(&self, at: Vec3) -> Option { let w = WIDTH / 2.0 - 1.0e-5; let lo = [at.x - w, at.y + 1.0e-5, at.z - w]; @@ -114,9 +146,16 @@ impl Game<'_> { None } - /// The level swap, and the player told it is in the new level at the - /// approximate exit while it loads. - fn start_server_trip(&mut self, host: &mut LanHost, conn: u32, target: Dim, end: bool) { + /// The player moves to `target`'s level (opened if nobody was there) + /// and is told it is there, at the approximate exit, while it loads. The + /// level whose tick is running is put back in place afterwards. + fn start_server_trip( + &mut self, + host: &mut LanHost, + conn: u32, + target: Dim, + plan: Option, + ) { let Some(i) = host.hub.guests.iter().position(|g| g.conn == conn) else { return; }; @@ -124,105 +163,142 @@ impl Game<'_> { let from = Vec3::new(g.position[0], g.position[1], g.position[2]); let yaw = g.yaw; let source = self.dim; + let end = plan.is_none(); + // Coordinates scale by 8 between the Overworld and the Nether; an + // End portal has fixed destinations. + let scale = match (source, target) { + (Dim::Overworld, Dim::Nether) | (Dim::End, Dim::Nether) => 1.0 / 8.0, + (Dim::Nether, Dim::Overworld) => 8.0, + _ => 1.0, + }; self.end_portal_travel = end; - let switched = self.switch_level(target, from); + let scaled = self.end_destination(target).unwrap_or(Vec3::new( + from.x * scale, + from.y, + from.z * scale, + )); self.end_portal_travel = false; - let destination = match switched { - Ok(d) => d, - Err(e) => { - log::error!("could not open {}: {e}", target.id()); - return; - } + if let Err(e) = self.enter_level(Some(host), target) { + log::error!("could not open {}: {e}", target.id()); + return; + } + let destination = match plan { + Some(plan) => self.arrival_centre(&plan), + None => scaled, }; - let destination = match self.portals.travel { - Some(plan) if !end => self.arrival_centre(&plan), - _ => destination, - }; - host.hub.set_dimension(target.id()); let at = [destination.x, destination.y, destination.z]; let ctx = self.server_ctx(); - host.hub.change_level(i, at, yaw, &ctx); + // TeleportTransition.PLAY_PORTAL_SOUND. + host.hub.change_level(i, at, yaw, None, true, &ctx); self.as_guest(host, conn, |g| g.trigger_dimension(source, target)); - self.server_trip = Some(Trip { + self.server_trips.push(Trip { conn, + dim: target, target: destination, end, + plan, + placed: false, }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } } - /// Once the destination has loaded around the trip's target: the exit - /// (the Nether portal found or built, the End platform, the Overworld's - /// spawn column) and the teleport there. - fn arrive_server_trip(&mut self, host: &mut LanHost) { - let Some(trip) = self.server_trip.as_ref() else { - return; - }; - let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { - // They left on the way. - self.server_trip = None; - self.portals.travel = None; - return; - }; - let (cx, cz) = ( - (trip.target.x.floor() as i32) >> 4, - (trip.target.z.floor() as i32) >> 4, - ); - if !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { - return; + /// The trips into the level in place whose destination has loaded + /// around their target: the exit (the Nether portal found or built, the + /// End platform, the Overworld's spawn column) and the teleport there. + fn arrive_server_trips(&mut self, host: &mut LanHost) { + let mut k = 0; + while k < self.server_trips.len() { + let trip = &self.server_trips[k]; + let Some(i) = host.hub.guests.iter().position(|g| g.conn == trip.conn) else { + // They left on the way. + self.server_trips.remove(k); + continue; + }; + let (cx, cz) = ( + (trip.target.x.floor() as i32) >> 4, + (trip.target.z.floor() as i32) >> 4, + ); + if trip.dim != self.dim + || !(-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) + { + k += 1; + continue; + } + let trip = self.server_trips.remove(k); + if trip.placed { + continue; + } + self.resolve_arrivals(); + let yaw = host.hub.guests[i].yaw; + let (position, yaw) = if trip.end { + match self.end_arrival(trip.target) { + Ok((at, turned)) => (at, turned.unwrap_or(yaw)), + Err(e) => { + log::error!("End arrival: {e}"); + (trip.target, yaw) + } + } + } else { + let exit = trip + .plan + .as_ref() + .and_then(|plan| self.nether_exit_portal(plan)); + match (trip.plan, exit) { + (Some(plan), Some(exit)) => { + let (at, rotation) = self.arrival(&plan, exit); + (at, yaw + rotation) + } + _ => (trip.target, yaw), + } + }; + // Player.getDimensionChangingDelay. + host.play.entry(trip.conn).or_default().portal.cooldown = 10; + let g = &mut host.hub.guests[i]; + g.yaw = yaw; + // A new body at the exit: no fall distance or motion carried over. + g.motion = None; + host.hub + .teleport(i, Some([position.x, position.y, position.z])); } - let Some(trip) = self.server_trip.take() else { - return; - }; - self.resolve_arrivals(); - let (position, yaw) = if trip.end { - match self.end_arrival(trip.target) { - Ok((at, yaw)) => (at, yaw.unwrap_or(host.hub.guests[i].yaw)), - Err(e) => { - log::error!("End arrival: {e}"); - (trip.target, host.hub.guests[i].yaw) - } - } - } else { - let plan = self.portals.travel.take(); - let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); - match (plan, exit) { - (Some(plan), Some(exit)) => { - let (at, rotation) = self.arrival(&plan, exit); - (at, host.hub.guests[i].yaw + rotation) - } - _ => (trip.target, host.hub.guests[i].yaw), - } - }; - // Player.getDimensionChangingDelay. - self.portals.player.cooldown = 10; - let g = &mut host.hub.guests[i]; - g.yaw = yaw; - // A new body at the exit: no fall distance or motion carried over. - g.motion = None; - host.hub - .teleport(i, Some([position.x, position.y, position.z])); } - /// `PlayerList.respawn` away from the Overworld: the lone player's level - /// goes back to the Overworld first, where the world spawn is. - pub(super) fn respawn_level(&mut self, host: &mut LanHost) { - if self.options.dedicated.is_none() || self.dim == Dim::Overworld { - return; + /// The players the command just run sends to another level + /// (`ServerPlayer.teleport` from TeleportCommand): a Respawn packet + /// keeping all data and the teleport, with no portal sound. The server + /// leaves the body alone until the level has loaded around it. + pub(super) fn run_level_teleports(&mut self, host: &mut LanHost) { + for t in std::mem::take(&mut self.level_teleports) { + let Some(i) = host.hub.guests.iter().position(|g| g.conn == t.conn) else { + continue; + }; + let source = self.dim; + if let Err(e) = self.enter_level(Some(host), t.dim) { + log::error!("could not open {}: {e}", t.dim.id()); + continue; + } + let g = &mut host.hub.guests[i]; + let [yaw, pitch] = t.rotation.unwrap_or([g.yaw, g.pitch]); + // A new body there: no fall distance or motion carried over. + g.motion = None; + let ctx = self.server_ctx(); + host.hub + .change_level(i, t.at, yaw, Some(pitch), false, &ctx); + self.as_guest(host, t.conn, |g| g.trigger_dimension(source, t.dim)); + self.server_trips.retain(|trip| !trip.is(t.conn)); + self.server_trips.push(Trip { + conn: t.conn, + dim: t.dim, + target: Vec3::new(t.at[0], t.at[1], t.at[2]), + end: false, + plan: None, + placed: true, + }); + if let Err(e) = self.enter_level(Some(host), source) { + log::error!("could not reopen {}: {e}", source.id()); + } } - if host.hub.guests.len() != 1 { - return; - } - self.server_trip = None; - self.portals.travel = None; - self.end_portal_travel = true; - let from = self.spawn.unwrap_or(Vec3::ZERO); - let switched = self.switch_level(Dim::Overworld, from); - self.end_portal_travel = false; - if let Err(e) = switched { - log::error!("could not open the Overworld: {e}"); - return; - } - host.hub.set_dimension(Dim::Overworld.id()); } /// The hub's view of the server for packets sent outside its own tick. @@ -243,6 +319,7 @@ impl Game<'_> { }, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), + collision: Some(self.collision), } } } diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index ba7bd66a1..a2131f9b0 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -45,7 +45,7 @@ impl Game<'_> { .as_ref() .is_some_and(|t| t.contains(id)) } - fn load_entity_types(&mut self) { + pub(super) fn load_entity_types(&mut self) { if self.spawners.entity_types.is_some() { return; } @@ -63,32 +63,27 @@ impl Game<'_> { .unwrap_or_default(); self.spawners.entity_types = Some(types); } - /// Every spawner's server tick, then its client tick. - pub(super) fn tick_spawners(&mut self) -> Result<()> { - self.load_entity_types(); - let keys: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Spawner(_))) - .map(|(k, _)| *k) - .collect(); - for key in &keys { - let state = self.world.block(key.0, key.1, key.2); - if &*self.res.facts.get(state).name != "minecraft:spawner" { - continue; - } - let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.remove(key) - else { - continue; - }; - let result = self.server_tick_spawner(*key, &mut spawner); - self.world - .block_entities - .insert(*key, BlockEntity::Spawner(spawner)); - result?; + /// The server tick of the spawner at `key`, if its block is still a + /// spawner. Its client tick comes after every block entity's + /// (`client_tick_spawners`). + pub(super) fn tick_spawner(&mut self, key: Pos) -> Result<()> { + let state = self.world.block(key.0, key.1, key.2); + if &*self.res.facts.get(state).name != "minecraft:spawner" { + return Ok(()); } - for key in keys { + let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.take(&key) else { + return Ok(()); + }; + let result = self.server_tick_spawner(key, &mut spawner); + self.world + .block_entities + .put(key, BlockEntity::Spawner(spawner)); + result + } + /// The client ticks of these spawners, then the shown mobs of spawners + /// that are gone go. + pub(super) fn client_tick_spawners(&mut self, keys: &[Pos]) { + for &key in keys { self.client_tick_spawner(key); } let entities = &self.world.block_entities; @@ -98,7 +93,6 @@ impl Game<'_> { Some(BlockEntity::Spawner(_) | BlockEntity::TrialSpawner(_)) ) }); - Ok(()) } fn server_tick_spawner(&mut self, key: Pos, spawner: &mut Spawner) -> Result<()> { let pos = [key.0, key.1, key.2]; @@ -427,6 +421,15 @@ impl Game<'_> { * glam::Mat4::from_scale(glam::Vec3::splat(scale)); let light = self.world.light(key.0, key.1, key.2); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); + if mob.species() == horizon_client::mobs::Species::SulfurCube { + self.sulfur_cube_body_geometry( + mob, + alpha as f32, + horizon_client::mobs::render::base_transform_at(mob, alpha as f32, origin), + packed, + out, + ); + } horizon_client::mobs::render::render_posed( mob, alpha as f32, diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 8cd751548..332f06b23 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -1885,17 +1885,27 @@ impl Game<'_> { } else { self.pack.names.item(&stack.item) }; - let mut lines = vec![(name, color)]; + let display = horizon_client::item_tooltip::TooltipDisplay::for_stack(stack); + let mut lines = Vec::new(); + if display.name_visible(self.screen == Screen::Creative) { + lines.push((name, color)); + } let translate = |k: &str| e.translate(k).map(str::to_owned); // ItemContainerContents.addToTooltip. let hover_name = |s: &ItemStack| { s.custom_name() .map_or_else(|| self.pack.names.item(&s.item), str::to_owned) }; - for line in horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) { - lines.push((line, u32::MAX)); + if display.shows("minecraft:container") { + for line in + horizon_client::item_tooltip::container_lines(stack, &hover_name, &translate) + { + lines.push((line, u32::MAX)); + } } - if stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow" { + if display.shows("minecraft:potion_contents") + && (stack.item.ends_with("potion") || &*stack.item == "minecraft:tipped_arrow") + { let scale = match &*stack.item { "minecraft:lingering_potion" => 0.25, "minecraft:tipped_arrow" => 0.125, @@ -1912,7 +1922,9 @@ impl Game<'_> { lines.push((line, c)); } } - if let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) { + if display.shows("minecraft:trim") + && let Some((material, pattern)) = stack.data().and_then(|d| d.trim.clone()) + { lines.push(( e.translate("item.minecraft.smithing_template.upgrade") .unwrap_or("Upgrade:") @@ -1929,30 +1941,44 @@ impl Game<'_> { lines.push((format!(" {p}"), rgba(170, 170, 170, 255))); lines.push((format!(" {m}"), rgba(170, 170, 170, 255))); } - for (text, curse) in e - .tooltip(stack.stored_enchantments()) - .into_iter() - .chain(e.tooltip(stack.enchantments())) - { - lines.push(( - text, - if curse { - rgba(255, 85, 85, 255) - } else { - rgba(170, 170, 170, 255) - }, - )); + if display.shows("minecraft:stored_enchantments") { + for (text, curse) in e.tooltip(stack.stored_enchantments()) { + lines.push(( + text, + if curse { + rgba(255, 85, 85, 255) + } else { + rgba(170, 170, 170, 255) + }, + )); + } + } + if display.shows("minecraft:enchantments") { + for (text, curse) in e.tooltip(stack.enchantments()) { + lines.push(( + text, + if curse { + rgba(255, 85, 85, 255) + } else { + rgba(170, 170, 170, 255) + }, + )); + } } // BannerPatternLayers.addToTooltip: up to six layer names. - for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { - let key = self.res.stations.banners.layer_key(layer); - lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + if display.shows("minecraft:banner_patterns") { + for layer in horizon_client::banner::tooltip_layers(stack).iter().take(6) { + let key = self.res.stations.banners.layer_key(layer); + lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); + } } // Spawner.appendHoverText: what a spawner or trial spawner item spawns. - if matches!( - &*stack.item, - "minecraft:spawner" | "minecraft:trial_spawner" - ) { + if display.shows("minecraft:block_entity_data") + && matches!( + &*stack.item, + "minecraft:spawner" | "minecraft:trial_spawner" + ) + { let gray = rgba(170, 170, 170, 255); match block_entity_item::spawner_entity(stack) { Some(id) => { @@ -1969,7 +1995,9 @@ impl Game<'_> { } } } - if let Some(info) = self.res.items.get(&stack.item) { + if display.shows("minecraft:attribute_modifiers") + && let Some(info) = self.res.items.get(&stack.item) + { let base = |name: &str, default| { self.player .as_ref() @@ -1997,7 +2025,8 @@ impl Game<'_> { &translate, )); } - if let Some(info) = self.res.items.get(&stack.item) + if display.shows("minecraft:damage") + && let Some(info) = self.res.items.get(&stack.item) && info.max_damage > 0 && stack.damage > 0 && self.options_advanced_tooltips() diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index 4606f6859..c4cee6319 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -5,11 +5,77 @@ use super::Game; use horizon_client::{ items::ItemStack, + mesher::Vertex, mobs::{Mob, Species, sulfur_cube}, }; use horizon_core::random::RandomSource; +fn block_transform(base: glam::Mat4, baby: bool) -> glam::Mat4 { + base * glam::Mat4::from_scale(glam::Vec3::new(1.0, -1.0, -1.0)) + * glam::Mat4::from_scale(glam::Vec3::splat(if baby { 0.5 } else { 1.0 })) + * glam::Mat4::from_translation(glam::Vec3::new(-0.5, -0.518, -0.5)) +} + +fn block_overlay(fuse_ticks: i32, alpha: f32, hurt: bool) -> u32 { + let fuse = if fuse_ticks >= 0 { + fuse_ticks as f32 - alpha + 1.0 + } else { + 0.0 + }; + if fuse > 0.0 && (fuse / 5.0) as i32 % 2 == 0 { + horizon_client::overlay::living(1.0, false) + } else { + horizon_client::overlay::living(0.0, hurt) + } +} + +fn block_light(light: u32, emission: u8) -> u32 { + let block = (light >> 8 & 0xFF).max(u32::from(emission) * 16); + (light & 0xFF) | block << 8 +} + impl Game<'_> { + /// The swallowed block replaces the opaque core and precedes the shell. + pub(super) fn sulfur_cube_body_geometry( + &self, + mob: &Mob, + alpha: f32, + base: glam::Mat4, + light: u32, + out: &mut Vec, + ) { + let Some(item) = mob.extra.head.as_deref() else { + return; + }; + if super::armor_stands::skull_kind(item).is_some() { + return; + } + // shortcut: the body slot retains only an item id; preserve the stack + // before supporting its block-state components here. + let Some(state) = self.res.items.get(item).and_then(|item| item.block) else { + return; + }; + let start = out.len(); + self.block_model_vertices( + state, + 42, + block_transform(base, mob.is_baby()), + block_light(light, self.res.facts.get(state).emission), + true, + out, + ); + let overlay = block_overlay( + sulfur_cube::fuse(mob), + alpha, + mob.hurt_time > 0 || mob.death_time > 0, + ); + if overlay != 0 { + for vertex in &mut out[start..] { + vertex.layer = overlay; + } + } + } + fn sulfur_sound(&mut self, index: usize, sound: &str) { let at = self.mobs[index].center(); self.audio @@ -126,6 +192,11 @@ impl Game<'_> { continue; } let item = e.stack.item.clone(); + let thrown_by_player = e + .thrower + .is_some_and(|uuid| Some(uuid) == self.level.player_uuid); + let mut swallowed = e.stack.clone(); + swallowed.count = 1; let (taken_item, id) = (e.clone(), self.mobs[i].id); self.add_pickup( super::pickups::Taken::Item(Box::new(taken_item)), @@ -140,6 +211,14 @@ impl Game<'_> { m.extra.head = Some(item); m.extra.point = None; self.sulfur_sound(i, "entity.sulfur_cube.absorb"); + if thrown_by_player { + let target = self.mob_entity(&self.mobs[i]); + self.trigger_item_entity( + "minecraft:thrown_item_picked_up_by_entity", + &swallowed, + &target, + ); + } } } /// `AbstractCubeMob.remove`: a dead adult splits into two babies (none @@ -167,3 +246,46 @@ impl Game<'_> { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn swallowed_block_uses_vanilla_lift_and_baby_scale() { + let base = glam::Mat4::from_translation(glam::Vec3::new(3.0, 4.0, -2.0)) + * glam::Mat4::from_rotation_y(0.7) + * glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); + for baby in [false, true] { + let size = if baby { 0.5 } else { 1.0 }; + let block = block_transform(base, baby); + for (point, expected) in [ + (glam::Vec3::ZERO, glam::Vec3::new(-0.5, 0.518, 0.5)), + (glam::Vec3::ONE, glam::Vec3::new(0.5, -0.482, -0.5)), + ] { + let actual = block.transform_point3(point); + let expected = base.transform_point3(expected * size); + assert!(actual.abs_diff_eq(expected, 1e-5), "baby={baby}"); + } + assert!(block.transform_vector3(glam::Vec3::Y).y > 0.0); + } + } + + #[test] + fn swallowed_tnt_flashes_white_over_hurt_using_the_interpolated_fuse() { + let white = horizon_client::overlay::WHITE + 15; + assert_eq!(block_overlay(-1, 0.0, false), 0); + assert_eq!(block_overlay(-1, 0.0, true), 1); + assert_eq!(block_overlay(9, 0.0, true), white); + assert_eq!(block_overlay(9, 0.5, false), 0); + assert_eq!(block_overlay(9, 0.5, true), 1); + assert_eq!(block_overlay(0, 0.5, false), white); + } + + #[test] + fn contained_block_emission_preserves_brighter_light_and_the_sky_channel() { + assert_eq!(block_light(0x2050, 1), 0x2050); + assert_eq!(block_light(0x2050, 7), 0x7050); + assert_eq!(block_light(0x0070, 0), 0x0070); + } +} diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index 78f107599..c47c17de9 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -12,6 +12,8 @@ use horizon_world::level::flags as level_flags; #[derive(Clone, Debug)] pub(super) struct PrimedTnt { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub position: Vec3, pub previous: Vec3, pub velocity: Vec3, @@ -140,6 +142,7 @@ impl Game<'_> { f64::from(pos.z) + 0.5, ); self.tnts.push(PrimedTnt { + id: 0, position, previous: position, velocity: Vec3::new(-rot.sin() * 0.02, f64::from(0.2f32), -rot.cos() * 0.02), @@ -241,7 +244,24 @@ impl Game<'_> { .and_then(|name| self.atlas.sprites.get(name).copied()); } } + let range = super::entity_culling::default_range( + glam::DVec3::splat(PrimedTnt::SIZE), + self.settings.entity_distance, + ); for t in &self.tnts { + // EntityRenderer.shouldRender. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + PrimedTnt::SIZE, + PrimedTnt::SIZE, + range, + 0.0, + ) { + continue; + } let fuse = t.fuse as f32 - alpha as f32 + 1.0; let scale = if fuse < 10.0 { let g = (1.0 - fuse / 10.0).clamp(0.0, 1.0); @@ -484,6 +504,7 @@ mod tests { world.set(21, 4, 20, flowing).unwrap(); let at = Vec3::new(20.5, 4.0, 20.5); let mut tnt = PrimedTnt { + id: 0, position: at, previous: at, velocity: Vec3::ZERO, diff --git a/crates/horizon-client/src/game/totem.rs b/crates/horizon-client/src/game/totem.rs index 805360c8d..47b67d9f8 100644 --- a/crates/horizon-client/src/game/totem.rs +++ b/crates/horizon-client/src/game/totem.rs @@ -53,9 +53,7 @@ impl Game<'_> { ("fire_resistance", 800, 0), ] { if let Some(e) = horizon_client::brewing::effect(id) { - self.potions - .effects - .add(EffectInstance::new(e.id, ticks, amp)); + self.add_player_effect(EffectInstance::new(e.id, ticks, amp)); } } self.audio diff --git a/crates/horizon-client/src/game/trial_spawner.rs b/crates/horizon-client/src/game/trial_spawner.rs index 4107e0859..42a26c6e4 100644 --- a/crates/horizon-client/src/game/trial_spawner.rs +++ b/crates/horizon-client/src/game/trial_spawner.rs @@ -106,34 +106,21 @@ impl TrialSpawnerLevel for GameLevel<'_, '_> { } impl Game<'_> { - /// Every trial spawner's server tick. - pub(super) fn tick_trial_spawners(&mut self) -> Result<()> { - let keys: Vec = self - .world + /// The server tick of the trial spawner at `key`. Its client tick comes + /// after every block entity's. + pub(super) fn tick_trial_spawner(&mut self, key: Pos) -> Result<()> { + let Some((current, ominous)) = self.trial_spawner_block(key) else { + return Ok(()); + }; + let Some(BlockEntity::TrialSpawner(mut spawner)) = self.world.block_entities.take(&key) + else { + return Ok(()); + }; + let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); + self.world .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::TrialSpawner(_))) - .map(|(k, _)| *k) - .collect(); - for &key in &keys { - let Some((current, ominous)) = self.trial_spawner_block(key) else { - continue; - }; - let Some(BlockEntity::TrialSpawner(mut spawner)) = - self.world.block_entities.remove(&key) - else { - continue; - }; - let result = self.server_tick_trial_spawner(key, &mut spawner, current, ominous); - self.world - .block_entities - .insert(key, BlockEntity::TrialSpawner(spawner)); - result?; - } - for key in keys { - self.client_tick_trial_spawner(key); - } - Ok(()) + .put(key, BlockEntity::TrialSpawner(spawner)); + result } /// The trial spawner block at `key`: its state and ominous flag. pub(super) fn trial_spawner_block(&self, key: Pos) -> Option<(TrialState, bool)> { diff --git a/crates/horizon-client/src/game/trial_visuals.rs b/crates/horizon-client/src/game/trial_visuals.rs index d32957fe1..cac28b5cc 100644 --- a/crates/horizon-client/src/game/trial_visuals.rs +++ b/crates/horizon-client/src/game/trial_visuals.rs @@ -237,7 +237,7 @@ impl Game<'_> { let shows = vault.display_item.is_some(); self.world .block_entities - .insert(key, BlockEntity::Vault(vault)); + .put(key, BlockEntity::Vault(vault)); let pos = [key.0, key.1, key.2]; if self.world.game_time % 20 == 0 { self.vault_connection_particles(pos); diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 8c372fa46..0dee8d22a 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -15,20 +15,48 @@ use horizon_core::{ }; pub(super) struct ThrownTrident { - stack: ItemStack, - position: Vec3, + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, + pub(super) stack: ItemStack, + pub(super) position: Vec3, previous: Vec3, - velocity: Vec3, - yaw: f32, - pitch: f32, - in_ground: bool, + pub(super) velocity: Vec3, + pub(super) yaw: f32, + pub(super) pitch: f32, + pub(super) in_ground: bool, in_ground_time: u32, dealt_damage: bool, - loyalty: u32, - no_physics: bool, + pub(super) loyalty: u32, + pub(super) no_physics: bool, returning: u32, creative_only: bool, } +impl ThrownTrident { + /// A trident a server sent (`handleAddEntity`): placed and moved by it. + pub(super) fn remote(id: u32, position: Vec3, yaw: f32, pitch: f32) -> Self { + Self { + id, + stack: ItemStack::new("minecraft:trident", 1), + position, + previous: position, + velocity: Vec3::ZERO, + yaw, + pitch, + in_ground: false, + in_ground_time: 0, + dealt_damage: false, + loyalty: 0, + no_physics: false, + returning: 0, + creative_only: false, + } + } + /// One tick of a server's client: the previous position, then `step`. + pub(super) fn remote_step(&mut self, step: impl FnOnce(Vec3) -> Vec3) { + self.previous = self.position; + self.position = step(self.position); + } +} const HALF: f64 = 0.25; fn bounds(p: Vec3) -> Aabb { Aabb::new( @@ -163,6 +191,7 @@ impl Game<'_> { on_ground, ); self.tridents.push(ThrownTrident { + id: 0, loyalty: thrown.enchantment_level("minecraft:loyalty"), stack: thrown, position: start, @@ -350,7 +379,26 @@ impl Game<'_> { else { return; }; + // AbstractArrow.shouldRenderAtSqrDistance: ten times the default. + let range = 10.0 + * super::entity_culling::default_range( + glam::DVec3::splat(2.0 * HALF), + self.settings.entity_distance, + ); for t in &self.tridents { + // EntityRenderer.shouldRender; ThrownTridentRenderer grows the box by 1.5. + if !self.standing_entity_in_view( + camera, + super::entity_culling::at(t.previous), + super::entity_culling::at(t.position), + alpha, + 2.0 * HALF, + 2.0 * HALF, + range, + 1.5, + ) { + continue; + } let p = glam::DVec3::new( t.previous.x + (t.position.x - t.previous.x) * alpha, t.previous.y + (t.position.y - t.previous.y) * alpha, diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index 018b6640b..f15aa9ea7 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -70,15 +70,7 @@ impl Game<'_> { /// One ordinary click on a game slot. False when nothing took it. pub(super) fn tweak_click(&mut self, slot: usize, button: i32, input: Input) -> bool { if self.remote.is_some() { - let ordinal = match input { - Input::Pickup => 0, - Input::QuickMove => 1, - Input::Swap => 2, - Input::Clone => 3, - Input::Throw => 4, - Input::QuickCraft => 5, - Input::PickupAll => 6, - }; + let ordinal = super::remote::input_ordinal(input); return self.remote_slot_click(slot, button as i8, ordinal); } if !self.menu_click(Some(slot), button, input) { diff --git a/crates/horizon-client/src/game/vault.rs b/crates/horizon-client/src/game/vault.rs index 31d7d3ea3..f3edfddb3 100644 --- a/crates/horizon-client/src/game/vault.rs +++ b/crates/horizon-client/src/game/vault.rs @@ -61,7 +61,7 @@ impl Game<'_> { .and_then(|s| VaultState::from_name(s)) .unwrap_or_default(); let ominous = block.properties.get("ominous").is_some_and(|v| v == "true"); - let Some(BlockEntity::Vault(vault)) = self.world.block_entities.remove(&key) else { + let Some(BlockEntity::Vault(vault)) = self.world.block_entities.take(&key) else { return None; }; Some((vault, current, ominous)) @@ -118,26 +118,20 @@ impl Game<'_> { self.rand_sequences = sequences; self.world .block_entities - .insert(key, BlockEntity::Vault(vault)); + .put(key, BlockEntity::Vault(vault)); Some(self.vault_events(key, events).map(|()| out)) } - /// Every vault's server tick, then its client tick. - pub(super) fn tick_vaults(&mut self) -> Result<()> { - let keys: Vec = self - .world - .block_entities - .iter() - .filter(|(_, e)| matches!(e, BlockEntity::Vault(_))) - .map(|(k, _)| *k) - .collect(); - for key in keys { - let pos = [key.0, key.1, key.2]; - let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| { - v.server_tick(l, random, pos, state, ominous, roll, events); - }); - if let Some(result) = ticked { - result?; - } + /// The server tick of the vault at `key`, then its client tick when there + /// is a window. + pub(super) fn tick_vault(&mut self, key: Pos) -> Result<()> { + let pos = [key.0, key.1, key.2]; + let ticked = self.with_vault(key, |v, l, random, state, ominous, roll, events| { + v.server_tick(l, random, pos, state, ominous, roll, events); + }); + if let Some(result) = ticked { + result?; + } + if self.options.dedicated.is_none() { self.client_tick_vault(key); } Ok(()) diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 7391ad8b9..be842c3c6 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] } mod arena; +mod flat; mod java_stages; mod occlusion; mod pack_stages; @@ -101,6 +102,8 @@ struct SectionGpu { faces: crate::mesher::FaceGroups, sort: translucency::SortState, sorted_indices: Option<(u32, u64)>, + /// Its id for flat draws (`flat::Flat::add`), when they are on. + flat_id: Option, } /// Line segments the hit outline can hold. const MAX_OUTLINE_EDGES: u64 = 256; @@ -251,6 +254,10 @@ pub struct Renderer { pub config: wgpu::SurfaceConfiguration, solid: wgpu::RenderPipeline, translucent: wgpu::RenderPipeline, + /// Flat section draws (`flat`), where multi-draw is emulated. + flat: Option, + /// `flat` draws this frame's sections (off: the per-section draws). + flat_on: bool, sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, @@ -355,6 +362,10 @@ pub struct Renderer { pub info: wgpu::AdapterInfo, pub suspended: bool, pub drawn_sections: usize, + /// Last frame's section draws (face ranges and translucent sections), + /// and the draw calls the backend issued for them. + pub section_draws: usize, + pub section_draw_calls: usize, pub uploaded_bytes: u64, started: Instant, /// Write the next presented frame to this PNG path (control socket). @@ -385,7 +396,7 @@ fn sprite_split() -> u32 { .unwrap_or(SPRITE_SPLIT) } /// Sprite arrays terrain.wgsl binds (`sprites`, `sprites_1`...). -const SPRITE_ARRAYS: u32 = 4; +const SPRITE_ARRAYS: u32 = 8; /// The views of terrain.wgsl's sprite arrays, the unused ones a 1-layer /// stand-in. fn sprite_views( @@ -441,6 +452,10 @@ fn terrain_group( view(5, &sprites[1]), view(6, &sprites[2]), view(7, &sprites[3]), + view(8, &sprites[4]), + view(9, &sprites[5]), + view(10, &sprites[6]), + view(11, &sprites[7]), ], }) } @@ -615,8 +630,12 @@ impl Renderer { adapter .request_device(&wgpu::DeviceDescriptor { label: Some("Horizon device"), + // Mappable primary buffers: section pages that no + // longer fit in video memory go to system memory. required_features: timing::GpuTimer::features(&adapter) - | (adapter.features() & wgpu::Features::INDIRECT_FIRST_INSTANCE), + | (adapter.features() + & (wgpu::Features::INDIRECT_FIRST_INSTANCE + | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)), required_limits: limits.clone(), ..Default::default() }) @@ -739,6 +758,10 @@ impl Renderer { entry(5, vf, sprite_array), entry(6, vf, sprite_array), entry(7, vf, sprite_array), + entry(8, vf, sprite_array), + entry(9, vf, sprite_array), + entry(10, vf, sprite_array), + entry(11, vf, sprite_array), ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { @@ -773,18 +796,19 @@ impl Renderer { step_mode: wgpu::VertexStepMode::Instance, attributes: &debug_line_attributes, })]; - let pipeline = |label: &str, - vertex: &str, - fragment: &str, - buffers: &[Option>], - topology: wgpu::PrimitiveTopology, - cull: Option, - depth_write: bool, - depth_test: bool, - blend: Option| { + let pipeline_in = |layout: &wgpu::PipelineLayout, + label: &str, + vertex: &str, + fragment: &str, + buffers: &[Option>], + topology: wgpu::PrimitiveTopology, + cull: Option, + depth_write: bool, + depth_test: bool, + blend: Option| { device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { label: Some(label), - layout: Some(&layout), + layout: Some(layout), vertex: wgpu::VertexState { module: &shader, entry_point: Some(vertex), @@ -825,6 +849,28 @@ impl Renderer { cache: None, }) }; + let pipeline = |label: &str, + vertex: &str, + fragment: &str, + buffers: &[Option>], + topology: wgpu::PrimitiveTopology, + cull: Option, + depth_write: bool, + depth_test: bool, + blend: Option| { + pipeline_in( + &layout, + label, + vertex, + fragment, + buffers, + topology, + cull, + depth_write, + depth_test, + blend, + ) + }; let tri = wgpu::PrimitiveTopology::TriangleList; let solid = pipeline( "Terrain solid", @@ -1641,7 +1687,34 @@ impl Renderer { std::mem::size_of::() as u64, 1 << 20, ); - let sorted_indices = arena::Arena::indices(&device, 1 << 16); + // Sections as one index list per frame where multi-draw is emulated. + let flat = flat::wanted(&adapter, &device).then(|| { + let buffers = [Some(wgpu::VertexBufferLayout { + array_stride: std::mem::size_of::() as u64, + step_mode: wgpu::VertexStepMode::Vertex, + attributes: &TERRAIN_ATTRIBUTES, + })]; + flat::Flat::new( + &device, + &bindings, + arena.page_vertices(), + |layout, label, fragment, blend| { + pipeline_in( + layout, + label, + "vs_terrain_flat", + fragment, + &buffers, + tri, + Some(wgpu::Face::Back), + true, + true, + blend, + ) + }, + ) + }); + let sorted_indices = arena::Arena::indices(&device, 1 << 16, flat.is_some()); let indirect = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section draws"), size: 1024 * 20, @@ -1676,6 +1749,8 @@ impl Renderer { config, solid, translucent, + flat_on: flat.is_some(), + flat, sky, dark_disc, lines, @@ -1755,6 +1830,8 @@ impl Renderer { info, suspended: size.width == 0 || size.height == 0, drawn_sections: 0, + section_draws: 0, + section_draw_calls: 0, uploaded_bytes: 0, started: Instant::now(), screenshot: None, @@ -1835,30 +1912,12 @@ impl Renderer { }) .create_view(&Default::default()) } - /// VSync on: tear-free presentation (Mailbox, else Fifo); off: Immediate when available. - /// VSync, unless Horizon's present-mode setting names a supported mode. + /// VSync on presents with Fifo, capped to the display's refresh rate in a + /// window and in fullscreen alike; Horizon's present-mode setting applies + /// only with VSync off (`window::chosen_present_mode`). pub fn set_present_mode(&mut self, vsync: bool, mode: crate::graphics::PresentMode) { use crate::graphics::PresentMode as P; - let wanted = match mode { - P::Auto => None, - P::Fifo => Some(wgpu::PresentMode::Fifo), - P::Mailbox => Some(wgpu::PresentMode::Mailbox), - P::Immediate => Some(wgpu::PresentMode::Immediate), - }; - match wanted.filter(|m| self.present_modes.contains(m)) { - Some(m) => { - if self.config.present_mode != m - && let Some(surface) = &self.surface - { - self.config.present_mode = m; - surface.configure(&self.device, &self.config); - } - } - None => self.set_vsync(vsync), - } - } - pub fn set_vsync(&mut self, vsync: bool) { - use crate::window::{PresentMode, vsync_present_mode}; + use crate::window::{PresentMode, chosen_present_mode}; let supported: Vec = self .present_modes .iter() @@ -1869,8 +1928,13 @@ impl Renderer { _ => None, }) .collect(); - // GpuSurface.PresentMode.getSupportedVsyncMode. - let mode = match vsync_present_mode(&supported, vsync) { + let setting = match mode { + P::Auto => None, + P::Fifo => Some(PresentMode::Fifo), + P::Mailbox => Some(PresentMode::Mailbox), + P::Immediate => Some(PresentMode::Immediate), + }; + let mode = match chosen_present_mode(&supported, vsync, setting) { Some(PresentMode::Mailbox) => wgpu::PresentMode::Mailbox, Some(PresentMode::Immediate) => wgpu::PresentMode::Immediate, _ => wgpu::PresentMode::Fifo, @@ -1896,12 +1960,31 @@ impl Renderer { } self.depth = Self::depth(&self.device, &self.config); } + /// Whether sections are drawn as one index list per frame (`flat`). + pub fn flat_draws(&self) -> bool { + self.flat_on + } + /// Switches between flat and per-section draws, for A/B checks. + pub fn set_flat_draws(&mut self, on: bool) -> Result<()> { + if on && self.flat.is_none() { + return Err("flat section draws are off on this device".into()); + } + self.flat_on = on; + Ok(()) + } pub fn section_count(&self) -> usize { self.sections.len() } pub fn has_section(&self, key: SectionKey) -> bool { self.sections.contains(key) } + /// Bring the cave culling graph up to date for `camera` without waiting: + /// a search this starts runs on its worker while the frame is prepared, + /// and `render` takes it if it has finished. + pub fn start_occlusion(&mut self, camera: DVec3, distance: f32) { + self.occlusion + .update(camera_section(camera), (distance / 16.0) as i32 + 2); + } pub fn upload(&mut self, key: SectionKey, mesh: &SectionMesh) { self.occlusion.set(key, mesh.visibility); if mesh.block_entities.is_empty() { @@ -1921,11 +2004,26 @@ impl Renderer { self.indices = Self::quad_indices(&self.device, self.index_quads); } let vertices = (mesh.solid.len() + mesh.translucent.len()) as u64; - let (page, start) = self.arena.alloc(&self.device, &self.queue, vertices); - let sorted_indices = (translucent > 0).then(|| { - self.sorted_indices - .alloc(&self.device, &self.queue, u64::from(translucent) * 6) - }); + // With video and system memory both full, the section is not drawn. + let Some((page, start)) = self.arena.alloc(&self.device, &self.queue, vertices) else { + return; + }; + let sorted_indices = if translucent > 0 { + let indices = + self.sorted_indices + .alloc(&self.device, &self.queue, u64::from(translucent) * 6); + if indices.is_none() { + self.arena.release(page, start, vertices); + return; + } + indices + } else { + None + }; + let flat_id = self + .flat + .as_mut() + .map(|f| f.add(&self.device, &self.queue, page, start, vertices)); let stride = std::mem::size_of::() as u64; for (offset, part) in [(0, &mesh.solid), (mesh.solid.len(), &mesh.translucent)] { if !part.is_empty() { @@ -1955,6 +2053,7 @@ impl Renderer { .collect(), ), sorted_indices, + flat_id, }, ); } @@ -1985,6 +2084,9 @@ impl Renderer { } fn release_section(&mut self, key: SectionKey) { if let Some(s) = self.sections.remove(key) { + if let (Some(flat), Some(id)) = (&mut self.flat, s.flat_id) { + flat.remove(id); + } if let Some((page, start)) = s.sorted_indices { self.sorted_indices .release(page, start, u64::from(s.translucent) * 6); @@ -2001,6 +2103,9 @@ impl Renderer { self.block_entities.clear(); self.sections.clear(); self.arena.clear(); + if let Some(flat) = &mut self.flat { + flat.clear(); + } self.sorted_indices.clear(); self.translucency_cursor = 0; self.occlusion.clear(); @@ -2181,6 +2286,11 @@ impl Renderer { ); } pub fn render(&mut self, frame: &Frame) -> Result { + self.arena.trim(); + self.sorted_indices.trim(); + if let Some(flat) = &mut self.flat { + flat.trim(|page| self.arena.has_page(page)); + } if self.suspended { return Ok(false); } @@ -2363,26 +2473,23 @@ impl Renderer { planes: frustum(view_proj), }; let camera = frame.camera; - let camera_section = ( - (camera.x.floor() as i32) >> 4, - (camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4, - (camera.z.floor() as i32) >> 4, - ); + let camera_section = camera_section(camera); let culling = !frame.title && frame.cave_culling; if culling { - let radius = (frame.distance / 16.0) as i32 + 2; - self.occlusion.update(camera_section, radius); + crate::spans::time("occlusion", || self.start_occlusion(camera, frame.distance)); } let reachable = &self.occlusion; let mut visible = std::mem::take(&mut self.visible); visible.clear(); - self.sections.visible( - camera, - (frame.distance / 16.0) as i32, - &view, - |k| !culling || reachable.contains(k), - &mut visible, - ); + crate::spans::time("visibility", || { + self.sections.visible( + camera, + (frame.distance / 16.0) as i32, + &view, + |k| !culling || reachable.contains(k), + &mut visible, + ) + }); self.drawn_sections = visible.len(); if visible.len() as u64 > self.instance_capacity { self.instance_capacity = (visible.len() as u64).next_power_of_two(); @@ -2470,7 +2577,45 @@ impl Renderer { } self.translucency_cursor += budget; let translucent_draws = self.draws.len() as u32 - solid_draws; - if self.multi_draw && !self.draws.is_empty() { + self.section_draws = self.draws.len(); + // Metal replays a multi-draw as one draw call per entry. + self.section_draw_calls = if self.multi_draw && self.info.backend != wgpu::Backend::Metal { + (0..self.draws.len()) + .filter(|&i| { + i == 0 + || i == solid_draws as usize + || self.draw_pages[i] != self.draw_pages[i - 1] + }) + .count() + } else { + self.draws.len() + }; + let flat_frame = match &mut self.flat { + Some(flat) + if self.flat_on && !self.draws.is_empty() && self.draws.len() >= flat.min_draws => + { + let sections = &self.sections; + let sorted = &self.sorted_indices; + crate::spans::time("flatten", || { + flat.prepare( + &self.device, + &mut encoder, + &mut self.uploads, + &self.draws, + &self.draw_pages, + solid_draws as usize, + visible + .iter() + .filter_map(|v| sections.get(v.slot).flat_id.map(|id| (id, v.origin))), + |page| sorted.buffer(page).clone(), + ) + }) + } + _ => false, + }; + if flat_frame { + self.section_draw_calls = self.flat.as_ref().map_or(0, |f| f.calls.len()); + } else if self.multi_draw && !self.draws.is_empty() { if self.draws.len() as u64 > self.indirect_capacity { self.indirect_capacity = (self.draws.len() as u64).next_power_of_two(); self.indirect = self.device.create_buffer(&wgpu::BufferDescriptor { @@ -2705,10 +2850,22 @@ impl Renderer { pass.draw(0..3, 0..1); } } - pass.set_pipeline(&self.solid); - pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, 0, solid_draws); + match self.flat.as_ref().filter(|_| flat_frame) { + Some(flat) => { + pass.set_pipeline(&flat.solid); + flat.draw(&mut pass, &flat.calls[..flat.solid_calls], |p| { + self.arena.buffer(p) + }); + pass.set_bind_group(0, &self.group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + } + None => { + pass.set_pipeline(&self.solid); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections(&mut pass, 0, solid_draws); + } + } if entity_quads > 0 { pass.set_pipeline(&self.entity_pipeline); pass.set_bind_group(0, &self.entity_group, &[]); @@ -2745,10 +2902,22 @@ impl Renderer { pass.set_vertex_buffer(0, self.debug_line_buffer.slice(..)); pass.draw(0..4, debug_depth..debug_depth + debug_top); } - pass.set_pipeline(&self.translucent); - pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); - pass.set_vertex_buffer(1, self.instances.slice(..)); - self.draw_sections(&mut pass, solid_draws, translucent_draws); + match self.flat.as_ref().filter(|_| flat_frame) { + Some(flat) => { + pass.set_pipeline(&flat.translucent); + flat.draw(&mut pass, &flat.calls[flat.solid_calls..], |p| { + self.arena.buffer(p) + }); + pass.set_bind_group(0, &self.group, &[]); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + } + None => { + pass.set_pipeline(&self.translucent); + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + pass.set_vertex_buffer(1, self.instances.slice(..)); + self.draw_sections(&mut pass, solid_draws, translucent_draws); + } + } // LevelRenderer.executeClassicTransparency: translucent targets' // outlines follow terrain, so its blending cannot wash them out. if outline_edges > 0 && frame.outline_after_terrain { @@ -2989,7 +3158,8 @@ impl Renderer { .take() .map(|path| (path, self.copy_frame(&mut encoder, &target_texture))); self.uploads.finish(&encoder); - let submission = self.queue.submit([encoder.finish()]); + let commands = crate::spans::time("encode", || encoder.finish()); + let submission = crate::spans::time("submit", || self.queue.submit([commands])); if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); @@ -3193,6 +3363,15 @@ enum Pack { Java(java_stages::JavaStages), } +/// The section the camera is in. +fn camera_section(camera: DVec3) -> SectionKey { + ( + (camera.x.floor() as i32) >> 4, + (camera.y.floor() as i32 - crate::chunk::MIN_Y) >> 4, + (camera.z.floor() as i32) >> 4, + ) +} + fn world_projection(fov_degrees: f32, aspect: f32, far: f32) -> Mat4 { Mat4::perspective_rh(fov_degrees.to_radians(), aspect, far, 0.05) } @@ -3490,13 +3669,39 @@ fn mix_frames(current: &mut [u8], next: &[u8], millis: u32) { let t = millis as f32 / 1000.0; for (c, n) in current.iter_mut().zip(next) { let (a, b) = (f32::from(*c) / 255.0, f32::from(*n) / 255.0); - *c = ((a * (1.0 - t) + b * t) * 255.0).round() as u8; + *c = round_unorm8((a * (1.0 - t) + b * t) * 255.0); } } +/// `x.round() as u8` for `x >= 0`, without the `roundf` library call that +/// x86-64 makes for every `f32::round` (it has no rounding instruction before +/// SSE4.1): the fraction `x - trunc(x)` is exact below 2^23, so rounding half +/// away from zero is adding one when it is at least a half. +#[inline] +fn round_unorm8(x: f32) -> u8 { + let whole = x as u8; + whole.saturating_add(u8::from(x - f32::from(whole) >= 0.5)) +} #[cfg(test)] mod sprite_upload_tests { use super::*; #[test] + fn blended_frames_round_like_f32_round() { + for millis in (0..1000).step_by(7).chain([999]) { + let t = millis as f32 / 1000.0; + for a in 0..=255u8 { + for b in 0..=255u8 { + let x = (f32::from(a) / 255.0 * (1.0 - t) + f32::from(b) / 255.0 * t) * 255.0; + assert_eq!(round_unorm8(x), x.round() as u8, "{a} {b} {millis}"); + } + } + } + for x in [ + 0.0, 0.49999997, 0.5, 1.5, 2.5, 254.49998, 254.5, 255.0, 255.00002, 300.0, + ] { + assert_eq!(round_unorm8(x), x.round() as u8, "{x}"); + } + } + #[test] fn real_rail_mips_do_not_change_with_larger_array_layers() { let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../.local/horizon-client/26.3"); diff --git a/crates/horizon-client/src/gfx/arena.rs b/crates/horizon-client/src/gfx/arena.rs index 233333e04..74d3b98e9 100644 --- a/crates/horizon-client/src/gfx/arena.rs +++ b/crates/horizon-client/src/gfx/arena.rs @@ -2,8 +2,11 @@ //! a frame binds it once and draws every section with indirect multi-draw. use std::collections::BTreeMap; -/// Ranges are rounded up to this many vertices to limit fragmentation. -const GRAIN: u64 = 256; +/// Ranges are rounded up to this many vertices to limit fragmentation, and +/// start at multiples of it (`flat` names sections by these blocks). +pub const GRAIN: u64 = 256; +/// The largest page, in bytes. +pub const PAGE_BYTES: u64 = 256 << 20; /// Free vertex ranges: start -> length, never adjacent. #[derive(Debug, PartialEq)] @@ -49,18 +52,30 @@ struct Page { /// Terrain vertices in pages of at most `page_limit` vertices (devices cap /// buffer sizes): a section's vertices sit in one page. pub struct Arena { - pages: Vec, + pages: Vec>, stride: u64, page_limit: u64, + initial_capacity: u64, usage: wgpu::BufferUsages, + /// A page had to go to system memory (logged once). + spilled: bool, + /// Tests: GPU-local pages fail as if video memory were full. + #[cfg(test)] + video_memory_full: bool, } impl Arena { pub fn new(device: &wgpu::Device, stride: u64, capacity: u64) -> Self { Self::with_usage(device, stride, capacity, wgpu::BufferUsages::VERTEX) } - pub fn indices(device: &wgpu::Device, capacity: u64) -> Self { - Self::with_usage(device, 4, capacity, wgpu::BufferUsages::INDEX) + /// Sorted translucent indices; `storage` when compute passes read them. + pub fn indices(device: &wgpu::Device, capacity: u64, storage: bool) -> Self { + let usage = if storage { + wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE + } else { + wgpu::BufferUsages::INDEX + }; + Self::with_usage(device, 4, capacity, usage) } fn with_usage( device: &wgpu::Device, @@ -69,31 +84,53 @@ impl Arena { usage: wgpu::BufferUsages, ) -> Self { // 256 MiB pages, or less where the device's buffers are smaller. - let bytes = device.limits().max_buffer_size.min(256 << 20); + let bytes = device.limits().max_buffer_size.min(PAGE_BYTES); let page_limit = (bytes / stride) / GRAIN * GRAIN; let capacity = capacity.next_multiple_of(GRAIN).min(page_limit); Self { - pages: vec![Page { - buffer: Self::create(device, stride, capacity, usage), - capacity, - free: FreeList::new(capacity), - }], + pages: Vec::new(), stride, page_limit, + initial_capacity: capacity, usage, + spilled: false, + #[cfg(test)] + video_memory_full: false, } } - fn create( - device: &wgpu::Device, - stride: u64, - capacity: u64, - usage: wgpu::BufferUsages, - ) -> wgpu::Buffer { - device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Section buffer arena"), - size: capacity * stride, - usage: usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC, - mapped_at_creation: false, + /// A buffer of `capacity` vertices in video memory or, when that is full + /// and the device allows it, in system memory: Vulkan drivers fail an + /// allocation rather than page like OpenGL ones, and wgpu's default error + /// handler panics. `None` when neither has room. + fn create(&mut self, device: &wgpu::Device, capacity: u64) -> Option { + let usage = self.usage | wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::COPY_SRC; + #[cfg(test)] + let local = (!self.video_memory_full) + .then(|| try_create(device, capacity * self.stride, usage)) + .flatten(); + #[cfg(not(test))] + let local = try_create(device, capacity * self.stride, usage); + local.or_else(|| { + // Mappable buffers are placed in host-visible memory, which the + // allocator takes from system memory once video memory is full. + if !device + .features() + .contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS) + { + return None; + } + let buffer = try_create( + device, + capacity * self.stride, + usage | wgpu::BufferUsages::MAP_WRITE, + )?; + if !std::mem::replace(&mut self.spilled, true) { + log::warn!( + "Horizon: video memory is full; more terrain is kept in system memory \ + (lower the render distance if frames slow down)" + ); + } + Some(buffer) }) } /// The rounded length a request of `vertices` occupies. @@ -102,55 +139,104 @@ impl Arena { } /// Bytes of every page's buffer. pub fn bytes(&self) -> u64 { - self.pages.iter().map(|p| p.capacity).sum::() * self.stride + self.pages.iter().flatten().map(|p| p.capacity).sum::() * self.stride + } + /// The most vertices a page holds. + pub fn page_vertices(&self) -> u64 { + self.page_limit + } + pub fn has_page(&self, page: u32) -> bool { + self.pages.get(page as usize).is_some_and(Option::is_some) } pub fn buffer(&self, page: u32) -> &wgpu::Buffer { - &self.pages[page as usize].buffer + &self.pages[page as usize] + .as_ref() + .expect("live arena page") + .buffer } /// A range of `vertices`: (page, first vertex). Grows the newest page /// (copying its contents on the GPU) or starts a new one when nothing - /// free is large enough. + /// free is large enough; `None` when no memory is left for it. pub fn alloc( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, vertices: u64, - ) -> (u32, u64) { + ) -> Option<(u32, u64)> { let len = Self::span(vertices).min(self.page_limit); for (i, page) in self.pages.iter_mut().enumerate() { - if let Some(start) = page.free.take(len) { - return (i as u32, start); + if let Some(page) = page + && let Some(start) = page.free.take(len) + { + return Some((i as u32, start)); } } - let last = self.pages.len() - 1; - let current = self.pages[last].capacity; - if current < self.page_limit { + let last = self.pages.len().saturating_sub(1); + if let Some(page) = self.pages.last().and_then(Option::as_ref) + && page.capacity < self.page_limit + { + let current = page.capacity; let grown = (current * 2).max(current + len).min(self.page_limit); - if grown - current >= len || grown == self.page_limit { - self.grow(device, queue, last, grown); - if let Some(start) = self.pages[last].free.take(len) { - return (last as u32, start); - } + if (grown - current >= len || grown == self.page_limit) + && self.grow(device, queue, last, grown) + && let Some(start) = self.pages[last].as_mut().unwrap().free.take(len) + { + return Some((last as u32, start)); } } - let capacity = (1 << 20u64).max(len).min(self.page_limit); + let capacity = if self.pages.is_empty() { + self.initial_capacity + } else { + 1 << 20 + } + .max(len) + .min(self.page_limit); + // A page just large enough when memory is short. + let (buffer, capacity) = match self.create(device, capacity) { + Some(buffer) => (buffer, capacity), + None if capacity > len => (self.create(device, len)?, len), + None => return None, + }; let mut free = FreeList::new(capacity); let start = free.take(len).expect("a new page fits one section"); - self.pages.push(Page { - buffer: Self::create(device, self.stride, capacity, self.usage), + let page = Page { + buffer, capacity, free, - }); - ((self.pages.len() - 1) as u32, start) + }; + let index = self + .pages + .iter() + .position(Option::is_none) + .unwrap_or_else(|| { + self.pages.push(None); + self.pages.len() - 1 + }); + self.pages[index] = Some(page); + Some((index as u32, start)) } pub fn release(&mut self, page: u32, start: u64, vertices: u64) { let len = Self::span(vertices).min(self.page_limit); - self.pages[page as usize].free.give(start, len); + self.pages[page as usize] + .as_mut() + .expect("live arena page") + .free + .give(start, len); } - fn grow(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, page: usize, capacity: u64) { + /// Moves a page into a larger buffer; false (the page unchanged) when + /// there is no memory for it. + fn grow( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + page: usize, + capacity: u64, + ) -> bool { let capacity = capacity.next_multiple_of(GRAIN).min(self.page_limit); - let buffer = Self::create(device, self.stride, capacity, self.usage); - let old = &mut self.pages[page]; + let Some(buffer) = self.create(device, capacity) else { + return false; + }; + let old = self.pages[page].as_mut().expect("live arena page"); let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("Grow section arena"), }); @@ -161,18 +247,124 @@ impl Arena { old.buffer = buffer; old.capacity = capacity; old.free.give(previous, capacity - previous); + true } - pub fn clear(&mut self) { + /// Reclaim after an upload batch, so replacing a section can reuse its range. + pub fn trim(&mut self) { for page in &mut self.pages { - page.free = FreeList::new(page.capacity); + if let Some(p) = page + && p.free.0.len() == 1 + && p.free.0.get(&0) == Some(&p.capacity) + { + *page = None; + } + } + // Keep live page indices stable; later allocations reuse interior holes. + while self.pages.last().is_some_and(Option::is_none) { + self.pages.pop(); } } + pub fn clear(&mut self) { + self.pages.clear(); + } +} + +/// `create_buffer` with an out-of-memory failure returned instead of raised +/// (raised errors are fatal). +fn try_create(device: &wgpu::Device, size: u64, usage: wgpu::BufferUsages) -> Option { + let scope = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); + let buffer = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Section buffer arena"), + size, + usage, + mapped_at_creation: false, + }); + // Native error scopes resolve at once. + pollster::block_on(scope.pop()).is_none().then_some(buffer) } #[cfg(test)] mod tests { use super::*; + fn device() -> Option<(wgpu::Device, wgpu::Queue)> { + device_with(wgpu::Features::empty()) + } + + /// A device with those of `features` the adapter has. + fn device_with(features: wgpu::Features) -> Option<(wgpu::Device, wgpu::Queue)> { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?; + eprintln!("arena GPU regression: {}", adapter.get_info().name); + let required_features = adapter.features() & features; + pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_features, + ..Default::default() + })) + .ok() + } + + #[test] + fn empty_pages_are_reclaimed_without_moving_live_ranges() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let mut arena = Arena::new(&device, 4, GRAIN); + arena.page_limit = 2 * GRAIN; + assert_eq!(arena.bytes(), 0); + let (first, a) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (_, b) = arena.alloc(&device, &queue, GRAIN).unwrap(); + let (live, c) = arena.alloc(&device, &queue, 2 * GRAIN).unwrap(); + let buffer = arena.buffer(live).clone(); + let data = [1u8, 2, 3, 4]; + queue.write_buffer(&buffer, c * 4, &data); + assert_eq!(arena.bytes(), 4 * GRAIN * 4); + arena.release(first, a, GRAIN); + arena.trim(); + assert_eq!(arena.bytes(), 4 * GRAIN * 4); + arena.release(first, b, GRAIN); + arena.trim(); + assert_eq!(arena.bytes(), 2 * GRAIN * 4); + assert_eq!(arena.buffer(live), &buffer); + let (reused, d) = arena.alloc(&device, &queue, GRAIN).unwrap(); + assert_eq!(reused, first); + + let (tx, rx) = std::sync::mpsc::channel(); + wgpu::util::DownloadBuffer::read_buffer( + &device, + &queue, + &arena.buffer(live).slice(c * 4..c * 4 + 4), + move |result| tx.send(result.unwrap().to_vec()).unwrap(), + ); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + assert_eq!(rx.recv().unwrap(), data); + arena.release(reused, d, GRAIN); + arena.release(live, c, 2 * GRAIN); + arena.trim(); + assert_eq!(arena.bytes(), 0); + assert!(arena.pages.is_empty()); + } + + #[test] + fn clearing_an_arena_releases_buffers_and_can_allocate_again() { + let Some((device, queue)) = device() else { + eprintln!("no GPU adapter: skipped"); + return; + }; + for mut arena in [ + Arena::new(&device, 28, GRAIN), + Arena::indices(&device, GRAIN, false), + ] { + arena.alloc(&device, &queue, GRAIN).unwrap(); + assert_eq!(arena.bytes(), arena.stride * GRAIN); + arena.clear(); + assert_eq!(arena.bytes(), 0); + assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + assert_eq!(arena.bytes(), arena.stride * GRAIN); + } + } + #[test] fn free_ranges_coalesce() { let mut free = FreeList::new(4 * GRAIN); @@ -197,4 +389,63 @@ mod tests { free.give(a, GRAIN); assert_eq!(free.take(GRAIN), Some(a)); } + + fn read(device: &wgpu::Device, queue: &wgpu::Queue, buffer: &wgpu::Buffer, offset: u64) -> u32 { + let (tx, rx) = std::sync::mpsc::channel(); + wgpu::util::DownloadBuffer::read_buffer( + device, + queue, + &buffer.slice(offset..offset + 4), + move |result| tx.send(result.unwrap().to_vec()).unwrap(), + ); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + u32::from_le_bytes(rx.recv().unwrap()[..4].try_into().unwrap()) + } + + #[test] + fn full_video_memory_spills_to_system_memory() { + let Some((device, queue)) = device_with(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS) else { + return; + }; + if !device + .features() + .contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS) + { + return; + } + let mut arena = Arena::indices(&device, GRAIN, false); + let (page, start) = arena.alloc(&device, &queue, GRAIN).unwrap(); + queue.write_buffer(arena.buffer(page), start * 4, &7u32.to_le_bytes()); + arena.video_memory_full = true; + // The full page can't grow in video memory: it moves to system + // memory with its contents, and new ranges come from there. + let (grown, next) = arena.alloc(&device, &queue, GRAIN).unwrap(); + assert!(arena.spilled); + assert_eq!(grown, page); + assert!( + arena + .buffer(page) + .usage() + .contains(wgpu::BufferUsages::MAP_WRITE) + ); + queue.write_buffer(arena.buffer(grown), next * 4, &9u32.to_le_bytes()); + assert_eq!(read(&device, &queue, arena.buffer(page), start * 4), 7); + assert_eq!(read(&device, &queue, arena.buffer(grown), next * 4), 9); + } + + #[test] + fn no_memory_left_is_not_an_error() { + let Some((device, queue)) = device() else { + return; + }; + let mut arena = Arena::indices(&device, GRAIN, false); + arena.alloc(&device, &queue, GRAIN).unwrap(); + arena.video_memory_full = true; + // Without mappable primary buffers nothing can spill: the request + // fails, and the arena keeps what it has. + assert_eq!(arena.alloc(&device, &queue, GRAIN), None); + assert_eq!(arena.bytes(), GRAIN * 4); + arena.release(0, 0, GRAIN); + assert_eq!(arena.alloc(&device, &queue, GRAIN), Some((0, 0))); + } } diff --git a/crates/horizon-client/src/gfx/flat.rs b/crates/horizon-client/src/gfx/flat.rs new file mode 100644 index 000000000..b867a42c2 --- /dev/null +++ b/crates/horizon-client/src/gfx/flat.rs @@ -0,0 +1,658 @@ +//! Flat section draws: where indirect multi-draw is emulated, as on Metal +//! (wgpu replays it as one draw call per indirect entry), the frame's section +//! draws are copied by a compute pass into one index list, in draw order, and +//! drawn with one draw call per run of sections in the same arena page. +//! +//! The picture is the one the per-section draws give: the same triangles +//! from the same vertices in the same order, through the same vertex and +//! fragment code. Only where a vertex finds its section's origin changes: +//! from the instance attribute to a table. A section's vertices fill whole +//! blocks of `GRAIN` vertices of its page (the arena rounds every range up), +//! so each block names one section: its id here, which indexes the frame's +//! camera-relative origins (computed on the CPU exactly as for the instance +//! attribute). +use super::arena::GRAIN; + +/// One section draw for `flatten.wgsl`: index count, first sorted index (or +/// `QUADS` for a solid draw), base vertex, first index in the list. +type Range = [u32; 4]; +const QUADS: u32 = u32::MAX; +const GROUP_LIMIT: u32 = 65535; + +struct PageTable { + /// Section id of every block of the page. + blocks: wgpu::Buffer, + group: Option, +} + +/// A run of the frame's index list drawn from one arena page. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Call { + pub page: u32, + pub first: u32, + pub count: u32, +} + +pub struct Flat { + pub solid: wgpu::RenderPipeline, + pub translucent: wgpu::RenderPipeline, + flatten: wgpu::ComputePipeline, + compute_layout: wgpu::BindGroupLayout, + draw_layout: wgpu::BindGroupLayout, + blocks_per_page: u64, + pages: Vec>, + free_ids: Vec, + next_id: u32, + origins: wgpu::Buffer, + origin_capacity: u64, + origin_data: Vec<[f32; 4]>, + /// The frame's index list. + pub indices: wgpu::Buffer, + index_capacity: u64, + ranges: wgpu::Buffer, + range_capacity: u64, + range_data: Vec, + /// Segments of `range_data` by index source: (sorted index page or + /// `None` for solid draws, first range, ranges). + segments: Vec<(Option, u64, u64)>, + empty: wgpu::Buffer, + /// This frame's draw calls: solid ones, then translucent ones. + pub calls: Vec, + pub solid_calls: usize, + /// Frames with fewer section draws keep the per-section draws. + pub min_draws: usize, + range_align: u64, +} + +/// Section draws from which a frame is drawn flat. Below it the index list +/// costs the GPU more than the draw calls cost the CPU: on an M4 Pro at +/// render distance 16 (2,900 draws) the copy and the list add about 0.4 ms +/// of GPU time for 0.5–0.8 ms less CPU time; at 32 (9,300 draws) the CPU +/// saves 1.3 ms. +const MIN_DRAWS: usize = 4096; + +/// Whether flat draws apply: the backend emulates multi-draw, and vertex +/// shaders can read storage buffers large enough for an index page. +/// `HORIZON_FLAT_DRAWS=1` draws every frame flat, `0` none. +pub fn wanted(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + match std::env::var("HORIZON_FLAT_DRAWS").as_deref() { + Ok("0") => return false, + Ok("1") => return supported(adapter, device), + _ => {} + } + adapter.get_info().backend == wgpu::Backend::Metal && supported(adapter, device) +} + +fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + let flags = adapter.get_downlevel_capabilities().flags; + let limits = device.limits(); + flags.contains(wgpu::DownlevelFlags::VERTEX_STORAGE | wgpu::DownlevelFlags::COMPUTE_SHADERS) + && limits.max_storage_buffers_per_shader_stage >= 3 + && limits.max_storage_buffer_binding_size >= super::arena::PAGE_BYTES +} + +fn storage(binding: u32, stage: wgpu::ShaderStages, read_only: bool) -> wgpu::BindGroupLayoutEntry { + wgpu::BindGroupLayoutEntry { + binding, + visibility: stage, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + } +} + +fn buffer( + device: &wgpu::Device, + label: &str, + size: u64, + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: size.max(16), + usage: usage | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) +} + +/// Lays out the frame's index list: each draw's range (destinations in draw +/// order) grouped by index source into `ranges`, every group padded to +/// `align` entries for binding, with `segments` naming each group; and the +/// draw calls, one per run of draws in the same vertex page, solid and +/// translucent apart. Returns the first translucent call and the list's +/// length. +fn plan( + draws: &[[u32; 5]], + pages: &[(u32, Option)], + solid_draws: usize, + align: u64, + calls: &mut Vec, + ranges: &mut Vec, + segments: &mut Vec<(Option, u64, u64)>, +) -> (usize, u64) { + calls.clear(); + ranges.clear(); + segments.clear(); + let mut solid_calls = None; + let mut total = 0u64; + let mut by_source: Vec<(Option, Vec)> = Vec::new(); + for (i, (d, &(page, sorted))) in draws.iter().zip(pages).enumerate() { + let first = if sorted.is_some() { d[2] } else { QUADS }; + let range = [d[0], first, d[3], total as u32]; + match by_source.iter_mut().find(|(s, _)| *s == sorted) { + Some((_, list)) => list.push(range), + None => by_source.push((sorted, vec![range])), + } + if i == solid_draws { + solid_calls = Some(calls.len()); + } + match calls.last_mut() { + Some(last) if last.page == page && i != solid_draws => last.count += d[0], + _ => calls.push(Call { + page, + first: total as u32, + count: d[0], + }), + } + total += u64::from(d[0]); + } + for (source, list) in by_source { + segments.push((source, ranges.len() as u64, list.len() as u64)); + ranges.extend(list); + let padded = (ranges.len() as u64).next_multiple_of(align); + ranges.resize(padded as usize, [0; 4]); + } + (solid_calls.unwrap_or(calls.len()), total) +} + +impl Flat { + /// `pipeline(layout, label, vertex entry, fragment entry, blend)` builds a + /// terrain pipeline as the per-section ones, without the origin buffer. + pub fn new( + device: &wgpu::Device, + terrain_layout: &wgpu::BindGroupLayout, + page_vertices: u64, + pipeline: impl Fn( + &wgpu::PipelineLayout, + &str, + &str, + Option, + ) -> wgpu::RenderPipeline, + ) -> Self { + let vertex = wgpu::ShaderStages::VERTEX; + let compute = wgpu::ShaderStages::COMPUTE; + let draw_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Flat section draws"), + entries: &[storage(0, vertex, true), storage(1, vertex, true)], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Flat terrain layout"), + bind_group_layouts: &[Some(terrain_layout), Some(&draw_layout)], + ..Default::default() + }); + let compute_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Flatten section draws"), + entries: &[ + storage(0, compute, true), + storage(1, compute, true), + storage(2, compute, false), + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Flatten section draws"), + source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), + }); + let flatten = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Flatten section draws"), + layout: Some( + &device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Flatten section draws"), + bind_group_layouts: &[Some(&compute_layout)], + ..Default::default() + }), + ), + module: &module, + entry_point: Some("flatten"), + compilation_options: Default::default(), + cache: None, + }); + let storage_usage = wgpu::BufferUsages::STORAGE; + Self { + solid: pipeline(&layout, "Terrain solid (flat)", "fs_solid", None), + translucent: pipeline( + &layout, + "Terrain translucent (flat)", + "fs_translucent", + Some(wgpu::BlendState::ALPHA_BLENDING), + ), + flatten, + compute_layout, + draw_layout, + blocks_per_page: page_vertices.div_ceil(GRAIN), + pages: Vec::new(), + free_ids: Vec::new(), + next_id: 0, + origins: buffer(device, "Section origins by id", 16, storage_usage), + origin_capacity: 1, + origin_data: Vec::new(), + indices: buffer( + device, + "Flat section indices", + 16, + wgpu::BufferUsages::INDEX | storage_usage, + ), + index_capacity: 4, + ranges: buffer(device, "Flat section ranges", 16, storage_usage), + range_capacity: 1, + range_data: Vec::new(), + segments: Vec::new(), + empty: buffer(device, "No sorted indices", 16, storage_usage), + calls: Vec::new(), + solid_calls: 0, + min_draws: if std::env::var("HORIZON_FLAT_DRAWS").as_deref() == Ok("1") { + 0 + } else { + MIN_DRAWS + }, + range_align: (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16) + .max(1), + } + } + /// A section uploaded to `vertices` vertices from `start` of `page`: its + /// id, which its blocks now name. + pub fn add( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + page: u32, + start: u64, + vertices: u64, + ) -> u32 { + let id = self.free_ids.pop().unwrap_or_else(|| { + self.next_id += 1; + self.next_id - 1 + }); + let page = page as usize; + if self.pages.len() <= page { + self.pages.resize_with(page + 1, || None); + } + let table = self.pages[page].get_or_insert_with(|| PageTable { + blocks: buffer( + device, + "Section ids by block", + self.blocks_per_page * 4, + wgpu::BufferUsages::STORAGE, + ), + group: None, + }); + let first = start / GRAIN; + let ids = vec![id; vertices.div_ceil(GRAIN) as usize]; + queue.write_buffer(&table.blocks, first * 4, bytemuck::cast_slice(&ids)); + id + } + pub fn remove(&mut self, id: u32) { + self.free_ids.push(id); + } + pub fn clear(&mut self) { + self.pages.clear(); + self.free_ids.clear(); + self.next_id = 0; + } + /// Forgets the tables of pages the arena released. + pub fn trim(&mut self, live: impl Fn(u32) -> bool) { + for (i, page) in self.pages.iter_mut().enumerate() { + if page.is_some() && !live(i as u32) { + *page = None; + } + } + } + /// Builds the frame's index list from `draws` (`DrawIndexedIndirectArgs`: + /// index count, instances, first index, base vertex, first instance), + /// solid ones first, with their (vertex page, sorted index page) and + /// the origins of the sections they draw by id. Records the copy into + /// `encoder`; `calls` then lists the frame's draw calls. False when the + /// frame cannot be drawn flat (the per-section draws then apply). + #[allow(clippy::too_many_arguments)] + pub fn prepare( + &mut self, + device: &wgpu::Device, + encoder: &mut wgpu::CommandEncoder, + uploads: &mut super::upload::Uploads, + draws: &[[u32; 5]], + pages: &[(u32, Option)], + solid_draws: usize, + origins: impl Iterator, + sorted_page: impl Fn(u32) -> wgpu::Buffer, + ) -> bool { + // Origins by section id. + self.origin_data.clear(); + for (id, o) in origins { + let id = id as usize; + if self.origin_data.len() <= id { + self.origin_data.resize(id + 1, [0.0; 4]); + } + self.origin_data[id] = [o[0], o[1], o[2], 0.0]; + } + if self.origin_data.len() as u64 > self.origin_capacity { + self.origin_capacity = (self.origin_data.len() as u64).next_power_of_two(); + self.origins = buffer( + device, + "Section origins by id", + self.origin_capacity * 16, + wgpu::BufferUsages::STORAGE, + ); + for page in self.pages.iter_mut().flatten() { + page.group = None; + } + } + if !self.origin_data.is_empty() { + uploads.buffer( + encoder, + &self.origins, + 0, + bytemuck::cast_slice(&self.origin_data), + ); + } + let (solid_calls, total) = plan( + draws, + pages, + solid_draws, + self.range_align, + &mut self.calls, + &mut self.range_data, + &mut self.segments, + ); + self.solid_calls = solid_calls; + if total == 0 || total * 4 > device.limits().max_storage_buffer_binding_size { + self.calls.clear(); + self.solid_calls = 0; + return false; + } + if self.range_data.len() as u64 > self.range_capacity { + self.range_capacity = (self.range_data.len() as u64).next_power_of_two(); + self.ranges = buffer( + device, + "Flat section ranges", + self.range_capacity * 16, + wgpu::BufferUsages::STORAGE, + ); + } + if total > self.index_capacity { + self.index_capacity = total.next_power_of_two(); + self.indices = buffer( + device, + "Flat section indices", + self.index_capacity * 4, + wgpu::BufferUsages::INDEX | wgpu::BufferUsages::STORAGE, + ); + } + uploads.buffer( + encoder, + &self.ranges, + 0, + bytemuck::cast_slice(&self.range_data), + ); + let groups: Vec<(wgpu::BindGroup, u32)> = self + .segments + .iter() + .map(|&(source, first, count)| { + let sorted = source.map(&sorted_page); + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Flatten section draws"), + layout: &self.compute_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &self.ranges, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: sorted.as_ref().unwrap_or(&self.empty).as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.indices.as_entire_binding(), + }, + ], + }); + (group, count as u32) + }) + .collect(); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Flatten section draws"), + timestamp_writes: None, + }); + pass.set_pipeline(&self.flatten); + for (group, count) in &groups { + pass.set_bind_group(0, group, &[]); + pass.dispatch_workgroups((*count).min(GROUP_LIMIT), count.div_ceil(GROUP_LIMIT), 1); + } + drop(pass); + for page in self.calls.iter().map(|c| c.page) { + let table = self.pages[page as usize] + .as_mut() + .expect("a drawn page has its block table"); + if table.group.is_none() { + table.group = Some(device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Flat section draws"), + layout: &self.draw_layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: table.blocks.as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.origins.as_entire_binding(), + }, + ], + })); + } + } + true + } + /// Draws `calls` with a flat pipeline set and `vertices` giving each + /// page's vertex buffer. + pub fn draw<'a>( + &self, + pass: &mut wgpu::RenderPass<'_>, + calls: &[Call], + vertices: impl Fn(u32) -> &'a wgpu::Buffer, + ) { + pass.set_index_buffer(self.indices.slice(..), wgpu::IndexFormat::Uint32); + for call in calls { + let table = self.pages[call.page as usize] + .as_ref() + .and_then(|t| t.group.as_ref()) + .expect("prepared page"); + pass.set_vertex_buffer(0, vertices(call.page).slice(..)); + pass.set_bind_group(1, table, &[]); + pass.draw_indexed(call.first..call.first + call.count, 0, 0..1); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Draws as `render` writes them: solid (page, quads at a base vertex) + /// first, then translucent (page, sorted page, count, first sorted index, + /// base vertex). + fn sample() -> (Vec<[u32; 5]>, Vec<(u32, Option)>, usize) { + let draws = vec![ + [6 * 3, 1, 0, 0, 0], + [6 * 2, 1, 0, 512, 1], + [6, 1, 0, 256, 2], + [6 * 4, 1, 0, 1024, 3], + [6 * 2, 1, 6, 768, 1], + [6, 1, 0, 40, 0], + ]; + let pages = vec![ + (0, None), + (0, None), + (1, None), + (0, None), + (0, Some(0)), + (0, Some(1)), + ]; + (draws, pages, 4) + } + + #[test] + fn plan_draws_runs_of_a_page_in_order() { + let (draws, pages, solid) = sample(); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let (solid_calls, total) = plan( + &draws, + &pages, + solid, + 4, + &mut calls, + &mut ranges, + &mut segments, + ); + assert_eq!(total, 6 * 13); + let call = |page, first, count| Call { page, first, count }; + // Pages 0, 0 | 1 | 0, then translucent 0, 0 (never merged with solid). + assert_eq!( + calls, + [ + call(0, 0, 30), + call(1, 30, 6), + call(0, 36, 24), + call(0, 60, 18) + ] + ); + assert_eq!(solid_calls, 3); + // Solid ranges, then each sorted page's, every group padded to 4. + assert_eq!(segments, [(None, 0, 4), (Some(0), 4, 1), (Some(1), 8, 1)]); + assert_eq!(ranges[3], [24, QUADS, 1024, 36]); + assert_eq!(ranges[4], [12, 6, 768, 60]); + assert_eq!(ranges[8], [6, 0, 40, 72]); + assert_eq!(ranges.len(), 12); + } + + /// The compute pass writes exactly the indices the per-section draws + /// read: quads 0 1 2 0 2 3 for solid draws, sorted indices otherwise, + /// plus the base vertex. + #[test] + fn flatten_writes_the_indices_of_the_per_section_draws() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle()); + let Ok(adapter) = pollster::block_on(instance.request_adapter(&Default::default())) else { + eprintln!("no GPU adapter: skipped"); + return; + }; + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&Default::default())) + else { + eprintln!("no GPU device: skipped"); + return; + }; + use wgpu::util::DeviceExt; + let (draws, pages, solid) = sample(); + let align = (u64::from(device.limits().min_storage_buffer_offset_alignment) / 16).max(1); + let (mut calls, mut ranges, mut segments) = (Vec::new(), Vec::new(), Vec::new()); + let (_, total) = plan( + &draws, + &pages, + solid, + align, + &mut calls, + &mut ranges, + &mut segments, + ); + let sorted: [Vec; 2] = [ + (0..32).map(|i| (i * 7) % 32).collect(), + (0..8).rev().collect(), + ]; + let mut expected = Vec::new(); + for (d, (_, page)) in draws.iter().zip(&pages) { + for k in 0..d[0] { + let i = match page { + None => (k / 6) * 4 + [0, 1, 2, 0, 2, 3][(k % 6) as usize], + Some(p) => sorted[*p as usize][(d[2] + k) as usize], + }; + expected.push(d[3] + i); + } + } + let storage = |entries: &[u32]| { + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: None, + contents: bytemuck::cast_slice(entries), + usage: wgpu::BufferUsages::STORAGE, + }) + }; + let range_buffer = storage(bytemuck::cast_slice(&ranges)); + let sorted_buffers = [storage(&sorted[0]), storage(&sorted[1]), storage(&[0; 4])]; + let out = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: total * 4, + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }); + let read = device.create_buffer(&wgpu::BufferDescriptor { + label: None, + size: total * 4, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: None, + source: wgpu::ShaderSource::Wgsl(include_str!("flatten.wgsl").into()), + }); + let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: None, + layout: None, + module: &module, + entry_point: Some("flatten"), + compilation_options: Default::default(), + cache: None, + }); + let mut encoder = device.create_command_encoder(&Default::default()); + { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(&pipeline); + for &(source, first, count) in &segments { + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: None, + layout: &pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: &range_buffer, + offset: first * 16, + size: wgpu::BufferSize::new(count * 16), + }), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: sorted_buffers[source.map_or(2, |p| p as usize)] + .as_entire_binding(), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: out.as_entire_binding(), + }, + ], + }); + pass.set_bind_group(0, &group, &[]); + pass.dispatch_workgroups(count as u32, 1, 1); + } + } + encoder.copy_buffer_to_buffer(&out, 0, &read, 0, total * 4); + queue.submit([encoder.finish()]); + read.slice(..).map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::wait_indefinitely()).unwrap(); + let got: Vec = + bytemuck::cast_slice(&read.slice(..).get_mapped_range().unwrap()).to_vec(); + assert_eq!(got, expected); + } +} diff --git a/crates/horizon-client/src/gfx/flatten.wgsl b/crates/horizon-client/src/gfx/flatten.wgsl new file mode 100644 index 000000000..2f57f8775 --- /dev/null +++ b/crates/horizon-client/src/gfx/flatten.wgsl @@ -0,0 +1,35 @@ +// Flat section draws (gfx/flat.rs): copies each section draw's indices into +// one index list, in draw order, offset by the draw's base vertex. Solid +// draws index quads (0 1 2 0 2 3 per quad, as Renderer::quad_indices); +// translucent ones read their sorted indices. +struct Range { + count: u32, + // First sorted index, or QUADS for a solid draw. + first: u32, + base: u32, + dst: u32, +} +const QUADS: u32 = 0xffffffffu; +const GROUP: u32 = 64u; +@group(0) @binding(0) var ranges: array; +@group(0) @binding(1) var sorted: array; +@group(0) @binding(2) var out: array; +@compute @workgroup_size(64) +fn flatten(@builtin(workgroup_id) group: vec3, + @builtin(local_invocation_index) lane: u32) { + let r = group.y * 65535u + group.x; + if r >= arrayLength(&ranges) { + return; + } + let d = ranges[r]; + for (var k = lane; k < d.count; k += GROUP) { + var i: u32; + if d.first == QUADS { + let c = k % 6u; + i = (k / 6u) * 4u + select(select(c - 2u, 0u, c == 3u), c, c < 3u); + } else { + i = sorted[d.first + k]; + } + out[d.dst + k] = d.base + i; + } +} diff --git a/crates/horizon-client/src/gfx/occlusion.rs b/crates/horizon-client/src/gfx/occlusion.rs index e871c50c0..b63e7eae5 100644 --- a/crates/horizon-client/src/gfx/occlusion.rs +++ b/crates/horizon-client/src/gfx/occlusion.rs @@ -2,11 +2,18 @@ //! faces. Breadth-first from the camera section through the faces each //! section's VisGraph connects, never stepping back towards the camera. //! -//! The search runs over dense arrays around the camera rather than hash sets, -//! so it stays cheap enough to redo whenever a section is meshed. +//! As in vanilla, the full search runs off the render thread: a worker keeps +//! its own copy of every section's connectivity and searches over dense +//! arrays around the camera. Frames use the last finished graph and never wait +//! for the next one. A section meshed in between propagates into the graph the +//! frame has (vanilla's partial update), so what it opens shows at once; what +//! it closes goes at the next full search. use super::SectionKey; +use crate::mesher::ALL_VISIBLE; use std::collections::{HashMap, VecDeque}; +use std::sync::mpsc::{self, Receiver, Sender, TryRecvError}; +/// Vanilla's `Direction` order: down, up, north, south, west, east. const STEPS: [(i32, i32, i32); 6] = [ (0, -1, 0), (0, 1, 0), @@ -15,74 +22,92 @@ const STEPS: [(i32, i32, i32); 6] = [ (-1, 0, 0), (1, 0, 0), ]; +/// In `Graph::directions`: the cell has a node. +const REACHED: u8 = 1 << 7; +/// In `Graph::entered`: the camera's own section, entered through no face. const NONE: u8 = 6; -pub struct Occlusion { - /// VisGraph connectivity per column, one entry per section (bottom first). - columns: HashMap<(i32, i32), Box<[u64]>>, +/// VisGraph connectivity per column, one entry per section (bottom first). +/// A missing column or section connects every face. +struct Columns { sections: i32, - dirty: bool, - from: Option, + map: HashMap<(i32, i32), Box<[u64]>>, +} + +impl Columns { + fn new(sections: i32) -> Self { + Self { + sections, + map: HashMap::new(), + } + } + /// Whether the section's connectivity changed. + fn set(&mut self, key: SectionKey, vis: u64) -> bool { + if !(0..self.sections).contains(&key.1) { + return false; + } + let column = match self.map.get_mut(&(key.0, key.2)) { + Some(column) => column, + None if vis == ALL_VISIBLE => return false, + None => self + .map + .entry((key.0, key.2)) + .or_insert_with(|| vec![ALL_VISIBLE; self.sections as usize].into()), + }; + let slot = &mut column[key.1 as usize]; + if *slot == vis { + return false; + } + *slot = vis; + if vis == ALL_VISIBLE && column.iter().all(|&v| v == ALL_VISIBLE) { + self.map.remove(&(key.0, key.2)); + } + true + } + fn get(&self, key: SectionKey) -> u64 { + self.map + .get(&(key.0, key.2)) + .and_then(|column| column.get(usize::try_from(key.1).ok()?)) + .copied() + .unwrap_or(ALL_VISIBLE) + } + fn apply(&mut self, edit: Edit) { + match edit { + Edit::Set(key, vis) => { + self.set(key, vis); + } + Edit::Clear => self.map.clear(), + } + } +} + +#[derive(Clone, Copy)] +enum Edit { + Set(SectionKey, u64), + Clear, +} + +/// One search's result over the box around the camera: vanilla's +/// `GraphStorage.sectionToNodeMap`, as dense arrays. +#[derive(Default)] +struct Graph { + from: SectionKey, radius: i32, /// The searched box: lowest section y and its height in sections. y0: i32, height: i32, - reached: Vec, - vis: Vec, - queue: VecDeque<(u32, u8, u8)>, + /// Per cell: `REACHED`, and the directions travelled from the camera to + /// it (`Node.directions`). + directions: Vec, + /// Per cell: the face it was first entered through (`NONE` for the + /// camera's). Vanilla's `Node.sourceDirections` also keeps the faces it is + /// reached through later; Horizon keeps the first only. + entered: Vec, } -impl Occlusion { - pub fn new(sections: i32) -> Self { - Self { - columns: HashMap::new(), - sections, - dirty: true, - from: None, - radius: 0, - y0: 0, - height: 0, - reached: Vec::new(), - vis: Vec::new(), - queue: VecDeque::new(), - } - } - pub fn set(&mut self, key: SectionKey, vis: u64) { - if !(0..self.sections).contains(&key.1) { - return; - } - let sections = self.sections as usize; - let column = self - .columns - .entry((key.0, key.2)) - .or_insert_with(|| vec![crate::mesher::ALL_VISIBLE; sections].into()); - let slot = &mut column[key.1 as usize]; - if *slot != vis { - *slot = vis; - self.dirty = true; - } - } - pub fn remove(&mut self, key: SectionKey) { - let Some(column) = self.columns.get_mut(&(key.0, key.2)) else { - return; - }; - if let Some(slot) = column.get_mut(key.1 as usize) - && *slot != crate::mesher::ALL_VISIBLE - { - *slot = crate::mesher::ALL_VISIBLE; - self.dirty = true; - } - if column.iter().all(|&v| v == crate::mesher::ALL_VISIBLE) { - self.columns.remove(&(key.0, key.2)); - } - } - pub fn clear(&mut self) { - self.columns.clear(); - self.dirty = true; - } +impl Graph { fn index(&self, key: SectionKey) -> Option { - let from = self.from?; - let (dx, dz, dy) = (key.0 - from.0, key.2 - from.2, key.1 - self.y0); + let (dx, dz, dy) = (key.0 - self.from.0, key.2 - self.from.2, key.1 - self.y0); let side = 2 * self.radius + 1; if dx.abs() > self.radius || dz.abs() > self.radius || !(0..self.height).contains(&dy) { return None; @@ -90,86 +115,331 @@ impl Occlusion { Some((((dz + self.radius) * side + dx + self.radius) * self.height + dy) as usize) } fn key(&self, index: usize) -> SectionKey { - let from = self.from.expect("searched"); let side = 2 * self.radius + 1; let i = index as i32; - let dy = i % self.height; let column = i / self.height; ( - from.0 + column % side - self.radius, - self.y0 + dy, - from.2 + column / side - self.radius, + self.from.0 + column % side - self.radius, + self.y0 + i % self.height, + self.from.2 + column / side - self.radius, ) } - pub fn contains(&self, key: SectionKey) -> bool { - self.index(key).is_some_and(|i| self.reached[i]) + fn contains(&self, key: SectionKey) -> bool { + self.index(key) + .is_some_and(|i| self.directions[i] & REACHED != 0) } - /// Search again when sections changed or the camera moved to another section. - pub fn update(&mut self, from: SectionKey, radius: i32) { - if !self.dirty && self.from == Some(from) && self.radius == radius { - return; - } - self.from = Some(from); + /// The full search from `from` (vanilla's `scheduleFullUpdate`). + fn search( + &mut self, + columns: &Columns, + from: SectionKey, + radius: i32, + vis: &mut Vec, + queue: &mut VecDeque, + ) { + self.from = from; self.radius = radius; self.y0 = from.1.min(-1); - self.height = from.1.max(self.sections) - self.y0 + 1; + self.height = from.1.max(columns.sections) - self.y0 + 1; let side = (2 * radius + 1) as usize; let size = side * side * self.height as usize; - self.reached.clear(); - self.reached.resize(size, false); - self.vis.clear(); - self.vis.resize(size, crate::mesher::ALL_VISIBLE); + self.directions.clear(); + self.directions.resize(size, 0); + self.entered.clear(); + self.entered.resize(size, NONE); + vis.clear(); + vis.resize(size, ALL_VISIBLE); for dz in -radius..=radius { for dx in -radius..=radius { - let Some(column) = self.columns.get(&(from.0 + dx, from.2 + dz)) else { + let Some(column) = columns.map.get(&(from.0 + dx, from.2 + dz)) else { continue; }; let base = self .index((from.0 + dx, 0, from.2 + dz)) .expect("column inside the searched box"); - self.vis[base..base + column.len()].copy_from_slice(column); + vis[base..base + column.len()].copy_from_slice(column); } } let start = self.index(from).expect("camera inside the searched box"); - self.reached[start] = true; - self.queue.clear(); - self.queue.push_back((start as u32, NONE, 0)); - while let Some((index, entered, travelled)) = self.queue.pop_front() { - let vis = self.vis[index as usize]; - let key = self.key(index as usize); + self.directions[start] = REACHED; + queue.clear(); + queue.push_back(start as u32); + self.propagate(queue, columns.sections, |i, _| vis[i]); + } + /// Vanilla's `runUpdates`: take nodes from the queue and step through + /// every face their entry face connects to, away from the camera. + fn propagate( + &mut self, + queue: &mut VecDeque, + sections: i32, + vis: impl Fn(usize, SectionKey) -> u64, + ) { + while let Some(index) = queue.pop_front() { + let i = index as usize; + let key = self.key(i); + let directions = self.directions[i]; + let entered = self.entered[i]; + let exits = if entered == NONE { + 0x3f + } else { + (vis(i, key) >> (u32::from(entered) * 6)) as u8 & 0x3f + }; for (d, step) in STEPS.iter().enumerate() { - let opposite = d ^ 1; - if travelled & (1 << opposite) != 0 { - continue; - } - if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 { + if exits & (1 << d) == 0 || directions & (1 << (d ^ 1)) != 0 { continue; } let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2); - if next.1 < -1 || next.1 > self.sections { + if next.1 < -1 || next.1 > sections { continue; } let Some(n) = self.index(next) else { continue }; - if !self.reached[n] { - self.reached[n] = true; - self.queue - .push_back((n as u32, opposite as u8, travelled | (1 << d))); + if self.directions[n] & REACHED == 0 { + self.directions[n] = directions | 1 << d; + self.entered[n] = (d ^ 1) as u8; + queue.push_back(n as u32); } } } + } +} + +struct Job { + edits: Vec, + from: SectionKey, + radius: i32, + /// Buffers to reuse. + graph: Graph, +} + +/// The thread that runs full searches over its own copy of the columns. +struct Worker { + jobs: Sender, + done: Receiver<(Graph, Vec)>, +} + +impl Worker { + fn spawn(sections: i32) -> Option { + let (jobs, job_rx) = mpsc::channel::(); + let (done_tx, done) = mpsc::channel(); + std::thread::Builder::new() + .name("occlusion".into()) + .spawn(move || { + let mut columns = Columns::new(sections); + let (mut vis, mut queue) = (Vec::new(), VecDeque::new()); + while let Ok(mut job) = job_rx.recv() { + for edit in job.edits.drain(..) { + columns.apply(edit); + } + job.graph + .search(&columns, job.from, job.radius, &mut vis, &mut queue); + if done_tx.send((job.graph, job.edits)).is_err() { + break; + } + } + }) + .ok()?; + Some(Self { jobs, done }) + } +} + +pub struct Occlusion { + /// The render thread's copy, for partial updates (and searches when the + /// worker is gone). + columns: Columns, + /// Edits the worker has not been sent yet. + edits: Vec, + /// A full search is due: sections changed since the last one started. + dirty: bool, + /// The last finished search; `None` until one finishes, or after the + /// columns were cleared. + graph: Option, + spare: Graph, + worker: Option, + /// The camera section and radius of the running search. + running: Option<(SectionKey, i32)>, + /// The running search started before the columns were cleared: drop it. + discard: bool, + /// The camera section and radius `graph`'s search started from (or is + /// starting from). + searched: Option<(SectionKey, i32)>, + /// Sections changed since `graph`'s search started, to propagate from. + changed: Vec, + /// Sections changed since the running search started: they propagate into + /// its graph when it lands. + changed_late: Vec, + vis: Vec, + queue: VecDeque, +} + +impl Occlusion { + pub fn new(sections: i32) -> Self { + Self { + columns: Columns::new(sections), + edits: Vec::new(), + dirty: true, + graph: None, + spare: Graph::default(), + worker: Worker::spawn(sections), + running: None, + discard: false, + searched: None, + changed: Vec::new(), + changed_late: Vec::new(), + vis: Vec::new(), + queue: VecDeque::new(), + } + } + pub fn set(&mut self, key: SectionKey, vis: u64) { + if self.columns.set(key, vis) { + self.edits.push(Edit::Set(key, vis)); + self.dirty = true; + self.changed.push(key); + if self.running.is_some() { + self.changed_late.push(key); + } + } + } + pub fn remove(&mut self, key: SectionKey) { + self.set(key, ALL_VISIBLE); + } + pub fn clear(&mut self) { + self.columns.map.clear(); + self.edits.clear(); + self.edits.push(Edit::Clear); + self.dirty = true; + // Another world: the old graph says nothing about it. + if let Some(graph) = self.graph.take() { + self.spare = graph; + } + self.searched = None; + self.discard = self.running.is_some(); + self.changed.clear(); + self.changed_late.clear(); + } + /// Whether `key` is visible from the camera. Without a usable graph + /// (before the first search lands, or with the camera somewhere the graph + /// never reached) every section is. + pub fn contains(&self, key: SectionKey) -> bool { + self.graph.as_ref().is_none_or(|g| g.contains(key)) + } + /// Take a finished search, propagate changed sections into the graph, + /// and start a search when sections changed or the camera moved to + /// another section. Never waits for the worker. + pub fn update(&mut self, from: SectionKey, radius: i32) { + self.collect(false); + self.propagate_changes(); + if self.running.is_none() && (self.dirty || self.searched != Some((from, radius))) { + self.start(from, radius); + } + // A graph that never reached the camera's section hides everything + // around it: until the new one lands, cull by the frustum alone. + if self + .graph + .as_ref() + .is_some_and(|g| g.from != from && !g.contains(from)) + && let Some(graph) = self.graph.take() + { + self.spare = graph; + } + } + fn start(&mut self, from: SectionKey, radius: i32) { self.dirty = false; + self.searched = Some((from, radius)); + let graph = std::mem::take(&mut self.spare); + if let Some(worker) = &self.worker { + let job = Job { + edits: std::mem::take(&mut self.edits), + from, + radius, + graph, + }; + if worker.jobs.send(job).is_ok() { + self.running = Some((from, radius)); + self.changed_late.clear(); + return; + } + log::warn!("Horizon: the occlusion worker stopped; culling on the render thread"); + self.worker = None; + } + self.edits.clear(); + let mut graph = Graph::default(); + graph.search(&self.columns, from, radius, &mut self.vis, &mut self.queue); + self.land(graph); + } + fn collect(&mut self, wait: bool) { + let Some(worker) = &self.worker else { return }; + if self.running.is_none() { + return; + } + let result = if wait { + worker.done.recv().map_err(|_| TryRecvError::Disconnected) + } else { + worker.done.try_recv() + }; + match result { + Ok((graph, edits)) => { + self.running = None; + if self.edits.is_empty() { + self.edits = edits; + } + if std::mem::take(&mut self.discard) { + self.spare = graph; + return; + } + self.land(graph); + self.changed.clear(); + self.changed.append(&mut self.changed_late); + } + Err(TryRecvError::Empty) => {} + Err(TryRecvError::Disconnected) => { + // The edits it held are lost with it: search here from now on. + self.worker = None; + self.running = None; + self.discard = false; + self.dirty = true; + } + } + } + fn land(&mut self, graph: Graph) { + if let Some(old) = self.graph.replace(graph) { + self.spare = old; + } + } + /// Vanilla's `runPartialUpdate`: what changed sections now connect to. + fn propagate_changes(&mut self) { + let Some(graph) = &mut self.graph else { + self.changed.clear(); + return; + }; + self.queue.clear(); + for key in self.changed.drain(..) { + if let Some(i) = graph.index(key) + && graph.directions[i] & REACHED != 0 + { + self.queue.push_back(i as u32); + } + } + let columns = &self.columns; + graph.propagate(&mut self.queue, columns.sections, |_, key| columns.get(key)); + } + /// Wait for the running search: tests, and A/B timing of the old + /// blocking search. + #[cfg(test)] + fn settle(&mut self, from: SectionKey, radius: i32) { + self.update(from, radius); + self.collect(true); + self.propagate_changes(); } } #[cfg(test)] mod tests { use super::*; - use crate::mesher::ALL_VISIBLE; #[test] fn open_space_reaches_the_whole_box() { let mut o = Occlusion::new(4); - o.update((0, 1, 0), 2); + o.settle((0, 1, 0), 2); for x in -2..=2 { for z in -2..=2 { for y in -1..=4 { @@ -186,11 +456,155 @@ mod tests { for (dx, dy, dz) in STEPS { o.set((dx, 1 + dy, dz), 0); } - o.update((0, 1, 0), 3); + o.settle((0, 1, 0), 3); assert!(o.contains((1, 1, 0)), "a neighbour is seen"); assert!(!o.contains((2, 1, 0)), "nothing shows through it"); o.set((1, 1, 0), ALL_VISIBLE); - o.update((0, 1, 0), 3); + o.settle((0, 1, 0), 3); assert!(o.contains((2, 1, 0))); } + + #[test] + fn frames_never_wait_and_partial_updates_open_at_once() { + let mut o = Occlusion::new(4); + for (dx, dy, dz) in STEPS { + o.set((dx, 1 + dy, dz), 0); + } + o.settle((0, 1, 0), 3); + assert!(!o.contains((2, 1, 0))); + // Opening the wall shows what is behind it in the same frame, from the + // graph the frame has, whether or not the full search has finished. + o.set((1, 1, 0), ALL_VISIBLE); + o.update((0, 1, 0), 3); + assert!(o.contains((2, 1, 0))); + assert!(o.contains((3, 1, 0))); + // Closing it again lasts until the next full search lands. + o.set((1, 1, 0), 0); + o.settle((0, 1, 0), 3); + o.settle((0, 1, 0), 3); + assert!(!o.contains((2, 1, 0))); + } + + #[test] + fn a_graph_that_lost_the_camera_culls_nothing() { + let mut o = Occlusion::new(4); + for (dx, dy, dz) in STEPS { + o.set((dx, 1 + dy, dz), 0); + } + o.settle((0, 1, 0), 3); + assert!(!o.contains((3, 1, 0))); + // The camera jumped past the wall; the next search is still running. + let o = &mut o; + o.update((3, 1, 0), 3); + if o.running.is_some() { + assert!(o.contains((3, 1, 0))); + } + o.settle((3, 1, 0), 3); + assert!(o.contains((3, 1, 0))); + assert!( + !o.contains((0, 1, 0)), + "the old camera section is walled in" + ); + } + + /// The search before it moved to the worker (main at ce38c8d7), over the + /// same box: whether each cell is reached. + fn reference(columns: &Columns, from: SectionKey, radius: i32) -> Vec { + let y0 = from.1.min(-1); + let height = from.1.max(columns.sections) - y0 + 1; + let side = 2 * radius + 1; + let index = |k: SectionKey| { + let (dx, dz, dy) = (k.0 - from.0, k.2 - from.2, k.1 - y0); + (dx.abs() <= radius && dz.abs() <= radius && (0..height).contains(&dy)) + .then(|| (((dz + radius) * side + dx + radius) * height + dy) as usize) + }; + let size = (side * side * height) as usize; + let mut reached = vec![false; size]; + let start = index(from).unwrap(); + reached[start] = true; + let mut queue = VecDeque::from([(from, NONE, 0u8)]); + while let Some((key, entered, travelled)) = queue.pop_front() { + let vis = columns.get(key); + for (d, step) in STEPS.iter().enumerate() { + let opposite = d ^ 1; + if travelled & (1 << opposite) != 0 { + continue; + } + if entered != NONE && vis & (1 << (usize::from(entered) * 6 + d)) == 0 { + continue; + } + let next = (key.0 + step.0, key.1 + step.1, key.2 + step.2); + if next.1 < -1 || next.1 > columns.sections { + continue; + } + let Some(n) = index(next) else { continue }; + if !reached[n] { + reached[n] = true; + queue.push_back((next, opposite as u8, travelled | (1 << d))); + } + } + } + reached + } + + fn random_world(o: &mut Occlusion, seed: u64, count: usize) { + let mut seed = seed; + let mut next = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + seed + }; + for _ in 0..count { + let r = next(); + let key = ( + (r % 13) as i32 - 6, + ((r >> 8) % 6) as i32, + ((r >> 16) % 13) as i32 - 6, + ); + // Open, half open or nearly closed sections. + let vis = match r >> 40 & 3 { + 0 => next() & next() & next(), + 1 => next(), + _ => next() | next(), + }; + o.set(key, vis & ALL_VISIBLE); + } + } + + /// The graph is the search the render thread did before, cell for cell. + #[test] + fn same_sections_as_before() { + let mut hidden = 0; + for seed in [0x9e37_79b9, 7, 0xdead_beef] { + let mut o = Occlusion::new(6); + random_world(&mut o, seed, 900); + for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4), (1, -1, 1), (0, 7, 0)] { + o.settle(from, 6); + o.settle(from, 6); + let graph = o.graph.as_ref().expect("searched"); + let reached: Vec = + graph.directions.iter().map(|&d| d & REACHED != 0).collect(); + assert_eq!(reached, reference(&o.columns, from, 6), "{seed} {from:?}"); + hidden += reached.iter().filter(|&&r| !r).count(); + } + } + assert!(hidden > 1000, "the worlds hide sections ({hidden})"); + } + + /// The worker's graph is the one the render thread would compute. + #[test] + fn the_worker_matches_a_search_on_the_render_thread() { + let mut o = Occlusion::new(6); + random_world(&mut o, 0x9e37_79b9, 800); + for from in [(0, 2, 0), (3, 0, -2), (-5, 5, 4)] { + o.settle(from, 6); + o.settle(from, 6); + let mut local = Graph::default(); + local.search(&o.columns, from, 6, &mut Vec::new(), &mut VecDeque::new()); + let graph = o.graph.as_ref().expect("searched"); + assert_eq!(graph.directions, local.directions); + assert_eq!(graph.entered, local.entered); + } + } } diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index b3daeeaa4..5d2354234 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -1,5 +1,9 @@ //! GPU frame time from timestamp queries, read back a few frames late so the //! CPU never waits for it. Frames whose readback slot is still busy go untimed. +//! +//! Where the GPU can only time pass boundaries (Apple GPUs on Metal), the +//! frame is bracketed by two one-thread compute passes that write the +//! timestamps (Metal leaves an empty pass's timestamps at zero). use std::sync::{ Arc, atomic::{AtomicU8, Ordering}, @@ -23,24 +27,18 @@ pub struct GpuTimer { current: Option, next: usize, period_ns: f32, + /// Timestamps between commands, or else this pass's boundaries. + marker: Option, } impl GpuTimer { - /// The features timing needs; `None` when the adapter lacks them. + /// The features timing uses that the adapter has (none: no timing). pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { - let wanted = - wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS; - if adapter.features().contains(wanted) { - wanted - } else { - wgpu::Features::empty() - } + adapter.features() + & (wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS) } pub fn new(device: &wgpu::Device, queue: &wgpu::Queue) -> Option { - if !device - .features() - .contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS) - { + if !device.features().contains(wgpu::Features::TIMESTAMP_QUERY) { return None; } let queries = device.create_query_set(&wgpu::QuerySetDescriptor { @@ -72,21 +70,56 @@ impl GpuTimer { current: None, next: 0, period_ns: queue.get_timestamp_period(), + marker: (!device + .features() + .contains(wgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERS)) + .then(|| { + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Frame timestamp"), + source: wgpu::ShaderSource::Wgsl( + "@compute @workgroup_size(1) fn mark() {}".into(), + ), + }); + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("Frame timestamp"), + layout: None, + module: &module, + entry_point: Some("mark"), + compilation_options: Default::default(), + cache: None, + }) + }), }) } pub fn begin(&mut self, encoder: &mut wgpu::CommandEncoder) { let slot = self.next; self.current = (self.slots[slot].state.load(Ordering::Acquire) == FREE).then_some(slot); if self.current.is_some() { - encoder.write_timestamp(&self.queries, 0); + self.stamp(encoder, 0); } } pub fn end(&mut self, encoder: &mut wgpu::CommandEncoder) { let Some(slot) = self.current else { return }; - encoder.write_timestamp(&self.queries, 1); + self.stamp(encoder, 1); encoder.resolve_query_set(&self.queries, 0..2, &self.resolve, 0); encoder.copy_buffer_to_buffer(&self.resolve, 0, &self.slots[slot].buffer, 0, 16); } + fn stamp(&self, encoder: &mut wgpu::CommandEncoder, index: u32) { + let Some(marker) = &self.marker else { + encoder.write_timestamp(&self.queries, index); + return; + }; + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { + label: Some("Frame timestamp"), + timestamp_writes: Some(wgpu::ComputePassTimestampWrites { + query_set: &self.queries, + beginning_of_pass_write_index: (index == 0).then_some(0), + end_of_pass_write_index: (index == 1).then_some(1), + }), + }); + pass.set_pipeline(marker); + pass.dispatch_workgroups(1, 1, 1); + } /// After the frame's submission: start reading its timestamps back. pub fn submitted(&mut self) { let Some(slot) = self.current.take() else { diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index f10c6b3b3..b564825e7 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -53,7 +53,9 @@ impl Preset { /// How the swapchain presents frames. #[derive(Clone, Copy, Debug, PartialEq, Eq, Default)] pub enum PresentMode { - /// Follow vanilla's VSync option (Mailbox or Fifo on, Immediate off). + /// Vanilla's choice: Fifo with VSync on, else the first of Immediate, + /// Mailbox and Fifo the surface supports. The other modes apply only + /// with VSync off: VSync on always presents with Fifo. #[default] Auto, Fifo, @@ -271,9 +273,14 @@ impl Graphics { if self.workers > 0 { return self.workers as usize; } + // The pool never takes every core. The render thread and the + // integrated server thread (single player runs on its own server + // thread by default) each need one, and a pool that fills every core + // starves them: the frame rate collapses to single digits while the + // workers saturate the CPU and its memory bandwidth. let auto = std::thread::available_parallelism() .map_or(2, |n| n.get()) - .saturating_sub(1) + .saturating_sub(2) .max(1); if self.battery { auto.div_ceil(2) } else { auto } } @@ -357,6 +364,17 @@ mod tests { ); } + #[test] + fn automatic_workers_leave_cores_for_the_render_and_server_threads() { + let g = Graphics::default(); + assert_eq!(g.workers, 0); + let cores = std::thread::available_parallelism().map_or(2, |n| n.get()); + assert_eq!(g.worker_threads(), cores.saturating_sub(2).max(1)); + // A manual count is the player's own choice, kept as asked. + let manual = Graphics { workers: 3, ..g }; + assert_eq!(manual.worker_threads(), 3); + } + #[test] fn battery_mode_only_lowers_the_frame_cap() { let mut g = Graphics::default(); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 745cd5d80..4d7619037 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -211,7 +211,7 @@ pub fn rows(level: Level) -> Vec { h( H::PresentMode, None, - "How frames reach the screen. Auto follows VSync.", + "How frames reach the screen while VSync is off.", ), h( H::Pacing, diff --git a/crates/horizon-client/src/health.rs b/crates/horizon-client/src/health.rs index db0677d5f..493488732 100644 --- a/crates/horizon-client/src/health.rs +++ b/crates/horizon-client/src/health.rs @@ -161,6 +161,8 @@ pub struct PlayerHealth { pub ids: PlayerFloatIds, pub food: FoodData, pub hurt: State, + /// Client hurt animation; fully blocked hits only refresh the server's hurt state. + pub hurt_animation_time: i32, pub dead: bool, pub sync_velocity: bool, pub game_time: i64, @@ -210,6 +212,7 @@ impl PlayerHealth { last_source: None, last_stamp: 0, }, + hurt_animation_time: 0, dead: false, sync_velocity: false, game_time: 0, @@ -242,6 +245,9 @@ impl PlayerHealth { if self.hurt.hurt_time > 0 { self.hurt.hurt_time -= 1; } + if self.hurt_animation_time > 0 { + self.hurt_animation_time -= 1; + } } } impl PlayerMotion { @@ -300,8 +306,11 @@ impl PlayerMotion { sound: environment.block_sound, }; if environment.totem_fired { - self.health.totem_used = true; - self.health.totem_ready = false; + h.totem_used = true; + h.totem_ready = false; + } + if outcome.hurt { + h.hurt_animation_time = h.hurt.hurt_time; } Ok(outcome) } diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index 90b11f18d..fa1b62a5e 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -55,6 +55,7 @@ impl PlayerMotion { data: &mut h.data, ids: h.ids, hurt: &mut h.hurt, + hurt_animation_time: &mut h.hurt_animation_time, dead: &mut h.dead, sync_velocity: &mut h.sync_velocity, game_time: h.game_time, @@ -70,6 +71,7 @@ struct TickWorld<'a> { data: &'a mut SyncedFloats, ids: PlayerFloatIds, hurt: &'a mut State, + hurt_animation_time: &'a mut i32, dead: &'a mut bool, sync_velocity: &'a mut bool, game_time: i64, @@ -142,8 +144,11 @@ impl FoodWorld for TickWorld<'_> { totem: false, totem_fired: false, }; - ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)? - .hurt(self.hurt, amount)?; + if ServerPlayerCombat::new(self.attributes, self.data, food, self.ids, &mut environment)? + .hurt(self.hurt, amount)? + { + *self.hurt_animation_time = self.hurt.hurt_time; + } Ok(()) } } diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index d54564b7a..adc4e0f18 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -110,6 +110,16 @@ pub const OMINOUS_LAYERS: [(&str, &str); 8] = [ ("circle", "light_gray"), ("border", "black"), ]; + +/// The raid captain banner's default tooltip setting, stored by vanilla as a +/// component but represented by `StackData::ominous_banner` in Horizon. +fn ominous_tooltip_display() -> Tag { + Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), + )]) +} + /// `WrittenBookContent` with the pages as plain text. #[derive(Clone, Debug, Default, PartialEq)] pub struct WrittenBook { @@ -610,13 +620,9 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { "minecraft:banner_patterns", Tag::List(OMINOUS_LAYERS.iter().map(|(p, c)| layer(p, c)).collect()), )); - entries.push(( - "minecraft:tooltip_display", - Tag::compound([( - "hidden_components", - Tag::List(vec![Tag::String("minecraft:banner_patterns".into())]), - )]), - )); + if d.other("minecraft:tooltip_display").is_none() { + entries.push(("minecraft:tooltip_display", ominous_tooltip_display())); + } entries.push(( "minecraft:item_name", Tag::compound([( @@ -793,10 +799,8 @@ pub fn decode_components(components: Option<&Tag>) -> (u32, Option { + component: Option<&'a Tag>, + ominous_banner: bool, +} + +impl<'a> TooltipDisplay<'a> { + pub fn for_stack(stack: &'a ItemStack) -> Self { + Self { + component: stack + .data() + .and_then(|data| data.other("minecraft:tooltip_display")), + ominous_banner: stack.data().is_some_and(|data| data.ominous_banner), + } + } + + fn hides_tooltip(&self) -> bool { + matches!( + self.component.and_then(|display| display.get("hide_tooltip")), + Some(Tag::Byte(value)) if *value != 0 + ) + } + + /// `ItemStack.getTooltipLines`: `hide_tooltip` suppresses the name unless + /// the tooltip flag is creative. + pub fn name_visible(&self, creative: bool) -> bool { + creative || !self.hides_tooltip() + } + + /// `TooltipDisplay.shows`: whether details for a data component are shown. + pub fn shows(&self, component: &str) -> bool { + if self.hides_tooltip() { + return false; + } + // `item_data::decode_components` models the raid captain banner's + // default hidden pattern tooltip as `ominous_banner` instead of + // retaining its redundant `tooltip_display` component. + if self.ominous_banner + && self.component.is_none() + && component == "minecraft:banner_patterns" + { + return false; + } + let Some(Tag::List(hidden)) = self + .component + .and_then(|display| display.get("hidden_components")) + else { + return true; + }; + let component = horizon_world::nbt::JavaString::from(component); + !hidden + .iter() + .any(|tag| matches!(tag, Tag::String(id) if id == &component)) + } +} /// `EquipmentSlotGroup` in declaration order, the order tooltips list them in. const SLOT_GROUPS: [&str; 11] = [ @@ -348,6 +406,49 @@ pub fn lines( mod tests { use super::*; + #[test] + fn tooltip_display_controls_name_and_component_visibility() { + let mut stack = ItemStack::new("minecraft:diamond_sword", 1); + let display = TooltipDisplay::for_stack(&stack); + assert!(display.name_visible(false)); + assert!(display.shows("minecraft:attribute_modifiers")); + + stack.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::compound([( + "hidden_components", + Tag::List(vec![Tag::String("minecraft:attribute_modifiers".into())]), + )])), + ); + let display = TooltipDisplay::for_stack(&stack); + assert!(display.name_visible(false)); + assert!(!display.shows("minecraft:attribute_modifiers")); + assert!(display.shows("minecraft:enchantments")); + + stack.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::compound([("hide_tooltip", Tag::Byte(1))])), + ); + let display = TooltipDisplay::for_stack(&stack); + assert!(!display.name_visible(false)); + assert!(display.name_visible(true)); + assert!(!display.shows("minecraft:attribute_modifiers")); + } + + #[test] + fn ominous_banner_keeps_its_default_hidden_pattern_tooltip() { + let mut banner = crate::mobs::raider::ominous_banner(); + let display = TooltipDisplay::for_stack(&banner); + assert!(!display.shows("minecraft:banner_patterns")); + + banner.data_mut().set_other( + "minecraft:tooltip_display", + Some(Tag::Compound(Default::default())), + ); + let display = TooltipDisplay::for_stack(&banner); + assert!(display.shows("minecraft:banner_patterns")); + } + #[test] fn ominous_banner_name_and_rarity_use_the_stack() { let translate = |key: &str| match key { diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 54a505ab9..2782d254f 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -39,6 +39,25 @@ pub struct ToolRule { pub speed: Option, pub correct: Option, } +#[derive(Clone, Debug, PartialEq)] +pub struct ConsumeEffectSpec { + pub id: String, + pub duration: i32, + pub amplifier: i32, +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ConsumeEffect { + ApplyEffects { + effects: Vec, + probability: f32, + }, + ClearAllEffects, + RemoveEffects(Vec), + TeleportRandomly, + PlaySound(String), +} + #[derive(Clone, Debug)] pub struct ItemInfo { pub fire_resistant: bool, @@ -49,7 +68,9 @@ pub struct ItemInfo { pub tool: Vec, pub tool_default_speed: f32, pub food: Option<(u32, f32)>, + pub can_always_eat: bool, pub consumable: bool, + pub consume_effects: Vec, pub model: String, /// Main-hand `attack_damage` / `attack_speed` modifier amounts. pub attack_damage: f32, @@ -421,6 +442,79 @@ impl Items { f["saturation"].as_f64().unwrap_or(0.0) as f32, ) }); + let can_always_eat = c + .get("minecraft:food") + .and_then(|f| f.get("can_always_eat")) + .and_then(|v| v.as_bool()) + .unwrap_or(false); + let mut consume_effects = Vec::new(); + if let Some(effects) = c + .get("minecraft:consumable") + .and_then(|cons| cons.get("on_consume_effects")) + .and_then(|e| e.as_array()) + { + for effect in effects { + match effect.get("type").and_then(|t| t.as_str()) { + Some("minecraft:apply_effects") => { + let probability = effect + .get("probability") + .and_then(|p| p.as_f64()) + .map_or(1.0, |p| p as f32); + let mut specs = Vec::new(); + if let Some(list) = effect.get("effects").and_then(|l| l.as_array()) { + for e in list { + if let Some(id) = e.get("id").and_then(|i| i.as_str()) { + let duration = + e.get("duration").and_then(|d| d.as_i64()).unwrap_or(0) + as i32; + let amplifier = e + .get("amplifier") + .and_then(|a| a.as_i64()) + .unwrap_or(0) + as i32; + specs.push(ConsumeEffectSpec { + id: id.to_string(), + duration, + amplifier, + }); + } + } + } + consume_effects.push(ConsumeEffect::ApplyEffects { + effects: specs, + probability, + }); + } + Some("minecraft:clear_all_effects") => { + consume_effects.push(ConsumeEffect::ClearAllEffects); + } + Some("minecraft:remove_effects") => { + let mut targets = Vec::new(); + if let Some(eff) = effect.get("effects") { + if let Some(s) = eff.as_str() { + targets.push(s.to_string()); + } else if let Some(arr) = eff.as_array() { + for item in arr { + if let Some(s) = item.as_str() { + targets.push(s.to_string()); + } + } + } + } + consume_effects.push(ConsumeEffect::RemoveEffects(targets)); + } + Some("minecraft:teleport_randomly") => { + consume_effects.push(ConsumeEffect::TeleportRandomly); + } + Some("minecraft:play_sound") => { + if let Some(sound) = effect.get("sound").and_then(|s| s.as_str()) { + consume_effects.push(ConsumeEffect::PlaySound(sound.to_string())); + } + } + _ => {} + } + } + } items.insert( id.clone(), ItemInfo { @@ -435,7 +529,9 @@ impl Items { .as_f64() .unwrap_or(1.0) as f32, food, + can_always_eat, consumable: c.get("minecraft:consumable").is_some(), + consume_effects, model: c["minecraft:item_model"] .as_str() .unwrap_or(name) @@ -1496,6 +1592,34 @@ mod tests { .is_empty() ); } + + #[test] + fn always_edible_and_consume_effects_loaded() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("items.json").exists() { + return; + } + let assets = crate::assets::Assets::load(&root).unwrap(); + let facts = crate::blocks::BlockFacts::load(&root, assets.registry).unwrap(); + let items = Items::load(&root, assets.registry, &facts).unwrap(); + + let apple = items.get("minecraft:golden_apple").expect("golden apple"); + assert!(apple.can_always_eat); + assert!(apple.food.is_some()); + assert!(!apple.consume_effects.is_empty()); + + let enchanted = items + .get("minecraft:enchanted_golden_apple") + .expect("enchanted golden apple"); + assert!(enchanted.can_always_eat); + assert!(enchanted.food.is_some()); + assert!(!enchanted.consume_effects.is_empty()); + + let beef = items.get("minecraft:cooked_beef").expect("cooked beef"); + assert!(!beef.can_always_eat); + assert!(beef.food.is_some()); + } } pub fn take_held_drop(slot: &mut Option, all: bool) -> Option { diff --git a/crates/horizon-client/src/lan/advancements.rs b/crates/horizon-client/src/lan/advancements.rs index 0e0caf7ff..2e478e2b8 100644 --- a/crates/horizon-client/src/lan/advancements.rs +++ b/crates/horizon-client/src/lan/advancements.rs @@ -144,6 +144,13 @@ impl ServerAdvancements { ) -> Option> { let n = self.tree.list.len(); let first = visible.len() != n; + // flushDirty does nothing unless it is the first packet or progress + // changed: visibility follows progress alone, and every grant and + // revoke is in `changed`. This skips walking the whole tree for + // every player every tick. + if !first && changed.is_empty() { + return None; + } let now = self .tree .visible(&self.kids, |i| progress.done(&self.tree.list[i])); @@ -282,6 +289,20 @@ impl ServerAdvancements { book_add(entries, true) } + /// The recipe's display for ClientboundPlaceGhostRecipePacket (the + /// recipes the book lists). + pub fn ghost_display( + &self, + id: &str, + sync: &SyncData, + ) -> Option { + let bytes = self.book_entries(id, sync, 0).into_iter().next()?; + let mut r = horizon_protocol::buf::Reader::new(&bytes); + horizon_protocol::packets::recipes::RecipeBookEntry::read(&mut r) + .ok() + .map(|e| e.display) + } + /// ClientboundRecipeBookAddPacket.Entry for each display of a recipe: /// highlighted, and with a notification unless the recipe turns it off. fn book_entries(&self, id: &str, sync: &SyncData, flags: i8) -> Vec> { diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index 6b8c41e55..d6a7dc3a1 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -4,10 +4,13 @@ use crate::{ chunk::{Chunk, Light, MIN_Y, SECTIONS, Section}, containers::BlockEntity, + fast_hash::FxHashMap, }; use horizon_protocol::{ - buf::set_bit, - chunk::{BIOMES, BLOCKS, BlockEntityInfo, ChunkData, LightData, Paletted, Strategy}, + buf::{BitSet, Codec, List, Writer, set_bit}, + chunk::{ + BIOMES, BLOCKS, BlockEntityInfo, ChunkData, Heightmaps, LightData, Paletted, Strategy, + }, packets::play::LevelChunkWithLight, registry::{Builtin, ceil_log2}, }; @@ -91,7 +94,7 @@ pub struct ChunkEncoder { /// The save's tables, for the heightmaps. pub tables: Option>, /// Sections already looked at, by address (see `Encoded`). - cache: std::sync::Mutex>, + cache: std::sync::Mutex>, /// Each column's heightmaps, with the sections they were made from. heights: std::sync::Mutex>, /// The level's sections among a column's: all of them in the Overworld, @@ -104,9 +107,12 @@ pub struct ChunkEncoder { /// A column's client heightmaps, valid while it holds the same sections. struct Heights { sections: Vec>, - maps: Vec<(i32, Vec)>, + maps: ColumnHeightmaps, } +/// Heightmap type ids with their packed long arrays. +type ColumnHeightmaps = Arc)>>; + /// What a resident section gives the wire, kept while the section is /// unchanged. Resident sections are immutable behind `Arc` (edits go through /// `Arc::make_mut`, which moves an edited section to a new address while a @@ -115,12 +121,16 @@ struct Heights { struct Encoded { section: std::sync::Weak
, non_air: bool, - /// LevelChunkSection.write, and whether it holds block entity blocks. - wire: Option<(Arc<[u8]>, bool)>, + /// LevelChunkSection.write, and its block entity blocks. + wire: Option<(Arc<[u8]>, Entities)>, /// The section's light as the wire's two DataLayers, when not uniform. light: Option>, } +/// A section's blocks that have a block entity type, as (index, state) in +/// index order (y, then z, then x). +type Entities = Arc<[(u16, u32)]>; + /// One section's light as DataLayers (two blocks per byte, the even one in /// the low nibble), and whether each holds any light. struct Layers { @@ -223,7 +233,7 @@ impl ChunkEncoder { /// The client heightmaps (Heightmap.prime over the column), from the /// cache while the column's sections are unchanged. - fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> Vec<(i32, Vec)> { + fn heightmaps(&self, chunk: &Chunk, tables: &crate::save::SaveTables) -> ColumnHeightmaps { let same = |h: &Heights| { h.sections.len() == chunk.sections.len() && h.sections @@ -245,7 +255,9 @@ impl ChunkEncoder { } let min_y = MIN_Y + 16 * self.sections.start as i32; let height = 16 * self.sections.len() as i32; - let maps = crate::save::client_heightmaps_in(chunk, tables, min_y, height); + let maps = Arc::new(crate::save::client_heightmaps_in( + chunk, tables, min_y, height, + )); heights.insert( (chunk.x, chunk.z), Heights { @@ -258,22 +270,29 @@ impl ChunkEncoder { /// The cached entry for a section, made with `non_air` when missing. fn cached(&self, section: &Arc
, read: impl FnOnce(&mut Encoded) -> T) -> T { - let mut cache = self.cache.lock().unwrap(); + read(self.entry(&mut self.cache.lock().unwrap(), section)) + } + + /// A section's entry in the locked cache, made with `non_air` when missing. + fn entry<'a>( + &self, + cache: &'a mut FxHashMap, + section: &Arc
, + ) -> &'a mut Encoded { if cache.len() >= CACHE_SWEEP { cache.retain(|_, e| e.section.strong_count() > 0); if cache.len() >= CACHE_SWEEP / 2 { cache.clear(); } } - let entry = cache + cache .entry(Arc::as_ptr(section) as usize) .or_insert_with(|| Encoded { section: Arc::downgrade(section), non_air: self.non_air(section), wire: None, light: None, - }); - read(entry) + }) } /// LevelChunkSection.hasOnlyAir, negated. @@ -291,14 +310,14 @@ impl ChunkEncoder { } /// A section on the wire, from the cache or encoded now. - fn section_wire(&self, section: &Arc
) -> (Arc<[u8]>, bool) { + fn section_wire(&self, section: &Arc
) -> (Arc<[u8]>, Entities) { if let Some(wire) = self.cached(section, |e| e.wire.clone()) { return wire; } let (encoded, entities) = self.section(section); let mut w = horizon_protocol::buf::Writer::new(); encoded.write(&mut w); - let wire: (Arc<[u8]>, bool) = (w.data.into(), entities); + let wire: (Arc<[u8]>, Entities) = (w.data.into(), entities.into()); self.cached(section, |e| e.wire = Some(wire.clone())); wire } @@ -314,23 +333,23 @@ impl ChunkEncoder { // The heightmaps depend on the level's height. self.heights.get_mut().unwrap().clear(); } - pub fn entity_type(&self, state: u16) -> Option { + pub fn entity_type(&self, state: u32) -> Option { self.entity_types - .get(usize::from(state)) + .get(state as usize) .filter(|t| **t >= 0) .map(|t| i32::from(*t)) } - pub fn is_air(&self, state: u16) -> bool { + pub fn is_air(&self, state: u32) -> bool { self.flags - .get(usize::from(state)) + .get(state as usize) .is_none_or(|f| f & NON_AIR == 0) } - fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, bool) { + fn section(&self, section: &Section) -> (horizon_protocol::chunk::Section, Vec<(u16, u32)>) { let mut values = Vec::with_capacity(BLOCKS); - let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, false); - let mut count = |state: u16, n: i16| { - let f = self.flags.get(usize::from(state)).copied().unwrap_or(0); + let (mut non_empty, mut fluids, mut entities) = (0i16, 0i16, Vec::new()); + let mut count = |state: u32, n: i16| { + let f = self.flags.get(state as usize).copied().unwrap_or(0); if f & NON_AIR != 0 { non_empty += n; if f & FLUID != 0 { @@ -342,13 +361,17 @@ impl ChunkEncoder { // One block everywhere (all air, mostly): what from_values would give. let uniform = section.blocks.uniform(); if let Some(v) = uniform { - entities = count(v as u16, BLOCKS as i16); + if count(v, BLOCKS as i16) { + entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); + } } else { - let mut unpacked = [0u16; BLOCKS]; + let mut unpacked = [0u32; BLOCKS]; section.unpack(&mut unpacked); - for &v in &unpacked { - entities |= count(v, 1); - values.push(i32::from(v)); + for (i, &v) in unpacked.iter().enumerate() { + if count(v, 1) { + entities.push((i as u16, v)); + } + values.push(v as i32); } } let biome_values: Vec = (0..BIOMES) @@ -370,7 +393,11 @@ impl ChunkEncoder { palette: vec![v as i32], data: Vec::new(), }, - None => Paletted::from_values(&values, Strategy::Blocks, 16), + None => Paletted::from_values( + &values, + Strategy::Blocks, + crate::chunk::block_strategy().global_bits, + ), }, biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), }, @@ -382,17 +409,18 @@ impl ChunkEncoder { /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { let mut bits = 0u64; + // One lock for the column: body_in asks for nine columns' sections. + let mut cache = self.cache.lock().unwrap(); for (i, s) in chunk.sections[self.sections.clone()].iter().enumerate() { - if self.cached(s, |e| e.non_air) { + if self.entry(&mut cache, s).non_air { bits |= 1 << i; } } bits } - /// The chunk column with its light and block entities. `world` gives the - /// neighbouring columns, whose sections decide which light layers exist. - pub fn encode_in(&self, chunk: &Chunk, world: &crate::world::World) -> LevelChunkWithLight { + /// The non-air sections of the column and its neighbours, as bits. + fn around(&self, chunk: &Chunk, world: &crate::world::World) -> u64 { let mut around = 0u64; for dz in -1..=1 { for dx in -1..=1 { @@ -401,9 +429,55 @@ impl ChunkEncoder { } } } - let mut packet = self.encode_blocks(chunk, &world.block_entities); - packet.light = self.light_data(chunk, around); - packet + around + } + + /// The chunk column with its light and block entities, as the body + /// `Clientbound::encode` gives for its LevelChunkWithLight. `world` gives + /// the neighbouring columns, whose sections decide which light layers + /// exist. It is written once into a buffer of its final size: the cached + /// sections and light layers go straight to it, with no packet built and + /// copied again first. + pub fn body_in(&self, chunk: &Chunk, world: &crate::world::World) -> Vec { + self.body(chunk, &world.block_entities, self.around(chunk, world)) + } + + fn body( + &self, + chunk: &Chunk, + block_entities: &HashMap<(i32, i32, i32), BlockEntity>, + around: u64, + ) -> Vec { + let (wires, entities) = self.blocks(chunk, block_entities); + let heightmaps = self.heightmaps_of(chunk); + let lights = self.light_sections(chunk, around); + let buffer: usize = wires.iter().map(|w| w.len()).sum(); + // Before the light: their tags' size is only known once written. + let mut tags = Writer::new(); + List::::write(&entities, &mut tags); + // The masks, counts and lengths fit the 64 bytes. + let size = 64 + + heightmaps + .iter() + .map(|(_, h)| 10 + 8 * h.len()) + .sum::() + + buffer + + tags.data.len() + + lights.len() * 2 * (2048 + 3); + let mut w = Writer { + data: Vec::with_capacity(size), + }; + w.varint(horizon_protocol::ids::play::clientbound::LEVEL_CHUNK_WITH_LIGHT); + w.i32(chunk.x); + w.i32(chunk.z); + Heightmaps::write(&*heightmaps, &mut w); + w.varint(buffer as i32); + for wire in &wires { + w.bytes(wire); + } + w.bytes(&tags.data); + write_light(&lights, self.sky, &mut w); + w.data } pub fn encode( @@ -422,7 +496,41 @@ impl ChunkEncoder { chunk: &Chunk, block_entities: &HashMap<(i32, i32, i32), BlockEntity>, ) -> LevelChunkWithLight { - let mut buffer = Vec::new(); + let (wires, block_entities) = self.blocks(chunk, block_entities); + LevelChunkWithLight { + x: chunk.x, + z: chunk.z, + chunk: ChunkData { + heightmaps: self.heightmaps_of(chunk).to_vec(), + buffer: wires.concat(), + block_entities, + }, + light: LightData { + sky_mask: Vec::new(), + block_mask: Vec::new(), + empty_sky_mask: Vec::new(), + empty_block_mask: Vec::new(), + sky: Vec::new(), + block: Vec::new(), + }, + } + } + + fn heightmaps_of(&self, chunk: &Chunk) -> ColumnHeightmaps { + self.tables + .as_ref() + .map(|t| self.heightmaps(chunk, t)) + .unwrap_or_default() + } + + /// The level's sections on the wire, and the column's block entities in + /// the packet's order. + fn blocks( + &self, + chunk: &Chunk, + block_entities: &HashMap<(i32, i32, i32), BlockEntity>, + ) -> (Vec>, Vec) { + let mut wires = Vec::with_capacity(self.sections.len()); let mut entity_infos = Vec::new(); for (i, s) in chunk .sections @@ -431,31 +539,32 @@ impl ChunkEncoder { .skip(self.sections.start) .take(self.sections.len()) { - let (encoded, has_entities) = self.section_wire(s); - if has_entities { - for y in 0..16 { - for z in 0..16 { - for x in 0..16 { - let state = s.get(crate::chunk::index(x, y, z)); - if let Some(kind) = self.entity_type(state) { - let wy = MIN_Y + (i as i32) * 16 + y; - let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z); - entity_infos.push(BlockEntityInfo { - packed_xz: ((x << 4) | z) as i8, - y: wy as i16, - kind, - // BlockEntityInfo.create: an empty update tag is not sent. - tag: block_entities - .get(&pos) - .and_then(entity_tag) - .unwrap_or(Tag::End), - }); - } - } - } - } + let (encoded, entities) = self.section_wire(s); + // The section's block entity blocks, kept with its bytes, in the + // order a scan of every block would find them. + for &(index, state) in entities.iter() { + let Some(kind) = self.entity_type(state) else { + continue; + }; + let (x, y, z) = ( + i32::from(index & 15), + i32::from(index >> 8), + i32::from(index >> 4 & 15), + ); + let wy = MIN_Y + (i as i32) * 16 + y; + let pos = (chunk.x * 16 + x, wy, chunk.z * 16 + z); + entity_infos.push(BlockEntityInfo { + packed_xz: ((x << 4) | z) as i8, + y: wy as i16, + kind, + // BlockEntityInfo.create: an empty update tag is not sent. + tag: block_entities + .get(&pos) + .and_then(entity_tag) + .unwrap_or(Tag::End), + }); } - buffer.extend_from_slice(&encoded); + wires.push(encoded); } // A loaded chunk's block entities enter its maps in the save's order // (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities): @@ -480,27 +589,7 @@ impl ChunkEncoder { chunk.z * 16 + i32::from(e.packed_xz as u8 & 15), ) }); - LevelChunkWithLight { - x: chunk.x, - z: chunk.z, - chunk: ChunkData { - heightmaps: self - .tables - .as_ref() - .map(|t| self.heightmaps(chunk, t)) - .unwrap_or_default(), - buffer, - block_entities: entity_infos, - }, - light: LightData { - sky_mask: Vec::new(), - block_mask: Vec::new(), - empty_sky_mask: Vec::new(), - empty_block_mask: Vec::new(), - sky: Vec::new(), - block: Vec::new(), - }, - } + (wires, entity_infos) } /// ClientboundLightUpdatePacketData: the light layers of the sections @@ -509,23 +598,20 @@ impl ChunkEncoder { /// the cache while it is unchanged (uniform light is quicker to fill than /// to keep). fn light_data(&self, chunk: &Chunk, around: u64) -> LightData { - let mut data = light_data_with(&chunk.sections[self.sections.clone()], around, |s| { - if matches!(s.light, Light::Uniform(_)) { - return Arc::new(Layers::of(&s.light)); + light_data_of(&self.light_sections(chunk, around), self.sky) + } + + fn light_sections(&self, chunk: &Chunk, around: u64) -> Vec<(usize, SectionLight)> { + light_sections(&chunk.sections[self.sections.clone()], around, |s| { + if let Light::Uniform(v) = s.light { + return SectionLight::Uniform(v); } - self.cached(s, |e| e.light.clone()).unwrap_or_else(|| { + SectionLight::Layers(self.cached(s, |e| e.light.clone()).unwrap_or_else(|| { let layers = Arc::new(Layers::of(&s.light)); self.cached(s, |e| e.light = Some(layers.clone())); layers - }) - }); - if !self.sky { - // No sky light storage at all. - data.sky_mask.clear(); - data.empty_sky_mask.clear(); - data.sky.clear(); - } - data + })) + }) } } @@ -601,51 +687,123 @@ pub fn entity_tag(entity: &BlockEntity) -> Option { /// layer is sent, or marked empty when all dark; the others are left out. #[cfg(test)] fn light_data(sections: &[Arc
], around: u64) -> LightData { - light_data_with(sections, around, |s| Arc::new(Layers::of(&s.light))) + let lights = light_sections(sections, around, |s| { + SectionLight::Layers(Arc::new(Layers::of(&s.light))) + }); + light_data_of(&lights, true) } -/// The light layers, `section` giving a resident section's. -fn light_data_with( +/// A light section's two DataLayers: a resident section's from the cache, +/// or one value everywhere, which is quicker to write than to keep. +enum SectionLight { + Layers(Arc), + /// Sky light in the high nibble, block light in the low one. + Uniform(u8), +} +impl SectionLight { + /// Whether the sky and the block layer hold any light. + fn any(&self) -> (bool, bool) { + match self { + Self::Layers(l) => (l.sky_any, l.block_any), + Self::Uniform(v) => (v >> 4 != 0, v & 15 != 0), + } + } + /// Append the sky or the block layer's 2048 bytes. + fn put(&self, sky: bool, out: &mut Vec) { + match self { + Self::Layers(l) => out.extend_from_slice(if sky { &l.sky } else { &l.block }), + Self::Uniform(v) => { + let n = if sky { v >> 4 } else { v & 15 }; + out.resize(out.len() + 2048, n | n << 4); + } + } + } +} + +/// The existing light sections, by index from below the world, with their +/// layers (`section` giving a section of the world's). +fn light_sections( sections: &[Arc
], around: u64, - section: impl Fn(&Arc
) -> Arc, -) -> LightData { + section: impl Fn(&Arc
) -> SectionLight, +) -> Vec<(usize, SectionLight)> { let n = sections.len(); - let mut data = LightData { - sky_mask: Vec::new(), - block_mask: Vec::new(), - empty_sky_mask: Vec::new(), - empty_block_mask: Vec::new(), - sky: Vec::new(), - block: Vec::new(), - }; // Light section b holds chunk section b - 1. let exists = |b: usize| (b.saturating_sub(2)..=b.min(n - 1)).any(|s| s + 2 >= b && around >> s & 1 != 0); - for b in 0..n + 2 { - if !exists(b) { - continue; + (0..n + 2) + .filter(|&b| exists(b)) + .map(|b| { + let light = match b { + // Below the world nothing is lit; above it the sky is full. + 0 => SectionLight::Uniform(0), + _ if b == n + 1 => SectionLight::Uniform(0xF0), + _ => section(§ions[b - 1]), + }; + (b, light) + }) + .collect() +} + +/// The four masks of ClientboundLightUpdatePacketData (sky, block, empty +/// sky, empty block); a level without sky light has no sky storage at all. +fn light_masks(lights: &[(usize, SectionLight)], sky: bool) -> [Vec; 4] { + let mut masks: [Vec; 4] = Default::default(); + for (b, light) in lights { + let (sky_any, block_any) = light.any(); + if sky { + set_bit(&mut masks[if sky_any { 0 } else { 2 }], *b); } - let layers = match b { - // Below the world nothing is lit; above it the sky is full. - 0 => Arc::new(Layers::of(&Light::Uniform(0))), - _ if b == n + 1 => Arc::new(Layers::of(&Light::Uniform(0xF0))), - _ => section(§ions[b - 1]), - }; - if layers.sky_any { - set_bit(&mut data.sky_mask, b); - data.sky.push(layers.sky.clone()); - } else { - set_bit(&mut data.empty_sky_mask, b); - } - if layers.block_any { - set_bit(&mut data.block_mask, b); - data.block.push(layers.block.clone()); - } else { - set_bit(&mut data.empty_block_mask, b); + set_bit(&mut masks[if block_any { 1 } else { 3 }], *b); + } + masks +} + +/// The layers sent of one kind: those with any light. +fn sent_layers( + lights: &[(usize, SectionLight)], + sky: bool, +) -> impl Iterator + Clone { + lights.iter().map(|(_, l)| l).filter(move |l| { + let (sky_any, block_any) = l.any(); + if sky { sky_any } else { block_any } + }) +} + +fn light_data_of(lights: &[(usize, SectionLight)], sky: bool) -> LightData { + let [sky_mask, block_mask, empty_sky_mask, empty_block_mask] = light_masks(lights, sky); + let layers = |kind: bool| -> Vec> { + sent_layers(lights, kind) + .map(|l| { + let mut layer = Vec::with_capacity(2048); + l.put(kind, &mut layer); + layer + }) + .collect() + }; + LightData { + sky_mask, + block_mask, + empty_sky_mask, + empty_block_mask, + sky: if sky { layers(true) } else { Vec::new() }, + block: layers(false), + } +} + +/// LightData.write, from the layers themselves. +fn write_light(lights: &[(usize, SectionLight)], sky: bool, w: &mut Writer) { + for mask in light_masks(lights, sky) { + BitSet::write(&mask, w); + } + for kind in [true, false] { + let layers = sent_layers(lights, kind).filter(|_| sky || !kind); + w.varint(layers.clone().count() as i32); + for l in layers { + w.varint(2048); + l.put(kind, &mut w.data); } } - data } #[cfg(test)] @@ -669,6 +827,73 @@ mod tests { assert_eq!(block_entity_type("minecraft:stone"), None); } + #[test] + fn block_entities_come_from_the_cached_section_in_scan_order() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:chest": {"protocol_id": 1}, + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:chest", + "minecraft:oak_sign", + ] + .map(|n| (Arc::::from(n), false)); + let encoder = ChunkEncoder::new(states, &builtin, &[], &[]); + let mut chunk = Chunk::empty(2, -3); + for (x, y, z, state) in [(15, 3, 0, 2), (0, 3, 15, 3), (4, 3, 4, 1), (7, 40, 2, 2)] { + chunk.set(x, MIN_Y + y, z, state); + } + // Every block of a section looked at, as the scan did before the cache. + let scan = |chunk: &Chunk| { + let mut found = Vec::new(); + for (i, s) in chunk.sections.iter().enumerate() { + for y in 0..16 { + for z in 0..16 { + for x in 0..16 { + let state = s.get(crate::chunk::index(x, y, z)); + if let Some(kind) = encoder.entity_type(state) { + found.push((x, MIN_Y + i as i32 * 16 + y, z, kind)); + } + } + } + } + } + // Then the order the packet gives them, as encode_blocks does. + java_hash_order(&mut found, |e| { + (chunk.x * 16 + e.0, e.1, chunk.z * 16 + e.2) + }); + found + }; + let sent = |chunk: &Chunk| { + let packet = encoder.encode(chunk, &HashMap::new()); + let infos = packet.chunk.block_entities; + infos + .iter() + .map(|e| { + let xz = e.packed_xz as u8; + ( + i32::from(xz >> 4), + i32::from(e.y), + i32::from(xz & 15), + e.kind, + ) + }) + .collect::>() + }; + let expected = scan(&chunk); + assert_eq!(expected.len(), 3); + assert_eq!(sent(&chunk), expected); + // From the cache the second time, and after an edit. + assert_eq!(sent(&chunk), expected); + chunk.set(15, MIN_Y + 3, 0, 0); + chunk.set(9, MIN_Y + 3, 9, 3); + assert_eq!(sent(&chunk), scan(&chunk)); + } + fn encoder() -> ChunkEncoder { let states = ["minecraft:air", "minecraft:stone", "minecraft:water"] .map(|n| (Arc::::from(n), n.ends_with("water"))); @@ -758,6 +983,73 @@ mod tests { assert!(horizon_protocol::buf::bit(&data.empty_block_mask, 5)); } + #[test] + fn the_body_is_the_packet_encoded() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:chest": {"protocol_id": 1}, + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:chest", + "minecraft:oak_sign", + ] + .map(|n| (Arc::::from(n), false)); + let mut encoder = ChunkEncoder::new(states, &builtin, &[], &[]); + let mut chunk = Chunk::empty(-7, 12); + // Every kind of light section: uniform dark, uniform lit, sky and + // block light varying, none at all. + let mut light = Box::new([0u8; 4096]); + for (i, v) in light.iter_mut().enumerate() { + *v = (i * 53 % 256) as u8; + } + Arc::make_mut(&mut chunk.sections[4]).light = Light::Full(light); + Arc::make_mut(&mut chunk.sections[5]).light = Light::Uniform(0x07); + Arc::make_mut(&mut chunk.sections[6]).light = Light::Uniform(0); + Arc::make_mut(&mut chunk.sections[7]).light = Light::Full(Box::new([0x30; 4096])); + for (x, y, z, state) in [ + (3, 70, 9, 1), + (5, 70, 5, 2), + (0, -60, 15, 2), + (15, 300, 0, 1), + (8, 64, 1, 3), + ] { + chunk.set(x, y, z, state); + } + // A sign's update tag goes with the column. + let mut entities = HashMap::new(); + entities.insert( + (-7 * 16 + 8, 64, 12 * 16 + 1), + BlockEntity::Sign(crate::signs::SignData::default()), + ); + let packet = |encoder: &ChunkEncoder, around: u64| { + let mut packet = encoder.encode_blocks(&chunk, &entities); + packet.light = encoder.light_data(&chunk, around); + horizon_protocol::packets::play::Clientbound::LevelChunkWithLight(packet).encode() + }; + let sent = encoder + .encode_blocks(&chunk, &entities) + .chunk + .block_entities; + assert_eq!(sent.len(), 3); + assert!(sent.iter().any(|e| e.tag != Tag::End)); + for around in [0, 1, 0b1010_0000, 1 << 23, u64::MAX] { + assert_eq!( + encoder.body(&chunk, &entities, around), + packet(&encoder, around), + "around {around:#b}" + ); + } + encoder.set_dimension(0, 256, false); + assert_eq!( + encoder.body(&chunk, &entities, u64::MAX), + packet(&encoder, u64::MAX) + ); + } + #[test] fn a_nether_column_sends_its_sixteen_sections_without_sky_light() { let chunk = Chunk::empty(0, 0); diff --git a/crates/horizon-client/src/lan/conn.rs b/crates/horizon-client/src/lan/conn.rs index 77faa7e6f..5c448d8ab 100644 --- a/crates/horizon-client/src/lan/conn.rs +++ b/crates/horizon-client/src/lan/conn.rs @@ -150,6 +150,8 @@ pub struct PlayerSender { pub tx: Sender, pub pending: Arc, held: Arc>>>, + /// What [`flush_all`] gave the post thread and it hasn't passed on yet. + posted: Arc, } impl PlayerSender { pub fn new(tx: Sender, pending: Arc) -> Self { @@ -157,6 +159,7 @@ impl PlayerSender { tx, pending, held: Arc::default(), + posted: Arc::default(), } } fn held(&self) -> std::sync::MutexGuard<'_, Vec>> { @@ -168,21 +171,91 @@ impl PlayerSender { self.held().push(body); } else { self.flush(); - let _ = self.tx.send(Out::Packet(body)); + self.deliver(Out::Packet(body)); } } /// Hand the held packets to the writer thread. pub fn flush(&self) { let held = std::mem::take(&mut *self.held()); if !held.is_empty() { - let _ = self.tx.send(Out::Packets(held)); + self.deliver(Out::Packets(held)); } } /// Send a play disconnect with this reason after what was sent before. pub fn disconnect(&self, reason: horizon_world::nbt::Tag) { self.flush(); - let _ = self.tx.send(Out::Disconnect(reason)); + self.deliver(Out::Disconnect(reason)); } + /// To the writer thread, after anything still with the post thread. + fn deliver(&self, out: Out) { + if self.posted.load(Ordering::Acquire) == 0 { + let _ = self.tx.send(out); + } else { + post(vec![self.posting(out)]); + } + } + fn posting(&self, out: Out) -> Posted { + self.posted.fetch_add(1, Ordering::AcqRel); + Posted { + tx: self.tx.clone(), + out, + posted: self.posted.clone(), + } + } +} + +/// Hand every player's held packets to their writer threads. Waking a writer +/// costs a system call, and on a busy machine often the rest of the core's +/// time slice; one thread of its own wakes them, so the game thread wakes one +/// thread per tick, not one per player. Each player's packets keep their +/// order, also with what is sent to it next. +pub fn flush_all<'a>(senders: impl IntoIterator) { + let batch: Vec = senders + .into_iter() + .filter_map(|s| { + let held = std::mem::take(&mut *s.held()); + (!held.is_empty()).then(|| s.posting(Out::Packets(held))) + }) + .collect(); + if !batch.is_empty() { + post(batch); + } +} + +/// Packets on their way through the post thread. +struct Posted { + tx: Sender, + out: Out, + posted: Arc, +} +impl Posted { + fn hand_over(self) { + let _ = self.tx.send(self.out); + self.posted.fetch_sub(1, Ordering::AcqRel); + } +} + +/// Give a batch to the post thread, started the first time; without one +/// (the thread could not start) the batch is handed over here. +fn post(batch: Vec) { + static POST: std::sync::OnceLock>>> = std::sync::OnceLock::new(); + let post = POST.get_or_init(|| { + let (tx, rx) = channel::>(); + std::thread::Builder::new() + .name("horizon-lan-post".to_owned()) + .spawn(move || { + for batch in rx { + batch.into_iter().for_each(Posted::hand_over); + } + }) + .ok() + .map(|_| tx) + }); + let unsent = match post { + Some(tx) => tx.send(batch).err().map(|e| e.0), + None => Some(batch), + }; + unsent.into_iter().flatten().for_each(Posted::hand_over); } /// LegacyQueryHandler: the pre-1.7 server list ping. What the first read @@ -748,6 +821,82 @@ fn read_loop( } } +/// Packet bodies at least this large are compressed once for every +/// connection: chunk columns, mostly, which every player near them receives. +const SHARED_FRAME_MIN: usize = 8 << 10; +/// The compressed frames kept, in bytes; the oldest go first. +const SHARED_FRAME_BYTES: usize = 32 << 20; + +/// Compressed frame contents by the body they were made from: its length, +/// two independently keyed 64-bit hashes of it, and the threshold. +struct SharedFrames { + hashers: (std::hash::RandomState, std::hash::RandomState), + frames: Mutex, + /// [`SHARED_FRAME_BYTES`]. + limit: usize, +} +type FrameKey = (usize, u64, u64, usize); +#[derive(Default)] +struct FrameCache { + frames: crate::fast_hash::FxHashMap>, + order: std::collections::VecDeque, + bytes: usize, +} +impl SharedFrames { + fn get() -> &'static Self { + static FRAMES: std::sync::OnceLock = std::sync::OnceLock::new(); + FRAMES.get_or_init(|| Self::new(SHARED_FRAME_BYTES)) + } + fn new(limit: usize) -> Self { + Self { + hashers: Default::default(), + frames: Mutex::default(), + limit, + } + } + /// `frame::contents(body, Some(threshold))`, compressed only when no + /// connection has sent the same body lately. + fn contents(&self, body: &[u8], threshold: usize) -> horizon_protocol::Result> { + use std::hash::BuildHasher; + let key = ( + body.len(), + self.hashers.0.hash_one(body), + self.hashers.1.hash_one(body), + threshold, + ); + let cache = || self.frames.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(contents) = cache().frames.get(&key) { + return Ok(contents.clone()); + } + let contents: Arc<[u8]> = horizon_protocol::frame::contents(body, Some(threshold))?.into(); + let mut cache = cache(); + if cache.frames.insert(key, contents.clone()).is_none() { + cache.order.push_back(key); + cache.bytes += contents.len(); + while cache.bytes > self.limit + && let Some(old) = cache.order.pop_front() + { + if let Some(c) = cache.frames.remove(&old) { + cache.bytes -= c.len(); + } + } + } + Ok(contents) + } +} + +/// Send one packet body: a large one compressed through [`SharedFrames`], +/// so a chunk column sent to fifty players is compressed once, not fifty +/// times. The bytes on the wire are the same. +fn send_body(writer: &mut ConnWriter, body: &[u8]) -> horizon_protocol::Result<()> { + match writer.threshold { + Some(t) if body.len() >= t.max(SHARED_FRAME_MIN) => { + writer.send_contents(&SharedFrames::get().contents(body, t)?) + } + _ => writer.send(body), + } +} + fn write_loop( mut writer: ConnWriter, rx: Receiver, @@ -761,7 +910,7 @@ fn write_loop( loop { let mut write = |body: Vec| { pending.fetch_sub(body.len(), Ordering::Relaxed); - writer.send(&body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING + send_body(&mut writer, &body).is_ok() && pending.load(Ordering::Relaxed) <= MAX_PENDING }; match rx.recv_timeout(Duration::from_millis(200)) { Ok(Out::Packet(body)) => { @@ -819,15 +968,90 @@ fn write_loop( mod tests { use super::*; + fn unpack(out: Out) -> Vec> { + match out { + Out::Packet(body) => vec![body], + Out::Packets(bodies) => bodies, + Out::Disconnect(_) => vec![b"disconnect".to_vec()], + Out::Close => vec![b"close".to_vec()], + } + } + fn bodies(rx: &Receiver) -> Vec>> { - rx.try_iter() - .map(|out| match out { - Out::Packet(body) => vec![body], - Out::Packets(bodies) => bodies, - Out::Disconnect(_) => vec![b"disconnect".to_vec()], - Out::Close => vec![b"close".to_vec()], - }) - .collect() + rx.try_iter().map(unpack).collect() + } + + #[test] + fn packets_sent_after_a_posted_tick_follow_it() { + let (tx, rx) = channel(); + let (tx2, rx2) = channel(); + let sender = PlayerSender::new(tx, Arc::default()); + let other = PlayerSender::new(tx2, Arc::default()); + for round in 0..50u8 { + let holding = Holding::start(); + sender.send(vec![round, 1]); + sender.send(vec![round, 2]); + other.send(vec![round]); + drop(holding); + flush_all([&sender, &other]); + // Straight after the tick, while the post thread may still hold it. + sender.send(vec![round, 3]); + let next = || unpack(rx.recv_timeout(Duration::from_secs(10)).unwrap()); + assert_eq!(next(), [vec![round, 1], vec![round, 2]]); + assert_eq!(next(), [vec![round, 3]]); + let got = unpack(rx2.recv_timeout(Duration::from_secs(10)).unwrap()); + assert_eq!(got, [vec![round]]); + } + let holding = Holding::start(); + sender.send(vec![9]); + drop(holding); + flush_all([&sender]); + sender.disconnect(horizon_world::nbt::Tag::Byte(0)); + let next = || unpack(rx.recv_timeout(Duration::from_secs(10)).unwrap()); + assert_eq!(next(), [vec![9]]); + assert_eq!(next(), [b"disconnect".to_vec()]); + // Nothing sent twice, nothing left with the post thread. + assert!(rx.try_recv().is_err()); + let deadline = Instant::now() + Duration::from_secs(10); + while sender.posted.load(Ordering::Acquire) != 0 { + assert!(Instant::now() < deadline); + std::thread::yield_now(); + } + } + + #[test] + fn shared_frames_are_the_frames_compressed_here() { + use horizon_protocol::frame; + let frames = SharedFrames::new(usize::MAX); + let a: Vec = (0..40_000u32).map(|i| (i * 7 % 13) as u8).collect(); + let mut b = a.clone(); + b[20_000] ^= 1; + for (body, threshold) in [(&a, 256), (&b, 256), (&a, 256), (&a, 64), (&b, 256)] { + let shared = frames.contents(body, threshold).unwrap(); + assert_eq!(*shared, *frame::contents(body, Some(threshold)).unwrap()); + } + // One frame per body and threshold. + assert_eq!(frames.frames.lock().unwrap().frames.len(), 3); + } + + #[test] + fn shared_frames_keep_the_newest_within_their_limit() { + let first = SharedFrames::new(0) + .contents(&[1; 9000], 256) + .unwrap() + .len(); + let frames = SharedFrames::new(first * 2); + for n in 0..5u8 { + frames.contents(&[n; 9000], 256).unwrap(); + } + let cache = frames.frames.lock().unwrap(); + assert!((1..=2).contains(&cache.frames.len())); + assert_eq!(cache.order.len(), cache.frames.len()); + assert_eq!( + cache.bytes, + cache.frames.values().map(|c| c.len()).sum::() + ); + assert!(cache.bytes <= first * 2); } #[test] diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 0fa47510a..3ecd58b80 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -25,7 +25,7 @@ impl Hub { for g in self .guests .iter() - .filter(|g| g.placed && Some(g.conn) != except) + .filter(|g| self.here(g) && Some(g.conn) != except) { let d: f64 = (0..3).map(|k| (g.position[k] - at[k]).powi(2)).sum(); if d <= range * range { @@ -79,11 +79,11 @@ impl Hub { } /// ClientboundBlockEventPacket (`PlayerList.broadcast` within 64 blocks). - pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u16) { + pub fn block_event(&self, pos: [i32; 3], b0: i32, b1: i32, state: u32) { let block = self .encoder .block_ids - .get(usize::from(state)) + .get(state as usize) .copied() .unwrap_or(0); let at = [f64::from(pos[0]), f64::from(pos[1]), f64::from(pos[2])]; @@ -464,7 +464,7 @@ impl Hub { let Some(menu) = self.guests[i] .menu .as_ref() - .filter(|_| self.guests[i].placed) + .filter(|_| self.here(&self.guests[i])) else { continue; }; diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 3b926b372..36e153c02 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -11,7 +11,7 @@ use horizon_protocol::{ packets::play::{ self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment, - VecDelta, + SetPassengers, VecDelta, }, }; @@ -35,6 +35,30 @@ pub struct EntityState { /// EquipmentSlot ordinals (0 main hand, 1 off hand, 2 feet, 3 legs, /// 4 chest, 5 head, 6 body, 7 saddle) and their stacks. pub equipment: Vec<(u8, Option)>, + /// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks + /// touching a block): moves are sent as full position syncs. + pub precise: bool, +} + +/// `AbstractArrow`: every update sends its position and rotation. +fn is_arrow(kind: &str) -> bool { + matches!( + kind, + "minecraft:arrow" | "minecraft:spectral_arrow" | "minecraft:trident" + ) +} + +/// `AbstractHurtingProjectile.accelerationPower` (0.1, none for wind +/// charges), sent with each velocity update. +fn acceleration_power(kind: &str) -> Option { + match kind { + "minecraft:fireball" + | "minecraft:small_fireball" + | "minecraft:dragon_fireball" + | "minecraft:wither_skull" => Some(0.1), + "minecraft:wind_charge" | "minecraft:breeze_wind_charge" => Some(0.0), + _ => None, + } } /// What a client was last told about one entity (ServerEntity's fields). @@ -54,11 +78,45 @@ struct Sent { /// The type's update interval (0: never) and whether velocity is tracked. interval: u32, track_deltas: bool, + /// lastPassengers, and wasRiding: a passenger's position isn't synced, + /// and the first update after it dismounts is a full position sync. + passengers: Vec, + was_riding: bool, +} + +/// Who rides what this tick (`Entity.getPassengers`, `isPassenger`). +#[derive(Default)] +pub struct Riding { + /// Each vehicle's passengers, in order. + pub passengers: crate::fast_hash::FxHashMap>, + /// Each passenger's vehicle. + pub vehicle: crate::fast_hash::FxHashMap, +} + +impl Riding { + pub fn clear(&mut self) { + self.passengers.clear(); + self.vehicle.clear(); + } + /// `passenger` rides `vehicle`, after the ones already riding it. + pub fn add(&mut self, vehicle: i32, passenger: i32) { + self.passengers.entry(vehicle).or_default().push(passenger); + self.vehicle.insert(passenger, vehicle); + } + pub fn passengers(&self, id: i32) -> &[i32] { + self.passengers.get(&id).map_or(&[], Vec::as_slice) + } + fn set_passengers(&self, vehicle: i32) -> play::Clientbound { + play::Clientbound::SetPassengers(SetPassengers { + vehicle, + passengers: self.passengers(vehicle).to_vec(), + }) + } } #[derive(Default)] pub struct Tracker { - sent: std::collections::HashMap, + sent: crate::fast_hash::FxHashMap, } /// VecDeltaCodec.encode. @@ -66,11 +124,11 @@ fn encode(v: f64) -> i64 { (v * 4096.0).round() as i64 } -/// The horizontal range within which a client sees an entity of `kind` -/// (TrackedEntity.updatePlayer: the type's range, capped by the view distance). -pub fn visible_range(kind: &str, view_distance: i32) -> f64 { - let chunks = i32::from(tracking::settings(kind).0); - f64::from(chunks.min(view_distance) * 16) +/// The type's tracking range in chunks: a client sees an entity of `kind` +/// within it, capped by the view distance, horizontally +/// (TrackedEntity.updatePlayer). +pub fn tracking_chunks(kind: &str) -> i32 { + i32::from(tracking::settings(kind).0) } impl Tracker { @@ -94,7 +152,12 @@ impl Tracker { } /// The packets that introduce an entity (ServerEntity.sendPairingData). - pub fn spawn(&mut self, e: &EntityState, entity_type: i32) -> Vec { + pub fn spawn( + &mut self, + e: &EntityState, + entity_type: i32, + riding: &Riding, + ) -> Vec { let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); let head = pack_degrees(e.head_yaw); let (_, interval, track_deltas) = tracking::settings(&e.kind); @@ -121,6 +184,13 @@ impl Tracker { slots: e.equipment.clone(), })); } + let passengers = riding.passengers(e.id).to_vec(); + if !passengers.is_empty() { + out.push(riding.set_passengers(e.id)); + } + if let Some(&vehicle) = riding.vehicle.get(&e.id) { + out.push(riding.set_passengers(vehicle)); + } self.sent.insert( e.id, Sent { @@ -135,6 +205,8 @@ impl Tracker { teleport_delay: 0, interval, track_deltas, + passengers, + was_riding: false, }, ); out @@ -144,20 +216,48 @@ impl Tracker { /// rotation every update interval (positions at least every 60 ticks, a /// full position sync every 400 or when the entity lands or leaves the /// ground), velocity for types that track it, changed data at once. - pub fn update(&mut self, e: &EntityState) -> Vec { + pub fn update(&mut self, e: &EntityState, riding: &Riding) -> Vec { let Some(s) = self.sent.get_mut(&e.id) else { return Vec::new(); }; let mut out = Vec::new(); + let passengers = riding.passengers(e.id); + if passengers != s.passengers.as_slice() { + out.push(riding.set_passengers(e.id)); + s.passengers = passengers.to_vec(); + } let dirty = e.meta != s.meta; let due = s.interval != 0 && s.tick.is_multiple_of(s.interval); if due || dirty { let rotation = (pack_degrees(e.pitch), pack_degrees(e.yaw)); let turned = |a: i8, b: i8| (i32::from(a) - i32::from(b)).abs() >= 1; - let rotate = turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0); + let arrow = is_arrow(&e.kind); + let rotate = + arrow || turned(rotation.1, s.rotation.1) || turned(rotation.0, s.rotation.0); + if riding.vehicle.contains_key(&e.id) { + // A passenger: its rotation alone (its vehicle places it). + if rotate { + out.push(play::Clientbound::MoveEntityRot(MoveEntityRot( + MoveEntity { + id: e.id, + delta: None, + rotation: Some((rotation.1, rotation.0)), + on_ground: e.on_ground, + }, + ))); + s.rotation = rotation; + } + s.base = e.position; + s.was_riding = true; + Self::send_dirty(e, s, dirty, &mut out); + Self::send_head(e, s, &mut out); + s.tick += 1; + Self::send_equipment(e, s, &mut out); + return out; + } s.teleport_delay += 1; let d: f64 = (0..3).map(|k| (e.position[k] - s.base[k]).powi(2)).sum(); - let send_position = d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60); + let send_position = arrow || d >= 7.629_394_5e-6 || s.tick.is_multiple_of(60); let sync = EntityPositionSync { id: e.id, path: PositionPath::Linear(e.position), @@ -166,9 +266,14 @@ impl Tracker { on_ground: e.on_ground, }; // ServerEntity.createMovePacket. - let packet = if s.teleport_delay > 400 || s.was_on_ground != e.on_ground { + let packet = if e.precise + || s.teleport_delay > 400 + || s.was_riding + || s.was_on_ground != e.on_ground + { s.was_on_ground = e.on_ground; s.teleport_delay = 0; + s.was_riding = false; Some(play::Clientbound::EntityPositionSync(sync)) } else if send_position { let delta = [0, 1, 2].map(|k| encode(e.position[k]) - encode(s.base[k])); @@ -206,10 +311,23 @@ impl Tracker { let still = e.velocity.iter().all(|v| *v == 0.0); if diff > 1.0e-7 || diff > 0.0 && still { s.velocity = e.velocity; - out.push(play::Clientbound::SetEntityMotion(SetEntityMotion { + let motion = play::Clientbound::SetEntityMotion(SetEntityMotion { id: e.id, velocity: e.velocity, - })); + }); + match acceleration_power(&e.kind) { + // A bundle: the motion and the projectile's power. + Some(power) => out.extend([ + play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty), + motion, + play::Clientbound::ProjectilePower(play::ProjectilePower { + id: e.id, + power, + }), + play::Clientbound::BundleDelimiter(horizon_protocol::packets::Empty), + ]), + None => out.push(motion), + } } } if let Some(packet) = packet { @@ -227,33 +345,47 @@ impl Tracker { s.rotation = rotation; } } - // ServerEntity.sendDirtyEntityData. - if dirty { - let changed: Vec<_> = e - .meta - .iter() - .filter(|m| !s.meta.contains(m)) - .cloned() - .collect(); - if !changed.is_empty() { - out.push(play::Clientbound::SetEntityData(SetEntityData { - id: e.id, - values: changed, - })); - } - s.meta = e.meta.clone(); - } - let head = pack_degrees(e.head_yaw); - if turned(head, s.head) { - out.push(play::Clientbound::RotateHead(RotateHead { - id: e.id, - head_yaw: head, - })); - s.head = head; - } + Self::send_dirty(e, s, dirty, &mut out); + Self::send_head(e, s, &mut out); } s.tick += 1; - // LivingEntity.detectEquipmentUpdates: changed slots every tick. + Self::send_equipment(e, s, &mut out); + out + } + + /// ServerEntity.sendDirtyEntityData. + fn send_dirty(e: &EntityState, s: &mut Sent, dirty: bool, out: &mut Vec) { + if !dirty { + return; + } + let changed: Vec<_> = e + .meta + .iter() + .filter(|m| !s.meta.contains(m)) + .cloned() + .collect(); + if !changed.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: changed, + })); + } + s.meta = e.meta.clone(); + } + + fn send_head(e: &EntityState, s: &mut Sent, out: &mut Vec) { + let head = pack_degrees(e.head_yaw); + if (i32::from(head) - i32::from(s.head)).abs() >= 1 { + out.push(play::Clientbound::RotateHead(RotateHead { + id: e.id, + head_yaw: head, + })); + s.head = head; + } + } + + /// LivingEntity.detectEquipmentUpdates: changed slots every tick. + fn send_equipment(e: &EntityState, s: &mut Sent, out: &mut Vec) { if e.equipment != s.equipment { // Cleared slots are sent as empty stacks. let mut slots: Vec<(u8, Option)> = e @@ -275,7 +407,6 @@ impl Tracker { } s.equipment = e.equipment.clone(); } - out } } @@ -297,44 +428,91 @@ mod tests { data: 0, meta: Vec::new(), equipment: Vec::new(), + precise: false, } } #[test] fn moves_go_out_every_update_interval() { let mut t = Tracker::default(); - let spawn = t.spawn(&state(0.0), 100); + let spawn = t.spawn(&state(0.0), 100, &Riding::default()); assert!(matches!(spawn[0], play::Clientbound::AddEntity(_))); // Tick 0 is due and a multiple of 60: the position goes out unchanged. assert!(matches!( - t.update(&state(0.0))[..], + t.update(&state(0.0), &Riding::default())[..], [play::Clientbound::MoveEntityPos(_)] )); // A zombie updates every third tick. - assert!(t.update(&state(0.5)).is_empty()); - assert!(t.update(&state(0.5)).is_empty()); + assert!(t.update(&state(0.5), &Riding::default()).is_empty()); + assert!(t.update(&state(0.5), &Riding::default()).is_empty()); assert!(matches!( - t.update(&state(0.5))[..], + t.update(&state(0.5), &Riding::default())[..], [play::Clientbound::MoveEntityPos(_)] )); for _ in 0..2 { - t.update(&state(40.0)); + t.update(&state(40.0), &Riding::default()); } - let jump = t.update(&state(40.0)); + let jump = t.update(&state(40.0), &Riding::default()); assert!(matches!(jump[0], play::Clientbound::EntityPositionSync(_))); } + #[test] + fn fireballs_bundle_their_motion_with_their_power() { + let mut t = Tracker::default(); + let mut e = state(0.0); + e.kind = "minecraft:fireball".into(); + e.on_ground = false; + t.spawn(&e, 100, &Riding::default()); + e.velocity = [0.0, 0.0, 0.5]; + let out = t.update(&e, &Riding::default()); + assert!(matches!( + out[..], + [ + play::Clientbound::BundleDelimiter(_), + play::Clientbound::SetEntityMotion(_), + play::Clientbound::ProjectilePower(play::ProjectilePower { power, .. }), + play::Clientbound::BundleDelimiter(_), + play::Clientbound::MoveEntityPos(_), + ] if power == 0.1 + )); + } + + #[test] + fn arrows_send_position_and_rotation_every_update() { + let mut t = Tracker::default(); + let mut e = state(0.0); + e.kind = "minecraft:arrow".into(); + t.spawn(&e, 100, &Riding::default()); + assert!(matches!( + t.update(&e, &Riding::default())[..], + [play::Clientbound::MoveEntityPosRot(_)] + )); + } + + #[test] + fn precise_entities_sync_their_position() { + let mut t = Tracker::default(); + let mut e = state(0.0); + e.kind = "minecraft:tnt".into(); + e.precise = true; + t.spawn(&e, 100, &Riding::default()); + assert!(matches!( + t.update(&e, &Riding::default())[..], + [play::Clientbound::EntityPositionSync(_)] + )); + } + #[test] fn landing_sends_a_position_sync() { let mut t = Tracker::default(); let mut e = state(0.0); - t.spawn(&e, 100); - t.update(&e); + t.spawn(&e, 100, &Riding::default()); + t.update(&e, &Riding::default()); e.on_ground = false; - t.update(&e); - t.update(&e); + t.update(&e, &Riding::default()); + t.update(&e, &Riding::default()); assert!(matches!( - t.update(&e)[..], + t.update(&e, &Riding::default())[..], [play::Clientbound::EntityPositionSync(_)] )); } @@ -343,11 +521,11 @@ mod tests { fn metadata_and_equipment_send_only_the_changes() { let mut t = Tracker::default(); let mut e = state(0.0); - t.spawn(&e, 100); - t.update(&e); + t.spawn(&e, 100, &Riding::default()); + t.update(&e, &Riding::default()); e.meta.push((0, 0, Value::Byte(1))); e.equipment.push((0, Some(Stack::new(5, 1)))); - let out = t.update(&e); + let out = t.update(&e, &Riding::default()); assert!( out.iter() .any(|p| matches!(p, play::Clientbound::SetEntityData(_))) @@ -356,9 +534,9 @@ mod tests { out.iter() .any(|p| matches!(p, play::Clientbound::SetEquipment(_))) ); - assert!(t.update(&e).is_empty()); + assert!(t.update(&e, &Riding::default()).is_empty()); e.equipment.clear(); - let out = t.update(&e); + let out = t.update(&e, &Riding::default()); let Some(play::Clientbound::SetEquipment(eq)) = out.first() else { panic!("expected equipment"); }; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index db426ca21..1a699bc45 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -8,7 +8,7 @@ use horizon_protocol::{ packets::{configuration::ClientInformation, play}, }; use std::{ - collections::{HashSet, VecDeque}, + collections::VecDeque, sync::{Arc, atomic::AtomicI32}, }; @@ -37,6 +37,12 @@ pub struct Guest { pub last_action_tick: u64, /// The next ClientboundPlayerChatPacket.globalIndex for this connection. pub chat_index: i32, + /// Secure chat (ServerGamePacketListenerImpl): the player's message + /// chain, keyed once it sends a chat session; the messages its + /// acknowledgements cover; the signatures its client caches. + pub chain: horizon_protocol::secure_chat::Chain, + pub last_seen: horizon_protocol::secure_chat::LastSeenValidator, + pub signatures: horizon_protocol::secure_chat::SignatureCache, /// The hub tick the player was placed on: chunks go out from the tick /// after next, behind the first doTick's packets, as vanilla's do. pub placed_at: u64, @@ -69,19 +75,43 @@ pub struct Guest { pub fall_flying: bool, pub flying: bool, pub sleeping: bool, + /// The bed (its head) the player sleeps in (`LivingEntity.getSleepingPos`), + /// `Player.sleepCounter`, and the bed last told to the player itself. + pub bed: Option<[i32; 3]>, + pub sleep_timer: u32, + pub sent_bed: Option<[i32; 3]>, + /// Where the player respawns (a bed's spot; `ServerPlayer.respawnConfig`), + /// None for the world spawn. + pub spawn: Option<[f64; 3]>, /// Pending ClientboundPlayerPositionPacket id; movement is ignored until /// the client accepts it (ServerGamePacketListenerImpl.awaitingPositionFromClient). pub awaiting_teleport: Option<(i32, [f64; 3])>, pub teleport_counter: i32, + /// The hub tick the pending teleport was (re)sent on (awaitingTeleportTime). + pub teleport_tick: u64, + /// Where the player was when this tick's packets began (firstGoodX/Y/Z), + /// for the moved-too-quickly check. + pub first_good: [f64; 3], + /// Position moves received in all and by the start of this tick + /// (receivedMovePacketCount, knownMovePacketCount). + pub received_moves: i32, + pub known_moves: i32, + /// A position move arrived since the client's last ClientTickEnd + /// (receivedPositionThisTick): a second one is a protocol error. + pub position_this_tick: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. pub center: Option<(i32, i32)>, - pub sent_chunks: HashSet<(i32, i32)>, + pub sent_chunks: crate::fast_hash::FxHashSet<(i32, i32)>, pub chunk_queue: Vec<(i32, i32)>, + /// PlayerChunkSender: batches sent but not yet acknowledged, how many + /// may be (1 until the client's first acknowledgement, then 10), the + /// rate the client asks for and the chunks the next batch may hold. pub unacknowledged: u32, + pub max_unacknowledged: u32, pub chunks_per_tick: f32, - pub chunk_credit: f32, + pub batch_quota: f32, // Entities. pub tracker: Tracker, // Player state the gameplay code reads and writes. @@ -113,7 +143,8 @@ pub struct Guest { /// What the client believes the inventory menu holds (for change detection). pub menu_sent: Vec>, pub menu_state: i32, - pub sent_health: Option<(f32, i32, f32)>, + /// `lastSentHealth`, `lastSentFood` and `lastFoodSaturationZero`. + pub sent_health: Option<(f32, i32, bool)>, pub sent_xp: Option<(f32, i32, i32)>, /// Where the player last died (Player.lastDeathLocation), sent with the respawn. pub last_death: Option<[i32; 3]>, @@ -131,6 +162,9 @@ pub struct Guest { pub dead: bool, /// The join packets were sent (PlayerList.placeNewPlayer ran). pub placed: bool, + /// The level the player is in (`ServerPlayer.level().dimension()`): the + /// hub's level passes only reach the players in theirs. + pub dimension: String, /// The open block container, if any. pub menu: Option, pub next_window: i32, @@ -160,6 +194,9 @@ impl Guest { address: j.address, last_action_tick: 0, chat_index: 0, + chain: Default::default(), + last_seen: Default::default(), + signatures: Default::default(), placed_at: 0, center_sent: None, left_reason: String::new(), @@ -185,15 +222,25 @@ impl Guest { fall_flying: false, flying: false, sleeping: false, + bed: None, + sleep_timer: 0, + sent_bed: None, + spawn: None, awaiting_teleport: None, teleport_counter: 0, + teleport_tick: 0, + first_good: position, + received_moves: 0, + known_moves: 0, + position_this_tick: false, loaded: false, center: None, - sent_chunks: HashSet::new(), + sent_chunks: Default::default(), chunk_queue: Vec::new(), unacknowledged: 0, + max_unacknowledged: 1, chunks_per_tick: 9.0, - chunk_credit: 0.0, + batch_quota: 0.0, tracker: Tracker::default(), motion: None, inventory: vec![None; 36], @@ -226,6 +273,7 @@ impl Guest { moves_from_ground: false, dead: false, placed: false, + dimension: "minecraft:overworld".into(), menu: None, next_window: 0, drag: None, diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 8fcc41329..faff066ab 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,26 +12,36 @@ use super::{ guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, world::World, }; +use horizon_core::geometry::{Aabb, ShapeOp, Vec3, VoxelShape}; use horizon_protocol::ids::play::clientbound as ids; use horizon_protocol::{ entity_data::{Value, serializer}, packets::play::{self, Clientbound as C, Serverbound as S}, text::{literal, translatable}, }; -use horizon_world::nbt::{JavaString, Tag}; +use horizon_world::{ + block_collision::BlockCollisionRegistry, + block_collision_scan::BlockCollisionScan, + collision_context::CollisionContext, + nbt::{JavaString, Tag}, +}; use std::sync::{Arc, atomic::Ordering}; /// GameEvent types (ClientboundGameEventPacket). +pub mod chat; + pub mod game_event { pub const START_RAINING: u8 = 1; pub const STOP_RAINING: u8 = 2; pub const CHANGE_GAME_MODE: u8 = 3; pub const RAIN_LEVEL: u8 = 7; pub const THUNDER_LEVEL: u8 = 8; + pub const GUARDIAN_ELDER_EFFECT: u8 = 10; pub const LEVEL_CHUNKS_LOAD_START: u8 = 13; } @@ -88,6 +98,9 @@ pub struct TickCtx<'a> { /// TickRateManager: the tick rate and whether the game is frozen. pub tick_rate: f32, pub tick_frozen: bool, + /// Block collisions, for ServerGamePacketListenerImpl's moved-wrongly + /// check (none: moves are not checked against blocks). + pub collision: Option<&'a BlockCollisionRegistry<'a>>, } /// What the gameplay code has to do for a guest. @@ -97,8 +110,16 @@ pub enum HostEvent { /// A guest left (state to save, entities to drop). Left(Box), Packet(u32, Box), - /// A chat line to show on the host (already broadcast to the guests). - Chat(String), + /// A chat line to show on the host (already broadcast to the guests); + /// a dedicated server logs it, `[Not Secure]` unless signed and fresh. + Chat { + line: String, + secure: bool, + }, + /// A server log warning (ServerGamePacketListenerImpl's LOGGER.warn). + Warn(String), + /// A server log error (LOGGER.error). + Error(String), } pub struct Hub { @@ -108,10 +129,18 @@ pub struct Hub { pub guests: Vec, pub(super) sync: Arc, pub ticks: u64, + /// The `player_movement_check` and `elytra_movement_check` game rules, + /// set by the game before each tick. + pub movement_checks: (bool, bool), + /// Who rides what, set by the game before each tick. + pub riding: super::entity::Riding, last_clock: i64, last_rate: f32, ticking: (f32, bool), weather: (bool, f32, f32), + /// The clock and weather last sent in the levels not in place, by + /// dimension (`set_dimension` swaps them with the fields above). + level_sync: std::collections::HashMap, /// Operators and their permission levels (dedicated servers). pub ops: std::collections::HashMap, chat_type: i32, @@ -180,6 +209,24 @@ fn tracked(cx: i32, cz: i32, r: i32, x: i32, z: i32) -> bool { dx * dx + dz * dz < i64::from(r) * i64::from(r) } +/// What a level's players were last told of its clock and weather. +#[derive(Clone, Copy)] +struct LevelSync { + last_clock: i64, + last_rate: f32, + weather: (bool, f32, f32), +} + +impl Default for LevelSync { + fn default() -> Self { + Self { + last_clock: i64::MIN, + last_rate: 0.0, + weather: (false, 0.0, 0.0), + } + } +} + impl Hub { pub fn new(lan: Lan, sync: Arc, encoder: ChunkEncoder, config: HubConfig) -> Self { let chat_type = sync @@ -199,11 +246,14 @@ impl Hub { guests: Vec::new(), sync, ticks: 0, + movement_checks: (true, true), + riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, ticking: (20.0, false), ops: Default::default(), weather: (false, 0.0, 0.0), + level_sync: Default::default(), chat_type, dimension_type, clock_ids, @@ -257,6 +307,34 @@ impl Hub { g.sender.send(body.clone()); } } + /// PlayerList.setViewDistance: every player is told the new radius, + /// and each one's chunks follow it, up to what they asked for + /// (ChunkMap.getPlayerViewDistance). + pub fn set_view_distance(&mut self, distance: i32) { + self.config.view_distance = distance; + self.broadcast(&C::SetChunkCacheRadius(play::Distance { distance })); + for g in &mut self.guests { + g.view_distance = i32::from(g.info.view_distance).clamp(2, distance); + g.center = None; + } + } + /// PlayerList.setSimulationDistance. + pub fn set_simulation_distance(&mut self, distance: i32) { + self.config.simulation_distance = distance; + self.broadcast(&C::SetSimulationDistance(play::Distance { distance })); + } + /// Whether a guest is placed in the level in place (`config.dimension`). + pub fn here(&self, g: &Guest) -> bool { + g.placed && g.dimension == self.config.dimension + } + /// `PlayerList.broadcastAll(packet, dimension)`: the players in the + /// level in place. + pub fn broadcast_level(&self, packet: &C) { + let body = packet.encode(); + for g in self.guests.iter().filter(|g| self.here(g)) { + g.sender.send(body.clone()); + } + } pub fn broadcast_except(&self, conn: u32, packet: &C) { let body = packet.encode(); for g in self.guests.iter().filter(|g| g.placed && g.conn != conn) { @@ -357,56 +435,23 @@ impl Hub { }, })); } - /// PlayerList.broadcastChatMessage of a guest's unsigned message - /// (PlayerChatMessage.unsigned): a ClientboundPlayerChatPacket to every - /// player, each connection numbering its messages. - pub fn player_chat(&mut self, from: usize, text: &str) { - let (uuid, name) = (self.guests[from].uuid, self.guests[from].name.clone()); - let timestamp = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_millis() as i64); - let bound = play::ChatTypeBound { - chat_type: self.chat_type, - name: display_name(uuid, &name), - target: None, - }; - for g in self.guests.iter_mut().filter(|g| g.placed) { - let packet = C::PlayerChat(play::PlayerChat { - global_index: g.chat_index, - sender: uuid, - index: 0, - signature: None, - content: text.to_owned(), - timestamp, - salt: 0, - last_seen: Vec::new(), - unsigned_content: None, - filter: (0, Vec::new()), - chat_type: bound.clone(), - }); - g.chat_index += 1; - g.send(&packet); - } - } - /// Disconnect a guest with a reason (ServerGamePacketListenerImpl.disconnect). pub fn kick(&mut self, conn: u32, reason: Tag) { - if let Some(g) = self.guest(conn) { + // The log's "lost connection" line gives the reason, as vanilla's. + let text = self.english(&reason); + if let Some(g) = self.guest_mut(conn) { + g.left_reason = text; g.sender.disconnect(reason); } } fn player_info(&self, uuid: u128, name: &str, mode: i32, latency: i32) -> play::PlayerInfo { + let guest = self.guests.iter().find(|g| g.uuid == uuid); play::PlayerInfo { uuid, name: Some(name.to_owned()), - properties: self - .guests - .iter() - .find(|g| g.uuid == uuid) - .map(|g| g.properties.clone()) - .unwrap_or_default(), - chat_session: None, + properties: guest.map(|g| g.properties.clone()).unwrap_or_default(), + chat_session: guest.and_then(|g| g.chain.session()).map(|s| s.data()), game_mode: Some(mode), listed: Some(true), latency: Some(latency), @@ -448,6 +493,7 @@ impl Hub { guest.joined_tick = self.ticks; guest.position = ctx.spawn; guest.previous_position = ctx.spawn; + guest.dimension = self.config.dimension.clone(); self.guests.push(guest); conn } @@ -498,8 +544,9 @@ impl Hub { show_death_screen: true, limited_crafting: false, spawn: self.spawn_info(mode), - online_mode: false, - enforces_secure_chat: false, + // MinecraftServer.usesAuthentication, enforceSecureProfile. + online_mode: self.lan.shared.config.online.is_some(), + enforces_secure_chat: self.enforces_secure_chat(), })); g.send(&C::ChangeDifficulty(play::ChangeDifficulty { difficulty: ctx.difficulty, @@ -727,7 +774,9 @@ impl Hub { /// ServerGamePacketListenerImpl.teleport: move the client and wait for its confirmation. pub fn teleport(&mut self, i: usize, position: Option<[f64; 3]>) { + let ticks = self.ticks; let g = &mut self.guests[i]; + g.teleport_tick = ticks; if let Some(p) = position { g.position = p; g.previous_position = p; @@ -838,6 +887,20 @@ impl Hub { } /// ServerPlayer.initInventoryMenu / sendAllDataToRemote for the inventory menu. + /// ClientboundPlaceGhostRecipePacket: the recipe `id` faded into the + /// guest's menu `container`, whose items were missing. + pub fn send_ghost_recipe(&mut self, conn: u32, container: i32, id: &str) { + let Some(display) = self.sync.advancements.ghost_display(id, &self.sync) else { + return; + }; + self.send_to( + conn, + &C::PlaceGhostRecipe(horizon_protocol::packets::recipes::PlaceGhostRecipe { + container, + display, + }), + ); + } pub fn send_inventory(&mut self, i: usize) { let items: Vec> = (0..46).map(|s| self.guests[i].menu_slot(s)).collect(); let net: Vec<_> = items.iter().map(|s| self.stack(s)).collect(); @@ -857,7 +920,19 @@ impl Hub { // ---- per tick ------------------------------------------------------ + /// A whole tick with one level: the network, the level, then the + /// players' latencies. pub fn tick(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = self.poll(ctx); + events.extend(self.tick_level(ctx)); + self.end_tick(); + events + } + + /// The network since the last tick, once per server tick before any + /// level ticks: joins (into the level in place), leaves, and each guest's + /// packets queued for its own level's pass. + pub fn poll(&mut self, ctx: &mut TickCtx) -> Vec { self.ticks += 1; let mut events = Vec::new(); for event in self.lan.poll() { @@ -893,13 +968,25 @@ impl Hub { } } } + events + } + + /// The level in place's part of the tick (`ServerLevel.tick`'s chunk + /// map and the connections of the players in it): their packets, then + /// the chunks, block changes, containers and entities they see. + pub fn tick_level(&mut self, ctx: &mut TickCtx) -> Vec { + let mut events = Vec::new(); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.process_inbox(i, ctx, &mut events); } } - if !self.guests.iter().any(|g| g.placed) { - if self.guests.is_empty() { + if !self.guests.iter().any(|g| self.here(g)) { + if !self + .guests + .iter() + .any(|g| g.dimension == self.config.dimension) + { let _ = ctx.world.block_log.take(); } return events; @@ -909,7 +996,7 @@ impl Hub { } self.sync_world(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.update_chunks(i, ctx); } } @@ -917,7 +1004,7 @@ impl Hub { // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are // acknowledged after the block changes they made were sent, so a client's predicted // blocks settle on the server's states. - for g in &self.guests { + for g in self.guests.iter().filter(|g| self.here(g)) { let sequence = g.ack_up_to.replace(-1); if sequence >= 0 { g.send(&C::BlockChangedAck(play::BlockChangedAck { sequence })); @@ -926,11 +1013,16 @@ impl Hub { self.sync_containers(ctx.world); self.track_entities(ctx); for i in 0..self.guests.len() { - if self.guests[i].placed { + if self.here(&self.guests[i]) { self.sync_player_state(i); self.sync_effects(i); } } + events + } + + /// After every level: `PlayerList.tick`. + pub fn end_tick(&mut self) { let latencies: Vec<_> = self .guests .iter() @@ -952,12 +1044,13 @@ impl Hub { entries, })); } - events } fn remove_guest(&mut self, i: usize, reason: &str) -> Guest { let mut g = self.guests.remove(i); - g.left_reason = reason.to_owned(); + if g.left_reason.is_empty() { + g.left_reason = reason.to_owned(); + } if std::env::var_os("HORIZON_NET_DEBUG").is_some() { log::info!("[lan] {} left: {reason}", g.name); } @@ -983,7 +1076,7 @@ impl Hub { // MinecraftServer.tickServer: the game time every 20 ticks // (forceGameTimeSynchronization, no clocks). if self.ticks.is_multiple_of(20) { - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: Vec::new(), })); @@ -999,7 +1092,7 @@ impl Hub { .sync .id("minecraft:world_clock", "minecraft:overworld") .unwrap_or(0); - self.broadcast(&C::SetTime(play::SetTime { + self.broadcast_level(&C::SetTime(play::SetTime { game_time: world.game_time, clocks: vec![play::ClockState { clock: overworld, @@ -1018,7 +1111,7 @@ impl Hub { let w = &world.weather; let (raining, rain, thunder) = self.weather; if w.raining != raining { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: if w.raining { game_event::START_RAINING } else { @@ -1028,13 +1121,13 @@ impl Hub { })); } if (w.rain_level.1 - rain).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::RAIN_LEVEL, param: w.rain_level.1, })); } if (w.thunder_level.1 - thunder).abs() > f32::EPSILON { - self.broadcast(&C::GameEvent(play::GameEvent { + self.broadcast_level(&C::GameEvent(play::GameEvent { event: game_event::THUNDER_LEVEL, param: w.thunder_level.1, })); @@ -1082,15 +1175,16 @@ impl Hub { g.chunk_queue .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // Send ready chunks, closest first, in batches. - if g.chunk_queue.is_empty() || g.unacknowledged >= 10 || self.ticks <= g.placed_at + 1 { + // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in + // batches the client's acknowledgements pace. + if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { return; } - g.chunk_credit = (g.chunk_credit + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0) * 2.0); - let budget = g.chunk_credit.floor() as usize; - if budget == 0 { + g.batch_quota = (g.batch_quota + g.chunks_per_tick).min(g.chunks_per_tick.max(1.0)); + if g.batch_quota < 1.0 || g.chunk_queue.is_empty() { return; } + let budget = g.batch_quota.floor() as usize; let mut packets = Vec::new(); let mut taken = Vec::new(); for (idx, key) in g.chunk_queue.iter().enumerate() { @@ -1103,21 +1197,20 @@ impl Hub { if !chunk.lit { continue; } - packets.push(C::LevelChunkWithLight( - self.encoder.encode_in(chunk, ctx.world), - )); + packets.push(self.encoder.body_in(chunk, ctx.world)); taken.push(idx); } if packets.is_empty() { return; } - g.chunk_credit -= packets.len() as f32; + let size = packets.len(); + g.batch_quota -= size as f32; g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); - for p in &packets { - g.send(p); + for body in packets { + g.sender.send(body); } g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { - size: packets.len() as i32, + size: size as i32, })); g.unacknowledged += 1; for idx in taken.into_iter().rev() { @@ -1131,8 +1224,7 @@ impl Hub { let Some(chunk) = world.chunks.get(&(x, z)) else { return; }; - let packet = C::LevelChunkWithLight(self.encoder.encode_in(chunk, world)); - let body = packet.encode(); + let body = self.encoder.body_in(chunk, world); for g in self .guests .iter() @@ -1164,7 +1256,7 @@ impl Hub { for ((sx, sy, sz), positions) in sections { let viewers: Vec = (0..self.guests.len()) .filter(|&i| { - self.guests[i].placed && self.guests[i].sent_chunks.contains(&(sx, sz)) + self.here(&self.guests[i]) && self.guests[i].sent_chunks.contains(&(sx, sz)) }) .collect(); if viewers.is_empty() { @@ -1174,7 +1266,7 @@ impl Hub { let (x, y, z) = positions[0]; C::BlockUpdate(play::BlockUpdate { pos: [x, y, z], - state: i32::from(world.block(x, y, z).0 as u16), + state: world.block(x, y, z).0 as i32, }) } else { C::SectionBlocksUpdate(play::SectionBlocksUpdate { @@ -1203,7 +1295,7 @@ impl Hub { let Some(tag) = super::chunks::entity_tag(entity) else { continue; }; - let state = world.block(x, y, z).0 as u16; + let state = world.block(x, y, z).0; let Some(kind) = self.encoder.entity_type(state) else { continue; }; @@ -1280,6 +1372,7 @@ impl Hub { data: 0, meta, equipment, + precise: false, } } @@ -1329,7 +1422,7 @@ impl Hub { )); } let placed: Vec = (0..self.guests.len()) - .filter(|&i| self.guests[i].placed) + .filter(|&i| self.here(&self.guests[i])) .collect(); let guest_states: Vec<_> = placed .into_iter() @@ -1362,8 +1455,14 @@ impl Hub { all.extend(ctx.entities.iter().cloned()); let by_id: std::collections::HashMap = all.iter().enumerate().map(|(i, e)| (e.id, i)).collect(); + // Each entity type's tracking range, looked up once rather than for + // every player. + let ranges: Vec = all + .iter() + .map(|e| super::entity::tracking_chunks(&e.kind)) + .collect(); for gi in 0..self.guests.len() { - if !self.guests[gi].placed { + if !self.here(&self.guests[gi]) { continue; } let view = self.guests[gi].view_distance; @@ -1371,8 +1470,9 @@ impl Hub { let origin = self.guests[gi].position; // TrackedEntity.updatePlayer: within the type's range (capped by the // view distance) horizontally, in a chunk the client has. - let visible = |g: &Guest, e: &EntityState| { - let range = super::entity::visible_range(&e.kind, view); + let visible = |g: &Guest, ei: usize| { + let e = &all[ei]; + let range = f64::from(ranges[ei].min(view) * 16); let (dx, dz) = (origin[0] - e.position[0], origin[2] - e.position[2]); let chunk = ( (e.position[0].floor() as i32) >> 4, @@ -1384,7 +1484,7 @@ impl Hub { let mut removed = Vec::new(); for id in self.guests[gi].tracker.ids() { match by_id.get(&id) { - Some(&ei) if visible(&self.guests[gi], &all[ei]) => {} + Some(&ei) if visible(&self.guests[gi], ei) => {} _ => removed.push(id), } } @@ -1394,29 +1494,63 @@ impl Hub { } self.guests[gi].send(&C::RemoveEntities(play::RemoveEntities { ids: removed })); } - for e in &all { + for (ei, e) in all.iter().enumerate() { if e.id == me { continue; } if self.guests[gi].tracker.is_tracking(e.id) { - let packets = self.guests[gi].tracker.update(e); + let packets = self.guests[gi].tracker.update(e, &self.riding); self.guests[gi].send_all(&packets); - } else if visible(&self.guests[gi], e) { + } else if visible(&self.guests[gi], ei) { let Some(kind) = self.entity_type(&e.kind) else { continue; }; // Players need their list entry first; guests got it at join. - let packets = self.guests[gi].tracker.spawn(e, kind); + let packets = self.guests[gi].tracker.spawn(e, kind, &self.riding); self.guests[gi].send_all(&packets); } } } } + /// ServerPlayer.stopSleepInBed: the wake-up animation goes to the player + /// and those around, the pose is standing again and the sleep counter + /// starts the wake-up fade (100). + pub fn wake(&mut self, i: usize) { + let g = &mut self.guests[i]; + if g.bed.take().is_none() && !g.sleeping { + return; + } + g.sleeping = false; + g.sleep_timer = 100; + let (id, at) = (g.entity_id, g.position); + // ClientboundAnimatePacket.WAKE_UP. + self.broadcast_near( + at, + 128.0, + &C::Animate(play::Animate { id, action: 0 }), + None, + ); + } + // ---- per-player state ------------------------------------------------ /// ServerPlayer.doTick: health, food, experience and the inventory menu. fn sync_player_state(&mut self, i: usize) { + // LivingEntity.startSleeping / stopSleeping: the pose and the bed go + // to the player too (its client lies down in the bed from them). + let g = &mut self.guests[i]; + if g.bed != g.sent_bed { + g.sent_bed = g.bed; + let pose = if g.bed.is_some() { 2 } else { 0 }; + g.send(&C::SetEntityData(play::SetEntityData { + id: g.entity_id, + values: vec![ + (6, serializer::POSE, Value::Id(pose)), + (14, serializer::OPTIONAL_BLOCK_POS, Value::OptPos(g.bed)), + ], + })); + } // ServerEntity.sendDirtyEntityData on the player's first tick: the // health its creation set is still dirty, and goes to the player too. if self.guests[i].sent_health.is_none() { @@ -1449,17 +1583,15 @@ impl Hub { self.flush_advancements(i, true); } } - let health = { - let g = &self.guests[i]; - (g.health, g.food, g.saturation) - }; - // A dead player's health isn't sent (the death screen shows from the combat kill). - if self.guests[i].sent_health != Some(health) && !self.guests[i].dead { - let g = &mut self.guests[i]; + // Sent when the health or the food level changes, or the saturation + // reaches or leaves zero; a dead player's health of 0 too. + let g = &mut self.guests[i]; + let health = (g.health, g.food, g.saturation == 0.0); + if g.sent_health != Some(health) { g.send(&C::SetHealth(play::SetHealth { - health: health.0, - food: health.1, - saturation: health.2, + health: g.health, + food: g.food, + saturation: g.saturation, })); g.sent_health = Some(health); } @@ -1567,6 +1699,11 @@ impl Hub { } fn process_inbox(&mut self, i: usize, ctx: &mut TickCtx, events: &mut Vec) { + // ServerGamePacketListenerImpl.tickPlayer ran between the last + // tick's packets and these: resetPosition, and the moves it counted. + let g = &mut self.guests[i]; + g.first_good = g.position; + g.known_moves = g.received_moves; let mut budget = 400; while budget > 0 { let Some(packet) = self.guests[i].inbox.pop_front() else { @@ -1595,23 +1732,42 @@ impl Hub { self.guests[i].last_action_tick = self.ticks; } match packet { + // handleAcceptTeleportPacket. S::AcceptTeleportation(p) => { let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some_and(|(id, _)| id == p.id) { + if let Some((id, at)) = g.awaiting_teleport + && id == p.id + { + if p.x.is_nan() + || p.y.is_nan() + || p.z.is_nan() + || !p.yaw.is_finite() + || !p.pitch.is_finite() + { + self.kick(conn, invalid_movement()); + continue; + } + g.position = at; g.awaiting_teleport = None; + let rot = (p.yaw, p.pitch); + self.position_change(i, [p.x, p.y, p.z], rot, 0, ctx, events); } } S::MovePlayerPos(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags); + self.move_player(i, Some([p.x, p.y, p.z]), None, p.flags, ctx, events); } S::MovePlayerPosRot(p) => { - self.move_player(i, Some([p.x, p.y, p.z]), Some((p.yaw, p.pitch)), p.flags); + let (pos, rot) = ([p.x, p.y, p.z], (p.yaw, p.pitch)); + self.move_player(i, Some(pos), Some(rot), p.flags, ctx, events); } S::MovePlayerRot(p) => { - self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags); + self.move_player(i, None, Some((p.yaw, p.pitch)), p.flags, ctx, events); + } + S::MovePlayerStatus(p) => { + self.move_player(i, None, None, p.flags, ctx, events); } - S::MovePlayerStatus(p) => self.move_player(i, None, None, p.flags), S::PlayerLoaded(_) => self.guests[i].loaded = true, + // PlayerChunkSender.onChunkBatchReceivedByClient. S::ChunkBatchReceived(p) => { let g = &mut self.guests[i]; g.unacknowledged = g.unacknowledged.saturating_sub(1); @@ -1620,7 +1776,12 @@ impl Hub { } else { p.chunks_per_tick.clamp(0.01, 64.0) }; + if g.unacknowledged == 0 { + g.batch_quota = 1.0; + } + g.max_unacknowledged = 10; } + S::ClientTickEnd(_) => self.guests[i].position_this_tick = false, S::ClientInformation(info) => { let g = &mut self.guests[i]; g.view_distance = @@ -1636,63 +1797,215 @@ impl Hub { 1 => self.guests[i].sprinting = true, 2 => self.guests[i].sprinting = false, 6 => self.guests[i].fall_flying = true, - 0 => self.guests[i].sleeping = false, + // STOP_SLEEPING. + 0 => self.wake(i), _ => {} }, - S::ClientTickEnd(_) => {} - S::Chat(c) => { - let text: String = c.message.chars().filter(|c| !c.is_control()).collect(); - if !text.is_empty() { - let name = self.guests[i].name.clone(); - self.player_chat(i, &text); - events.push(HostEvent::Chat(format!("<{name}> {text}"))); - } - } + S::Chat(c) => self.handle_chat(i, c, events), + S::ChatAck(p) => self.chat_ack(i, p.offset, events), + S::ChatSessionUpdate(p) => self.chat_session_update(i, p, events), other => events.push(HostEvent::Packet(conn, Box::new(other))), } } - let _ = ctx; } /// ServerGamePacketListenerImpl.handleMovePlayer. - fn move_player(&mut self, i: usize, pos: Option<[f64; 3]>, rot: Option<(f32, f32)>, flags: u8) { - let g = &mut self.guests[i]; - if g.awaiting_teleport.is_some() || !g.loaded && g.ticks == 0 && pos.is_none() { + fn move_player( + &mut self, + i: usize, + pos: Option<[f64; 3]>, + rot: Option<(f32, f32)>, + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let conn = self.guests[i].conn; + // containsInvalidValues, on the packet's values (0 where it has none). + let (yaw, pitch) = rot.unwrap_or_default(); + if pos.is_some_and(|p| p.iter().any(|v| v.is_nan())) + || !yaw.is_finite() + || !pitch.is_finite() + { + self.kick(conn, invalid_movement()); return; } - if let Some(p) = pos { - if p.iter().any(|v| !v.is_finite() || v.abs() > 3.0e7) { + let g = &mut self.guests[i]; + if pos.is_some() { + if g.position_this_tick { + self.kick(conn, invalid_movement()); return; } - // A jump of more than a hundred blocks is a rejected move. - let d2: f64 = (0..3).map(|k| (p[k] - g.position[k]).powi(2)).sum(); - if d2 > 100.0 * 100.0 { - let at = g.position; - self.teleport(i, Some(at)); - return; - } - g.previous_position = g.position; - g.position = p; + g.position_this_tick = true; } - let moved = pos.map_or([0.0; 3], |_| { - [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]) - }); + if !g.loaded && g.ticks == 0 && pos.is_none() { + return; + } + // updateAwaitingTeleport: moves wait for the client to accept the + // teleport, which is sent again after 20 ticks without an answer. + if let Some((_, at)) = g.awaiting_teleport { + if self.ticks - g.teleport_tick > 20 { + self.teleport(i, Some(at)); + } + return; + } + let to = pos.unwrap_or(g.position); + let rot = rot.unwrap_or((g.yaw, g.pitch)); + self.position_change(i, to, rot, flags, ctx, events); + } + + /// ServerGamePacketListenerImpl.handlePlayerPositionChange. + fn position_change( + &mut self, + i: usize, + to: [f64; 3], + (yaw, pitch): (f32, f32), + flags: u8, + ctx: &TickCtx, + events: &mut Vec, + ) { + let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks); + let g = &mut self.guests[i]; + let to = [ + to[0].clamp(-3.0E7, 3.0E7), + to[1].clamp(-2.0E7, 2.0E7), + to[2].clamp(-3.0E7, 3.0E7), + ]; + let (yaw, pitch) = (wrap_degrees(yaw), wrap_degrees(pitch)); + let d = [0, 1, 2].map(|k| to[k] - g.first_good[k]); + let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if g.sleeping { + if moved > 1.0 { + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, None); + } + return; + } + // TickRateManager.runsNormally: not frozen (a frozen game's steps + // are not counted either; Horizon's hub does not see them). + if !frozen { + g.received_moves += 1; + let mut packets = g.received_moves - g.known_moves; + if packets > 5 { + packets = 1; + } + // shouldCheckPlayerMovement. The server holds no velocity for a + // guest (getDeltaMovement), so nothing is expected. + if check && (!g.fall_flying || elytra_check) { + let limit = if g.fall_flying { 300.0 } else { 100.0 }; + if moved > limit * f64::from(packets) { + events.push(HostEvent::Warn(format!( + "{} moved too quickly! {},{},{}", + g.name, + crate::java_text::double_to_string(d[0]), + crate::java_text::double_to_string(d[1]), + crate::java_text::double_to_string(d[2]) + ))); + self.teleport(i, None); + return; + } + } + } + let start = g.position; + let (wrongly, refused) = self.collide(i, to, ctx); + if wrongly { + let line = format!("{} moved wrongly!", self.guests[i].name); + events.push(HostEvent::Warn(line)); + } + if refused { + let g = &mut self.guests[i]; + (g.yaw, g.pitch) = (yaw, pitch); + self.teleport(i, Some(start)); + return; + } + let g = &mut self.guests[i]; + g.previous_position = g.position; + g.position = to; + let moved = [0, 1, 2].map(|k| g.position[k] - g.previous_position[k]); if g.moves.is_empty() { g.moves_from_ground = g.on_ground; } g.moves.push((moved, flags & 1 != 0)); - if let Some((yaw, pitch)) = rot - && yaw.is_finite() - && pitch.is_finite() - { - g.yaw = yaw % 360.0; - g.pitch = pitch.clamp(-90.0, 90.0); - g.head_yaw = g.yaw; - } + g.yaw = yaw; + g.pitch = pitch.clamp(-90.0, 90.0); + g.head_yaw = g.yaw; g.on_ground = flags & 1 != 0; g.ticks = g.ticks.max(1); } + /// The collision part of handlePlayerPositionChange: whether the move + /// counts as moved wrongly (logged), and whether it is refused (the + /// player is sent back where they were). + fn collide(&self, i: usize, to: [f64; 3], ctx: &TickCtx) -> (bool, bool) { + let g = &self.guests[i]; + // noPhysics (spectators) and sleepers move freely. + let Some(binding) = ctx.collision else { + return (false, false); + }; + if g.spectator() || g.sleeping { + return (false, false); + } + let height = if g.fall_flying { + 0.6 + } else if g.sneaking { + 1.5 + } else { + 1.8 + }; + let at = |p: [f64; 3]| { + Aabb::new( + Vec3::new(p[0] - 0.3, p[1], p[2] - 0.3), + Vec3::new(p[0] + 0.3, p[1] + height, p[2] + 0.3), + ) + }; + let (old, new) = (at(g.position), at(to)); + let mut scene = SceneCollisions { + world: ctx.world, + binding, + subject: None, + }; + // player.move, then how far from the target it ended (vanilla drops + // the vertical part: `yDist > -0.5 || yDist < 0.5` always holds). + let movement = Vec3::new( + to[0] - g.position[0], + to[1] - g.position[1], + to[2] - g.position[2], + ); + let fail = !g.creative() + && scene + .resolve(old, movement, 0.6, g.on_ground) + .is_ok_and(|done| { + let (dx, dz) = (movement.x - done.x, movement.z - done.z); + dx * dx + dz * dz > 0.0625 + }); + if fail && scene.unobstructed(old).unwrap_or(true) { + return (true, true); + } + // isEntityCollidingWithAnythingNew: a block the old box did not + // already touch. + let shrink = f64::from(1.0E-5_f32); + let shrink = Vec3::new(shrink, shrink, shrink); + let Ok(old_shape) = VoxelShape::from_box(old.deflate(shrink)) else { + return (fail, false); + }; + let context = CollisionContext::position(g.position[1]); + let Ok(scan) = + BlockCollisionScan::new(&mut scene, context, new.deflate(shrink), false, 1 << 20) + else { + return (fail, false); + }; + for hit in scan { + let Ok(hit) = hit else { break }; + if !hit + .shape + .join_is_not_empty(&old_shape, ShapeOp::AND) + .unwrap_or(true) + { + return (fail, true); + } + } + (fail, false) + } + /// Acknowledge a block interaction (ClientboundBlockChangedAckPacket). /// ServerGamePacketListenerImpl.ackBlockChangesUpTo: sent with the next tick's block /// changes (`tick`). @@ -1772,12 +2085,15 @@ impl Hub { let mode = self.guests[i].game_mode; let mut info = self.spawn_info(mode); // Player.getLastDeathLocation, set where the player died. + // The level they died in: theirs until now. info.last_death = self.guests[i].last_death.map(|pos| play::GlobalPos { - dimension: self.config.dimension.clone(), + dimension: self.guests[i].dimension.clone(), pos, }); self.close_container_for(i); let g = &mut self.guests[i]; + // PlayerList.respawn: into the level in place (the respawn level). + g.dimension = self.config.dimension.clone(); // ServerLevel.removePlayerImmediately: every entity paired with the dead player is // removed (ServerEntity.removePairing, one packet each). Its chunks are dropped // without ForgetLevelChunk (PlayerChunkSender.dropChunk skips dead players): the @@ -1846,6 +2162,20 @@ impl Hub { /// The level the players are in: the server holds one at a time, and the /// hub's packets name it. pub fn set_dimension(&mut self, dimension: &str) { + if self.config.dimension == dimension { + return; + } + // What this level's players were told stays with it. + let leaving = LevelSync { + last_clock: self.last_clock, + last_rate: self.last_rate, + weather: self.weather, + }; + let entering = self.level_sync.remove(dimension).unwrap_or_default(); + self.level_sync + .insert(std::mem::take(&mut self.config.dimension), leaving); + (self.last_clock, self.last_rate, self.weather) = + (entering.last_clock, entering.last_rate, entering.weather); self.config.dimension = dimension.to_owned(); self.dimension_type = self .sync @@ -1860,16 +2190,28 @@ impl Hub { /// names (`set_dimension`): ClientboundRespawnPacket keeping all data, /// then vanilla's packet order. Nothing tracked in the old level is /// removed one by one: the client drops its whole level. - pub fn change_level(&mut self, i: usize, at: [f64; 3], yaw: f32, ctx: &TickCtx) { + pub fn change_level( + &mut self, + i: usize, + at: [f64; 3], + yaw: f32, + pitch: Option, + portal_sound: bool, + ctx: &TickCtx, + ) { let mode = self.guests[i].game_mode; let info = self.spawn_info(mode); self.close_container_for(i); let g = &mut self.guests[i]; + g.dimension = self.config.dimension.clone(); g.tracker.clear(); g.sent_chunks.clear(); g.chunk_queue.clear(); g.center = None; g.yaw = yaw; + if let Some(pitch) = pitch { + g.pitch = pitch; + } g.position = at; g.previous_position = at; g.send(&C::Respawn(play::Respawn { @@ -1901,12 +2243,14 @@ impl Hub { // ServerPlayer.sendPostEffects. g.send(&raw(ids::POST_EFFECTS, vec![0])); // TeleportTransition.PLAY_PORTAL_SOUND. - g.send(&C::LevelEvent(play::LevelEvent { - kind: 1032, - pos: [0, 0, 0], - data: 0, - global: false, - })); + if portal_sound { + g.send(&C::LevelEvent(play::LevelEvent { + kind: 1032, + pos: [0, 0, 0], + data: 0, + global: false, + })); + } // lastSentExp, lastSentHealth and lastSentFood. g.sent_health = None; g.sent_xp = None; @@ -1920,6 +2264,23 @@ impl Hub { } /// A packet Horizon sends as raw bytes (no fields worth a type). +/// multiplayer.disconnect.invalid_player_movement. +/// Mth.wrapDegrees. +fn wrap_degrees(degrees: f32) -> f32 { + let mut wrapped = degrees % 360.0; + if wrapped >= 180.0 { + wrapped -= 360.0; + } + if wrapped < -180.0 { + wrapped += 360.0; + } + wrapped +} + +fn invalid_movement() -> Tag { + translatable("multiplayer.disconnect.invalid_player_movement", &[]) +} + fn raw(id: i32, payload: Vec) -> C { C::Unknown(id, payload) } diff --git a/crates/horizon-client/src/lan/hub/chat.rs b/crates/horizon-client/src/lan/hub/chat.rs new file mode 100644 index 000000000..7e75c84c5 --- /dev/null +++ b/crates/horizon-client/src/lan/hub/chat.rs @@ -0,0 +1,500 @@ +//! Chat on the server side, as ServerGamePacketListenerImpl and PlayerList +//! handle it: chat sessions validated against the services' keys, signed +//! messages checked link by link, the acknowledged window, and messages +//! relayed with each connection's numbering and signature cache. +use super::{HostEvent, Hub, display_name}; +use horizon_protocol::{ + packets::play::{self, Clientbound as C}, + secure_chat::{self, Body, Chain, ChatSession, DecodeError, ProfileKey, Signature, Unpacked}, + text::{literal, translatable}, +}; +use horizon_world::nbt::{JavaString, Tag}; + +/// Now, in epoch milliseconds (Instant.now()). +pub fn now_millis() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis() as i64) +} + +/// StringUtil.isAllowedChatCharacter. +fn allowed(c: char) -> bool { + c != '\u{a7}' && c >= ' ' && c != '\u{7f}' +} + +/// A translatable message in red. +fn red(key: &str) -> Tag { + let mut t = translatable(key, &[]); + if let Tag::Compound(map) = &mut t { + map.insert( + JavaString::from("color"), + Tag::String(JavaString::from("red")), + ); + } + t +} + +/// PlayerChatMessage as the server relays it. +#[derive(Clone, Debug, PartialEq)] +pub struct ChatMessage { + pub sender: u128, + /// The link's index in the sender's chain (0 when unsigned). + pub index: i32, + pub signature: Option, + pub content: String, + /// Epoch milliseconds. + pub timestamp: i64, + pub salt: i64, + pub last_seen: Vec, + /// What clients show instead of the signed text (withUnsignedContent). + pub unsigned_content: Option, +} + +impl ChatMessage { + /// The message a chain let through: a signed one keeps its body; + /// PlayerChatMessage.unsigned takes the time now, no salt, nothing seen. + pub fn new(sender: u128, unpacked: Unpacked, body: &Body, now: i64) -> Self { + let (index, signature, timestamp, salt, last_seen) = match unpacked { + Unpacked::Unsigned => (0, None, now, 0, Vec::new()), + Unpacked::Signed { index, signature } => ( + index, + Some(signature), + body.timestamp, + body.salt, + body.last_seen.to_vec(), + ), + }; + Self { + sender, + index, + signature, + content: body.content.to_owned(), + timestamp, + salt, + last_seen, + unsigned_content: None, + } + } + /// hasExpiredServer. + pub fn expired(&self, now: i64) -> bool { + now > self.timestamp + secure_chat::EXPIRES_AFTER_SERVER + } + /// PlayerList.verifyChatTrusted: signed and not expired. + pub fn trusted(&self, now: i64) -> bool { + self.signature.is_some() && !self.expired(now) + } +} + +impl Hub { + /// MinecraftServer.enforceSecureProfile. + pub fn enforces_secure_chat(&self) -> bool { + self.lan.shared.config.enforces_secure_chat() + } + + /// Component.getString in the server's language, for the log. + pub(crate) fn english(&self, tag: &Tag) -> String { + match &self.lan.shared.config.log { + Some(log) => horizon_protocol::text::plain(tag, &log.lang), + None => horizon_protocol::text::plain(tag, &Default::default()), + } + } + + /// tryHandleChat: an illegal character disconnects; with chat hidden a + /// message (not a command) is refused. Whether to go on. + pub fn try_handle_chat(&mut self, i: usize, message: &str, command: bool) -> bool { + let conn = self.guests[i].conn; + if !message.chars().all(allowed) { + self.kick( + conn, + translatable("multiplayer.disconnect.illegal_characters", &[]), + ); + return false; + } + // ChatVisiblity.HIDDEN. + if !command && self.guests[i].info.chat_visibility == 2 { + self.guests[i].send(&C::SystemChat(play::SystemChat { + content: red("chat.disabled.options"), + overlay: false, + })); + return false; + } + true + } + + /// unpackAndApplyLastSeen: the acknowledged messages, or a disconnect. + pub fn apply_last_seen( + &mut self, + i: usize, + update: &play::LastSeenUpdate, + events: &mut Vec, + ) -> Option> { + let g = &mut self.guests[i]; + match g + .last_seen + .apply_update(update.offset, update.acknowledged, update.checksum) + { + Ok(seen) => Some(seen), + // Vanilla logs the ValidationException's stack trace after the line. + Err(_) => { + events.push(HostEvent::Error(format!( + "Failed to validate message acknowledgements from {}", + g.name + ))); + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.chat_validation_failed", &[]), + ); + None + } + } + } + + /// handleChatAck. + pub(super) fn chat_ack(&mut self, i: usize, offset: i32, events: &mut Vec) { + let g = &mut self.guests[i]; + if g.last_seen.apply_offset(offset).is_err() { + events.push(HostEvent::Error(format!( + "Failed to validate message acknowledgement offset from {}", + g.name + ))); + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.chat_validation_failed", &[]), + ); + } + } + + /// handleMessageDecodeFailure: logged, and the reason in red for the player. + pub fn decode_failure(&mut self, i: usize, e: DecodeError, events: &mut Vec) { + let reason = red(e.key()); + events.push(HostEvent::Warn(format!( + "Failed to update secure chat state for {}: '{}'", + self.guests[i].name, + self.english(&reason) + ))); + self.guests[i].send(&C::SystemChat(play::SystemChat { + content: reason, + overlay: false, + })); + } + + /// handleChat: the acknowledgements, then the message through the + /// sender's chain, then to everyone. + pub(super) fn handle_chat(&mut self, i: usize, c: play::Chat, events: &mut Vec) { + let Some(last_seen) = self.apply_last_seen(i, &c.last_seen, events) else { + return; + }; + if !self.try_handle_chat(i, &c.message, false) { + return; + } + let (enforce, now) = (self.enforces_secure_chat(), now_millis()); + let body = Body { + content: &c.message, + timestamp: c.timestamp, + salt: c.salt, + last_seen: &last_seen, + }; + let signature = c.signature.as_deref().and_then(secure_chat::signature); + let g = &mut self.guests[i]; + let (uuid, name) = (g.uuid, g.name.clone()); + let message = match g + .chain + .unpack(uuid, signature.as_ref(), &body, enforce, now) + { + Ok(unpacked) => ChatMessage::new(uuid, unpacked, &body, now), + Err(e) => return self.decode_failure(i, e, events), + }; + if message.signature.is_some() && message.expired(now) { + events.push(HostEvent::Warn(format!( + "Received expired chat: '{}'. Is the client/server system time unsynchronized?", + message.content + ))); + } + let bound = play::ChatTypeBound { + chat_type: self.chat_type, + name: display_name(uuid, &name), + target: None, + }; + let line = format!("<{name}> {}", message.content); + self.broadcast_chat(&message, &bound, line, events); + } + + /// handleChatSessionUpdate: a new profile key, validated against the + /// services' keys, starts a new chain and is announced to everyone. + pub(super) fn chat_session_update( + &mut self, + i: usize, + p: play::ChatSessionUpdate, + events: &mut Vec, + ) { + let key = ProfileKey { + expires_at: p.expires_at, + key: p.key, + signature: p.key_signature, + }; + let g = &self.guests[i]; + let (conn, uuid) = (g.conn, g.uuid); + let old = g.chain.session().map(|s| s.profile_key.expires_at); + if g.chain.session().is_some_and(|s| s.profile_key == key) { + return; + } + if old.is_some_and(|old| key.expires_at < old) { + self.kick( + conn, + translatable("multiplayer.disconnect.expired_public_key", &[]), + ); + return; + } + let secure = self.lan.shared.config.secure_chat.clone(); + let keys = secure.as_deref().map_or(&[][..], |s| s.keys()); + if keys.is_empty() { + events.push(HostEvent::Warn(format!( + "Ignoring chat session from {} due to missing Services public key", + g.name + ))); + return; + } + match ChatSession::validate(p.session, key, keys, uuid) { + Ok(session) => { + let data = session.data(); + self.guests[i].chain = Chain::keyed(session); + // resetPlayerChatState: INITIALIZE_CHAT to every player. + self.broadcast(&C::PlayerInfoUpdate(play::PlayerInfoUpdate { + actions: 2, + entries: vec![play::PlayerInfo { + uuid, + chat_session: Some(data), + ..Default::default() + }], + })); + } + Err(reason) => { + events.push(HostEvent::Error( + "Failed to validate profile key".to_owned(), + )); + self.kick(conn, translatable(reason, &[])); + } + } + } + + /// PlayerList.broadcastChatMessage: logged (`[Not Secure]` unless signed + /// and fresh), then sent to every player. + pub fn broadcast_chat( + &mut self, + message: &ChatMessage, + bound: &play::ChatTypeBound, + line: String, + events: &mut Vec, + ) { + let secure = message.trusted(now_millis()); + events.push(HostEvent::Chat { line, secure }); + for k in 0..self.guests.len() { + if self.guests[k].placed { + self.send_chat(k, message, bound); + } + } + } + + /// ServerPlayer.sendChatMessage (players who show chat) and + /// sendPlayerChatMessage: numbered for the connection, the last seen + /// packed against its cache; a signed message joins the cache and the + /// messages the player must acknowledge. + pub fn send_chat(&mut self, k: usize, message: &ChatMessage, bound: &play::ChatTypeBound) { + let g = &mut self.guests[k]; + if g.info.chat_visibility != 0 { + return; + } + let last_seen = message + .last_seen + .iter() + .map(|s| g.signatures.pack(s)) + .collect(); + g.send(&C::PlayerChat(play::PlayerChat { + global_index: g.chat_index, + sender: message.sender, + index: message.index, + signature: message.signature.map(|s| s.to_vec()), + content: message.content.clone(), + timestamp: message.timestamp, + salt: message.salt, + last_seen, + unsigned_content: message.unsigned_content.clone(), + filter: (0, Vec::new()), + chat_type: bound.clone(), + })); + g.chat_index += 1; + if let Some(signature) = &message.signature { + g.signatures.push(&message.last_seen, Some(signature)); + g.last_seen.add_pending(signature); + if g.last_seen.tracked_count() > 4096 { + let conn = g.conn; + self.kick( + conn, + translatable("multiplayer.disconnect.too_many_pending_chats", &[]), + ); + } + } + } + + /// sendChatMessage of a system message: a disguised chat, to players + /// who show chat. + fn send_disguised(&self, k: usize, message: Tag, chat_type: play::ChatTypeBound) { + let g = &self.guests[k]; + if g.info.chat_visibility == 0 { + g.send(&C::DisguisedChat(play::DisguisedChat { + message, + chat_type, + })); + } + } + + /// collectSignedArguments, or collectUnsignedArguments when the client + /// signed none: each of the command's message arguments (`parsed`, by + /// name) through the sender's chain. + pub fn signed_arguments( + &mut self, + i: usize, + p: &play::ChatCommandSigned, + parsed: &[(String, String)], + last_seen: &[Signature], + events: &mut Vec, + ) -> Result, DecodeError> { + let (enforce, now) = (self.enforces_secure_chat(), now_millis()); + let g = &mut self.guests[i]; + let uuid = g.uuid; + let mut out = Vec::new(); + if p.arguments.is_empty() { + for (name, value) in parsed { + // SignedMessageBody.unsigned. + let body = Body { + content: value, + timestamp: now, + salt: 0, + last_seen: &[], + }; + let unpacked = g.chain.unpack(uuid, None, &body, enforce, now)?; + out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now))); + } + return Ok(out); + } + let mismatch = |events: &mut Vec| { + let names = |l: &mut dyn Iterator| { + l.map(String::as_str).collect::>().join(", ") + }; + events.push(HostEvent::Error(format!( + "Signed command mismatch between server and client ('{}'): got [{}] from client, but expected [{}]", + p.command, + names(&mut p.arguments.iter().map(|a| &a.0)), + names(&mut parsed.iter().map(|a| &a.0)), + ))); + DecodeError::InvalidCommandSignature + }; + for (name, signature) in &p.arguments { + let Some((_, value)) = parsed.iter().find(|(n, _)| n == name) else { + g.chain.set_broken(); + return Err(mismatch(events)); + }; + let body = Body { + content: value, + timestamp: p.timestamp, + salt: p.salt, + last_seen, + }; + let signature = secure_chat::signature(signature); + let unpacked = g + .chain + .unpack(uuid, signature.as_ref(), &body, enforce, now)?; + out.push((name.clone(), ChatMessage::new(uuid, unpacked, &body, now))); + } + if parsed.iter().any(|(n, _)| !out.iter().any(|(o, _)| o == n)) { + return Err(mismatch(events)); + } + Ok(out) + } + + /// A message command's chat (SayCommand, EmoteCommands): to everyone, + /// bound to `chat_type` and the sender's name. + pub fn broadcast_command_chat( + &mut self, + i: usize, + chat_type: &str, + message: Option, + text: &str, + events: &mut Vec, + ) { + let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone()); + let bound = play::ChatTypeBound { + chat_type: self.chat_type_id(chat_type), + name: display_name(uuid, &name), + target: None, + }; + let line = match chat_type { + "say_command" => format!("[{name}] {text}"), + _ => format!("* {name} {text}"), + }; + match message { + Some(message) => self.broadcast_chat(&message, &bound, line, events), + // An unsigned command packet (no signing context): + // PlayerChatMessage.system, a disguised chat. + None => { + events.push(HostEvent::Chat { + line, + secure: false, + }); + for k in 0..self.guests.len() { + if self.guests[k].placed { + self.send_disguised(k, literal(text), bound.clone()); + } + } + } + } + } + + /// MsgCommand.sendMessage to each target: the outgoing line for the + /// sender, the incoming one for the target. Nothing is logged. + pub fn whisper( + &mut self, + i: usize, + targets: &[usize], + message: Option, + text: &str, + ) { + let (uuid, name) = (self.guests[i].uuid, self.guests[i].name.clone()); + let (outgoing, incoming) = ( + self.chat_type_id("msg_command_outgoing"), + self.chat_type_id("msg_command_incoming"), + ); + for &t in targets { + let target = display_name(self.guests[t].uuid, &self.guests[t].name); + let out = play::ChatTypeBound { + chat_type: outgoing, + name: display_name(uuid, &name), + target: Some(target), + }; + let inc = play::ChatTypeBound { + chat_type: incoming, + name: display_name(uuid, &name), + target: None, + }; + match &message { + Some(m) => { + self.send_chat(i, m, &out); + self.send_chat(t, m, &inc); + } + None => { + self.send_disguised(i, literal(text), out); + self.send_disguised(t, literal(text), inc); + } + } + } + } + + /// A chat type's registry id. + fn chat_type_id(&self, name: &str) -> i32 { + self.sync + .id("minecraft:chat_type", &format!("minecraft:{name}")) + .unwrap_or(self.chat_type) + } +} diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index 58badc010..afe188699 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -20,8 +20,9 @@ pub mod menu; pub mod playerdata; mod recipes; pub mod tracking; +pub mod waypoints; -pub use conn::{Holding, PlayerSender}; +pub use conn::{Holding, PlayerSender, flush_all}; use horizon_protocol::packets::play; use horizon_protocol::{ GAME_VERSION, PROTOCOL_VERSION, crypto::uuid_string, packets::configuration::ClientInformation, @@ -121,8 +122,8 @@ pub struct NetConfig { pub hide_online_players: bool, /// server-icon.png (64x64 PNG bytes). pub favicon: Option>, - /// MinecraftServer.enforceSecureProfile. - pub enforces_secure_chat: bool, + /// Secure chat (a dedicated server; none on a LAN world). + pub secure_chat: Option>, pub accepts_transfers: bool, /// LanServerPinger: announce the world on the local network. pub announce: bool, @@ -137,6 +138,10 @@ pub struct NetConfig { pub log: Option, } impl NetConfig { + /// MinecraftServer.enforceSecureProfile. + pub fn enforces_secure_chat(&self) -> bool { + self.secure_chat.as_ref().is_some_and(|s| s.enforced()) + } /// IntegratedServer.publishServer. pub fn lan(port: u16, motd: String, max_players: usize) -> Self { Self { @@ -148,7 +153,7 @@ impl NetConfig { enable_status: true, hide_online_players: false, favicon: None, - enforces_secure_chat: false, + secure_chat: None, accepts_transfers: false, announce: true, listen: true, @@ -160,6 +165,46 @@ impl NetConfig { } } +/// A dedicated server's secure chat (DedicatedServer.enforceSecureProfile, +/// Services.profileKeySignatureValidator): the services' profile-key keys, +/// fetched in the background from startup and waited for by their first +/// use, as authlib's RetryableFetch does. +pub struct SecureChat { + /// enforce-secure-profile, in online mode. + pub enforce: bool, + keys: std::sync::OnceLock>, + fetch: Mutex>>>, +} + +impl SecureChat { + pub fn new( + enforce: bool, + fetch: impl FnOnce() -> Vec + Send + 'static, + ) -> Self { + let handle = std::thread::Builder::new() + .name("Services keys".into()) + .spawn(fetch) + .ok(); + Self { + enforce, + keys: std::sync::OnceLock::new(), + fetch: Mutex::new(handle), + } + } + /// The keys players' chat keys must be signed by (none when the + /// services couldn't be reached). + pub fn keys(&self) -> &[horizon_protocol::rsa::RsaPublicKey] { + self.keys.get_or_init(|| { + let handle = self.fetch.lock().ok().and_then(|mut h| h.take()); + handle.and_then(|h| h.join().ok()).unwrap_or_default() + }) + } + /// enforceSecureProfile: enforced, and able to check keys. + pub fn enforced(&self) -> bool { + self.enforce && !self.keys().is_empty() + } +} + /// State shared with the connection threads. pub struct Shared { pub sync: Arc, @@ -300,7 +345,7 @@ impl Shared { Json::String(format!("data:image/png;base64,{}", base64(icon))), )); } - if self.config.enforces_secure_chat { + if self.config.enforces_secure_chat() { status.push(("enforcesSecureChat".to_owned(), Json::Bool(true))); } Json::Object(status).compact() diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index 555463685..d7dc097dd 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -68,9 +68,15 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_total = level.xp_total; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); + guest.flying = level.flying; guest.selected = (level.selected_slot.max(0) as usize).min(8); + guest.spawn = level.spawn.map(|s| [s[0] + 0.5, s[1], s[2] + 0.5]); guest.saved = level.player_extra.clone(); guest.recipe_book = level.recipe_book.clone(); + guest.dimension = match level.dimension.as_str() { + d @ ("minecraft:the_nether" | "minecraft:the_end") => d.to_owned(), + _ => "minecraft:overworld".to_owned(), + }; if level.ender_items.len() == 27 { guest.ender_items = level.ender_items.clone(); } @@ -100,7 +106,6 @@ pub fn apply(guest: &mut Guest, level: &Level) { pub fn save(guest: &Guest, world: &Path) { let mut level = Level { player_uuid: Some(uuid_ints(guest.uuid)), - dimension: "minecraft:overworld".into(), ..Level::default() }; store(guest, &mut level); @@ -114,6 +119,7 @@ pub fn save(guest: &Guest, world: &Path) { /// Put a guest's state in `level`'s player fields. pub fn store(guest: &Guest, level: &mut Level) { level.position = Some(guest.position); + level.dimension = guest.dimension.clone(); level.rotation = [guest.yaw, guest.pitch]; level.health = guest.health; level.food = guest.food; @@ -124,7 +130,9 @@ pub fn store(guest: &Guest, level: &mut Level) { level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; + level.flying = guest.flying; level.selected_slot = guest.selected as i32; + level.spawn = guest.spawn.map(|s| [s[0] - 0.5, s[1], s[2] - 0.5]); level.on_ground = guest.on_ground; level.player_extra = guest.saved.clone(); level.recipe_book = guest.recipe_book.clone(); diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs new file mode 100644 index 000000000..a8797dbaf --- /dev/null +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -0,0 +1,643 @@ +//! The locator bar for remote players: ServerWaypointManager and +//! WaypointTransmitter's connections, for players (the transmitters vanilla has +//! by default: `waypoint_transmit_range` is 0 for every other entity). +//! +//! Vanilla updates a player's connections each time the player's position +//! changes (`Entity.setPosRaw`, then `ServerChunkCache.move`). The hub sees the +//! position once a tick, after the moves it handled, and updates from there: +//! the same packets, since a client sends one move a tick. Hiding (crouching, +//! invisibility, a carved pumpkin or a mob head worn) changes +//! `waypoint_transmit_range` and tracks or untracks the waypoint, as +//! `LivingEntity.onAttributeUpdated` does; joining or leaving a team remakes the +//! connections with the team's colour (`ServerScoreboard.updatePlayerWaypoint`). +use horizon_protocol::packets::play::{ + Clientbound as C, TrackedWaypoint, WaypointId, WaypointTarget, waypoint_operation, +}; +use std::collections::HashMap; + +/// `Player.createAttributes`: both waypoint ranges. +pub const PLAYER_RANGE: f64 = 6.0e7; +/// `WaypointTransmitter.REALLY_FAR_DISTANCE`. +const REALLY_FAR: f32 = 332.0; +/// `EntityAzimuthConnection.update`: half a degree. +const AZIMUTH_STEP: f32 = 0.008_726_646; + +/// Items that hide their wearer (`Waypoint.addHideAttribute` on the head slot). +pub const HIDING_HEADS: [&str; 8] = [ + "minecraft:carved_pumpkin", + "minecraft:skeleton_skull", + "minecraft:wither_skeleton_skull", + "minecraft:player_head", + "minecraft:zombie_head", + "minecraft:creeper_head", + "minecraft:dragon_head", + "minecraft:piglin_head", +]; + +/// A team colour as the locator bar draws it (`Waypoint.Icon.cloneAndAssignStyle`: +/// `TeamColor.rgb()`, black lightened so it shows). +pub fn team_rgb(color: &str) -> Option { + let rgb = match color { + "black" => return Some(-13_619_152), + "dark_blue" => 0x0000AA, + "dark_green" => 0x00AA00, + "dark_aqua" => 0x00AAAA, + "dark_red" => 0xAA0000, + "dark_purple" => 0xAA00AA, + "gold" => 0xFFAA00, + "gray" => 0xAAAAAA, + "dark_gray" => 0x555555, + "blue" => 0x5555FF, + "green" => 0x55FF55, + "aqua" => 0x55FFFF, + "red" => 0xFF5555, + "light_purple" => 0xFF55FF, + "yellow" => 0xFFFF55, + "white" => 0xFFFFFF, + _ => return None, + }; + Some(rgb) +} + +/// Waypoint.Icon. +#[derive(Clone, Debug, PartialEq)] +pub struct Icon { + pub style: String, + pub color: Option, +} + +impl Default for Icon { + fn default() -> Self { + Self { + style: "minecraft:default".into(), + color: None, + } + } +} + +/// A player as the waypoint manager sees them this tick. +#[derive(Clone, Debug)] +pub struct Player { + pub uuid: u128, + /// The connection that receives the player's locator bar (None: the host, + /// whose own game draws it). + pub conn: Option, + pub position: [f64; 3], + pub spectator: bool, + /// `waypoint_transmit_range`: 0 while hidden. + pub transmit_range: f64, + pub receive_range: f64, + /// `Entity.firstTick`: the player has not ticked since joining. + pub first_tick: bool, + /// The chunk view radius (`ChunkMap.getPlayerViewDistance`). + pub view_distance: i32, + /// The player's team and its colour (`TeamColor.rgb`). + pub team: Option<(String, Option)>, + /// The icon `/waypoint modify` set. + pub icon: Icon, +} + +impl Player { + fn block(&self) -> [i32; 3] { + self.position.map(|v| v.floor() as i32) + } + fn chunk(&self) -> [i32; 2] { + let [x, _, z] = self.block(); + [x >> 4, z >> 4] + } + /// `Entity.distanceTo`. + fn distance_to(&self, other: &Player) -> f32 { + let d2: f64 = (0..3) + .map(|k| (self.position[k] - other.position[k]).powi(2)) + .sum(); + d2.sqrt() as f32 + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + Block([i32; 3]), + Chunk([i32; 2]), + Azimuth(f32), +} + +#[derive(Clone, Debug)] +struct Connection { + kind: Kind, + icon: Icon, +} + +/// What the manager remembers of a player between ticks. +struct Memo { + position: [f64; 3], + /// The centre of the player's ChunkTrackingView (`ChunkMap.move`). + view_center: [i32; 2], + transmitting: bool, + team: Option<(String, Option)>, +} + +/// ServerWaypointManager for one level. +#[derive(Default)] +pub struct Waypoints { + /// The transmitters, in the order they were tracked. + waypoints: Vec, + /// The receivers, in the order they joined. + players: Vec, + /// Connections by receiver, then source. + connections: HashMap>, + memo: HashMap, + /// The `locator_bar` game rule as last seen. + enabled: Option, +} + +/// One tick's players, and the packets for their connections. +struct Tick<'a> { + players: HashMap, + view: HashMap, + /// Players a respawn replaced this tick: a new ServerPlayer, on its first tick. + fresh: &'a [u128], + enabled: bool, + out: Vec<(u32, C)>, +} + +impl Tick<'_> { + fn send( + &mut self, + receiver: u128, + source: u128, + operation: i32, + icon: &Icon, + target: WaypointTarget, + ) { + let Some(conn) = self.players.get(&receiver).and_then(|p| p.conn) else { + return; + }; + self.out.push(( + conn, + C::TrackedWaypoint(TrackedWaypoint { + operation, + id: WaypointId::Uuid(source), + style: icon.style.clone(), + color: icon.color, + target, + }), + )); + } + fn connect(&mut self, receiver: u128, source: u128, c: &Connection) { + let target = match c.kind { + Kind::Block(p) => WaypointTarget::Block(p), + Kind::Chunk(p) => WaypointTarget::Chunk(p), + Kind::Azimuth(a) => WaypointTarget::Azimuth(a), + }; + self.send(receiver, source, waypoint_operation::TRACK, &c.icon, target); + } + /// `ClientboundTrackedWaypointPacket.removeWaypoint`: an empty waypoint with the null icon. + fn disconnect(&mut self, receiver: u128, source: u128) { + self.send( + receiver, + source, + waypoint_operation::UNTRACK, + &Icon::default(), + WaypointTarget::Empty, + ); + } + /// `ChunkTrackingView.isInViewDistance` of the receiver's view. + fn chunk_visible(&self, [x, z]: [i32; 2], receiver: u128) -> bool { + let Some(&([cx, cz], r)) = self.view.get(&receiver) else { + return false; + }; + let dx = i64::from(((x - cx).abs() - 1).max(0)); + let dz = i64::from(((z - cz).abs() - 1).max(0)); + dx * dx + dz * dz < i64::from(r) * i64::from(r) + } + /// `WaypointTransmitter.doesSourceIgnoreReceiver`. + fn ignores(&self, source: &Player, receiver: &Player) -> bool { + if receiver.spectator { + return false; + } + if source.spectator { + return true; + } + let range = source.transmit_range.min(receiver.receive_range); + f64::from(source.distance_to(receiver)) >= range + } + fn really_far(source: &Player, receiver: &Player) -> bool { + source.distance_to(receiver) > REALLY_FAR + } + /// `EntityAzimuthConnection`: the angle of the receiver seen from the source, + /// `Mth.atan2` of the offset turned clockwise. + fn azimuth(source: &Player, receiver: &Player) -> f32 { + let d = [0, 1, 2].map(|k| receiver.position[k] - source.position[k]); + horizon_core::geometry::trig::atan2(d[0], -d[2]) as f32 + } + /// `LivingEntity.makeWaypointConnectionWith`. + fn make(&self, source: u128, receiver: u128) -> Option { + let (s, r) = (self.players.get(&source)?, self.players.get(&receiver)?); + if s.first_tick || self.fresh.contains(&source) || source == receiver || self.ignores(s, r) + { + return None; + } + // Waypoint.Icon.cloneAndAssignStyle: the icon's colour, else the team's. + let mut icon = s.icon.clone(); + if icon.color.is_none() { + icon.color = s.team.as_ref().and_then(|t| t.1); + } + let kind = if Self::really_far(s, r) { + Kind::Azimuth(Self::azimuth(s, r)) + } else if !self.chunk_visible(s.chunk(), receiver) { + Kind::Chunk(s.chunk()) + } else { + Kind::Block(s.block()) + }; + Some(Connection { kind, icon }) + } + /// `Connection.isBroken` for each kind. + fn broken(&self, c: &Connection, source: u128, receiver: u128) -> bool { + let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else { + return true; + }; + match c.kind { + Kind::Block(last) => { + let now = s.block(); + (0..3).map(|k| (now[k] - last[k]).abs()).sum::() > 1 || self.ignores(s, r) + } + Kind::Chunk(last) => { + let now = s.chunk(); + let moved = (now[0] - last[0]).abs().max((now[1] - last[1]).abs()); + moved > 1 || self.ignores(s, r) || self.chunk_visible(last, receiver) + } + Kind::Azimuth(_) => { + self.ignores(s, r) + || self.chunk_visible(s.chunk(), receiver) + || !Self::really_far(s, r) + } + } + } + /// `Connection.update`: the packet when the waypoint moved. + fn update(&mut self, c: &mut Connection, source: u128, receiver: u128) { + let (Some(s), Some(r)) = (self.players.get(&source), self.players.get(&receiver)) else { + return; + }; + let target = match &mut c.kind { + Kind::Block(last) => { + let now = s.block(); + if now == *last { + return; + } + *last = now; + WaypointTarget::Block(now) + } + Kind::Chunk(last) => { + let now = s.chunk(); + if now == *last { + return; + } + *last = now; + WaypointTarget::Chunk(now) + } + Kind::Azimuth(last) => { + let now = Self::azimuth(s, r); + if (now - *last).abs() <= AZIMUTH_STEP { + return; + } + *last = now; + WaypointTarget::Azimuth(now) + } + }; + let icon = c.icon.clone(); + self.send(receiver, source, waypoint_operation::UPDATE, &icon, target); + } +} + +impl Waypoints { + fn connection(&mut self, receiver: u128, source: u128) -> Option<&mut Connection> { + self.connections + .get_mut(&receiver)? + .iter_mut() + .find(|(s, _)| *s == source) + .map(|(_, c)| c) + } + fn put(&mut self, receiver: u128, source: u128, c: Connection) { + let row = self.connections.entry(receiver).or_default(); + match row.iter_mut().find(|(s, _)| *s == source) { + Some(slot) => slot.1 = c, + None => row.push((source, c)), + } + } + fn take(&mut self, receiver: u128, source: u128) -> Option { + let row = self.connections.get_mut(&receiver)?; + let i = row.iter().position(|(s, _)| *s == source)?; + Some(row.remove(i).1) + } + + /// `createConnection`. + fn create_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) { + if receiver == source || !t.enabled { + return; + } + match t.make(source, receiver) { + Some(c) => { + t.connect(receiver, source, &c); + self.put(receiver, source, c); + } + None => { + if self.take(receiver, source).is_some() { + t.disconnect(receiver, source); + } + } + } + } + /// `updateConnection`. + fn update_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) { + if receiver == source || !t.enabled { + return; + } + let Some(mut c) = self.connection(receiver, source).cloned() else { + return; + }; + if !t.broken(&c, source, receiver) { + t.update(&mut c, source, receiver); + self.put(receiver, source, c); + return; + } + match t.make(source, receiver) { + Some(new) => { + t.connect(receiver, source, &new); + self.put(receiver, source, new); + } + None => { + t.disconnect(receiver, source); + self.take(receiver, source); + } + } + } + /// `trackWaypoint`. + fn track(&mut self, t: &mut Tick, source: u128) { + if !self.waypoints.contains(&source) { + self.waypoints.push(source); + } + for receiver in self.players.clone() { + self.create_connection(t, receiver, source); + } + } + /// `updateWaypoint`. + fn update_waypoint(&mut self, t: &mut Tick, source: u128) { + if !self.waypoints.contains(&source) { + return; + } + for receiver in self.players.clone() { + if self.connection(receiver, source).is_some() { + self.update_connection(t, receiver, source); + } else { + self.create_connection(t, receiver, source); + } + } + } + /// `untrackWaypoint`. + fn untrack(&mut self, t: &mut Tick, source: u128) { + for receiver in self.players.clone() { + if self.take(receiver, source).is_some() { + t.disconnect(receiver, source); + } + } + self.waypoints.retain(|w| *w != source); + } + /// `addPlayer`. + fn add_player(&mut self, t: &mut Tick, player: u128, transmitting: bool) { + if !self.players.contains(&player) { + self.players.push(player); + } + for source in self.waypoints.clone() { + self.create_connection(t, player, source); + } + if transmitting { + self.track(t, player); + } + } + /// `updatePlayer`. + fn update_player(&mut self, t: &mut Tick, player: u128) { + for source in self.waypoints.clone() { + if self.connection(player, source).is_some() { + self.update_connection(t, player, source); + } else { + self.create_connection(t, player, source); + } + } + } + /// `removePlayer`. + fn remove_player(&mut self, t: &mut Tick, player: u128) { + for (source, _) in self.connections.remove(&player).unwrap_or_default() { + t.disconnect(player, source); + } + self.untrack(t, player); + self.players.retain(|p| *p != player); + } + /// `breakAllConnections`. + fn break_all(&mut self, t: &mut Tick) { + for receiver in self.players.clone() { + for (source, _) in self.connections.remove(&receiver).unwrap_or_default() { + t.disconnect(receiver, source); + } + } + self.connections.clear(); + } + + /// One tick: players who left, joined, moved, hid or changed team, and the + /// `locator_bar` game rule. `respawned` players are removed and added again, + /// as `PlayerList.respawn` replaces the ServerPlayer. Returns the packets for + /// each connection. + pub fn tick( + &mut self, + players: &[Player], + respawned: &[u128], + locator_bar: bool, + ) -> Vec<(u32, C)> { + let mut t = Tick { + players: players.iter().map(|p| (p.uuid, p)).collect(), + view: HashMap::new(), + fresh: respawned, + enabled: locator_bar, + out: Vec::new(), + }; + // Vanilla reads the rule when it connects; changing it breaks or remakes + // every connection (MinecraftServer.onGameRuleChanged). + let was = self.enabled.replace(locator_bar); + for (uuid, memo) in &self.memo { + if let Some(p) = t.players.get(uuid) { + t.view.insert(*uuid, (memo.view_center, p.view_distance)); + } + } + // Players who left, and the ServerPlayer a respawn replaced. + let gone: Vec = self + .players + .iter() + .copied() + .filter(|uuid| !t.players.contains_key(uuid) || respawned.contains(uuid)) + .collect(); + for uuid in gone { + self.remove_player(&mut t, uuid); + self.memo.remove(&uuid); + } + if was == Some(true) && !locator_bar { + self.break_all(&mut t); + } + // Players who joined (PlayerList.placeNewPlayer: addPlayer). + for p in players { + if self.memo.contains_key(&p.uuid) { + continue; + } + let center = p.chunk(); + t.view.insert(p.uuid, (center, p.view_distance)); + let transmitting = p.transmit_range > 0.0; + self.memo.insert( + p.uuid, + Memo { + position: p.position, + view_center: center, + transmitting, + team: p.team.clone(), + }, + ); + if p.receive_range > 0.0 { + self.add_player(&mut t, p.uuid, transmitting); + } else if transmitting { + self.track(&mut t, p.uuid); + } + } + if was == Some(false) && locator_bar { + for player in self.players.clone() { + self.update_player(&mut t, player); + } + } + for p in players { + let memo = &self.memo[&p.uuid]; + // Entity.setPosRaw, then ServerChunkCache.move. + if memo.position != p.position { + let moved_view = memo.view_center != p.chunk(); + let transmitting = memo.transmitting; + self.memo.get_mut(&p.uuid).unwrap().position = p.position; + if !p.first_tick { + if transmitting { + self.update_waypoint(&mut t, p.uuid); + } + if p.receive_range > 0.0 { + self.update_player(&mut t, p.uuid); + } + } + if moved_view { + self.memo.get_mut(&p.uuid).unwrap().view_center = p.chunk(); + t.view.insert(p.uuid, (p.chunk(), p.view_distance)); + } + if p.receive_range > 0.0 { + self.update_player(&mut t, p.uuid); + } + } + // LivingEntity.onAttributeUpdated(WAYPOINT_TRANSMIT_RANGE). + let transmitting = p.transmit_range > 0.0; + if transmitting != self.memo[&p.uuid].transmitting { + self.memo.get_mut(&p.uuid).unwrap().transmitting = transmitting; + if transmitting { + self.track(&mut t, p.uuid); + } else { + self.untrack(&mut t, p.uuid); + } + } + // ServerScoreboard: a team joined, left or recoloured remakes the connections. + if p.team != self.memo[&p.uuid].team { + self.memo.get_mut(&p.uuid).unwrap().team = p.team.clone(); + for receiver in self.players.clone() { + self.create_connection(&mut t, receiver, p.uuid); + } + } + } + t.out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn player(uuid: u128, conn: u32, position: [f64; 3]) -> Player { + Player { + uuid, + conn: Some(conn), + position, + spectator: false, + transmit_range: PLAYER_RANGE, + receive_range: PLAYER_RANGE, + first_tick: false, + view_distance: 4, + team: None, + icon: Icon::default(), + } + } + + /// The packets to `conn`, as (operation, target). + fn to(out: &[(u32, C)], conn: u32) -> Vec<(i32, WaypointTarget)> { + out.iter() + .filter(|(c, _)| *c == conn) + .map(|(_, p)| match p { + C::TrackedWaypoint(w) => (w.operation, w.target), + other => panic!("{other:?}"), + }) + .collect() + } + + #[test] + fn a_new_player_shows_once_it_moves() { + let mut w = Waypoints::default(); + let a = player(1, 10, [0.5, 100.0, 0.5]); + let mut b = player(2, 20, [5.5, 100.0, 0.5]); + b.first_tick = true; + w.tick(std::slice::from_ref(&a), &[], true); + let out = w.tick(&[a.clone(), b.clone()], &[], true); + // B gets A at once; A sees nothing of B while B hasn't ticked. + assert_eq!(to(&out, 20), [(0, WaypointTarget::Block([0, 100, 0]))]); + assert!(to(&out, 10).is_empty()); + b.first_tick = false; + assert!(w.tick(&[a.clone(), b.clone()], &[], true).is_empty()); + b.position[0] += 1.0; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert_eq!(to(&out, 10), [(0, WaypointTarget::Block([6, 100, 0]))]); + // One block: an update. Three: a new connection. Out of view: a chunk. + b.position[0] += 1.0; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert_eq!(to(&out, 10), [(2, WaypointTarget::Block([7, 100, 0]))]); + b.position[0] += 3.0; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert_eq!(to(&out, 10), [(0, WaypointTarget::Block([10, 100, 0]))]); + b.position[0] = 100.5; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert_eq!(to(&out, 10), [(0, WaypointTarget::Chunk([6, 0]))]); + // Really far: an angle. + b.position[0] = 1000.5; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert!(matches!( + to(&out, 10)[..], + [(0, WaypointTarget::Azimuth(_))] + )); + // Hidden: untracked; the rule off: every connection broken. + b.transmit_range = 0.0; + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert_eq!(to(&out, 10), [(1, WaypointTarget::Empty)]); + let out = w.tick(&[a.clone(), b.clone()], &[], false); + assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]); + assert!(to(&out, 10).is_empty()); + // Leaving untracks what was left. + let out = w.tick(&[a.clone(), b.clone()], &[], true); + assert!(matches!( + to(&out, 20)[..], + [(0, WaypointTarget::Azimuth(_))] + )); + let out = w.tick(&[b.clone()], &[], true); + assert_eq!(to(&out, 20), [(1, WaypointTarget::Empty)]); + } + + #[test] + fn team_colours() { + assert_eq!(team_rgb("red"), Some(0xFF5555)); + assert_eq!(team_rgb("black"), Some(0xFF30_3030_u32 as i32)); + assert_eq!(team_rgb("reset"), None); + } +} diff --git a/crates/horizon-client/src/level_loading.rs b/crates/horizon-client/src/level_loading.rs index a6b3d04d9..686938adf 100644 --- a/crates/horizon-client/src/level_loading.rs +++ b/crates/horizon-client/src/level_loading.rs @@ -115,6 +115,27 @@ pub fn draw( } } +/// The startup loading screen: the stage's line and a progress bar, centred +/// like `LevelLoadingScreen`'s text and bar. +pub fn draw_progress(batch: &mut HudBatch, atlas: &HudAtlas, line: &str, progress: f32) { + let (x_center, y_center) = ((batch.width as i32) / 2, (batch.height as i32) / 2); + let text_top = y_center - 50; + let text = Text::literal(line); + let tw = atlas.font.width_text(&text) as i32; + batch.text_styled( + atlas, + &text, + (x_center - tw / 2) as f32, + text_top as f32, + u32::MAX, + true, + ); + let (left, top) = ((x_center - 100) as f32, (text_top + 9 + 3) as f32); + batch.fill(atlas, left, top, 200.0, 2.0, opaque(0)); + let done = (progress.clamp(0.0, 1.0) * 200.0).round(); + batch.fill(atlas, left, top, done, 2.0, opaque(0x00FF00)); +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 45e09a6a3..c51aa09ce 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -16,6 +16,7 @@ pub mod banner; pub mod beehive; pub mod benchmark; pub mod biome; +pub mod block_entities; pub mod block_entity_anim; pub mod block_entity_item; pub mod block_entity_nbt; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index fd271f40f..dcf4633a9 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -65,17 +65,9 @@ impl LightTables { } /// Full tables with the vanilla occlusion shapes from `occlusion.nbt`. pub fn load(root: &Path, registry: &BlockRegistry, facts: &BlockFacts) -> crate::Result { - use horizon_world::{ - collision::CachedCollisionRegistry, - nbt::{self, Limits}, - }; - let data = nbt::read_named( - &std::fs::read(root.join("occlusion.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; + use horizon_world::{collision::CachedCollisionRegistry, registry::BlockTableFile}; + let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?; + let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?; let mut tables = Self::new(facts); let block = VoxelShape::block(); let mut shapes: Vec = vec![VoxelShape::empty(), block.clone()]; @@ -165,14 +157,14 @@ impl LightTables { fn edge_occluded(&self, top: usize, bottom: usize) -> bool { self.cells[bottom].dampening != 0 || self.blocked(top, bottom, Direction::Down as usize) } - pub fn emission(&self, state: u16) -> u8 { + pub fn emission(&self, state: u32) -> u8 { self.cells[state as usize].emission } - pub fn dampening(&self, state: u16) -> u8 { + pub fn dampening(&self, state: u32) -> u8 { self.cells[state as usize].dampening } /// Whether a state change can change light (`hasDifferentLightProperties`). - pub fn differs(&self, old: u16, new: u16) -> bool { + pub fn differs(&self, old: u32, new: u32) -> bool { let (a, b) = (&self.cells[old as usize], &self.cells[new as usize]); old != new && (a.dampening != b.dampening || a.emission != b.emission || a.shaped || b.shaped) @@ -211,12 +203,12 @@ pub fn light_chunk( // up to 14 blocks into it (sky light there is always 15). let h = ((top_section + 1) * 16).min(HEIGHT as usize); let at = |x: usize, y: usize, z: usize| (y * W + z) * W + x; - let mut states = vec![0u16; W * W * h]; + let mut states = vec![0u32; W * W * h]; let mut sky = vec![0u8; W * W * h]; let mut block = vec![0u8; W * W * h]; let mut queue = VecDeque::new(); let mut sky_queue = VecDeque::new(); - let mut ids = Box::new([0u16; 4096]); + let mut ids = Box::new([0u32; 4096]); for (dz, row) in region.iter().enumerate() { for (dx, chunk) in row.iter().enumerate() { let Some(chunk) = chunk else { continue }; @@ -391,13 +383,13 @@ pub fn apply_relighting(chunk: &mut Chunk, lights: Vec) -> Vec<(i32, i32, /// Resident chunks the incremental relighter reads and writes. pub trait LightWorld { - fn state(&self, x: i32, y: i32, z: i32) -> Option; + fn state(&self, x: i32, y: i32, z: i32) -> Option; /// Packed light (sky << 4 | block), None outside loaded chunks. fn light(&self, x: i32, y: i32, z: i32) -> Option; fn set_light(&mut self, x: i32, y: i32, z: i32, packed: u8); } impl LightWorld for HashMap<(i32, i32), Arc, S> { - fn state(&self, x: i32, y: i32, z: i32) -> Option { + fn state(&self, x: i32, y: i32, z: i32) -> Option { if !(MIN_Y..MIN_Y + HEIGHT).contains(&y) { return None; } @@ -611,10 +603,10 @@ fn relight_layer( mod tests { use super::*; - const AIR: u16 = 0; - const STONE: u16 = 1; - const TORCH: u16 = 2; - const SLAB: u16 = 3; + const AIR: u32 = 0; + const STONE: u32 = 1; + const TORCH: u32 = 2; + const SLAB: u32 = 3; /// Air, stone, torch and a bottom slab (full bottom face, half sides, /// empty top), with a third face shape for the half sides. fn tables() -> LightTables { @@ -889,7 +881,7 @@ mod tests { for (si, s) in fixture.sections.iter_mut().enumerate() { let section = Arc::make_mut(s); for i in 0..4096 { - section.set(i, ((i + si) % 16) as u16); + section.set(i, ((i + si) % 16) as u32); } for i in 0..64 { section.biomes.set(i, (i % 4) as u32); diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 5e57edcfc..64286b1fe 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -1668,6 +1668,18 @@ impl Menu { env: &Env, clicked: usize, moved: &ItemStack, + ) -> Result<(), &'static str> { + self.quick_move_all_each(env, clicked, moved, &mut |_, _| {}) + } + + /// `quick_move_all`, calling `each` with the menu and the slot after each + /// QUICK_MOVE (a server's client sends every one of them). + pub fn quick_move_all_each( + &mut self, + env: &Env, + clicked: usize, + moved: &ItemStack, + each: &mut dyn FnMut(&Self, usize), ) -> Result<(), &'static str> { if clicked >= self.slots.len() || !self.can_take_for_pick_all(clicked) { return Ok(()); @@ -1680,6 +1692,7 @@ impl Menu { && self.quick_replace(t, moved, env) { self.click(env, t as i32, 0, Input::QuickMove)?; + each(self, t); } } Ok(()) diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index 7f1191126..c3990f598 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -434,17 +434,17 @@ fn pi(x: i32, y: i32, z: i32) -> usize { } /// Blocks and light of one section plus a `B`-block border. struct Padded { - blocks: Vec, + blocks: Vec, light: Vec, } impl Padded { fn new(region: &[[Option<&Chunk>; 3]; 3], sy: i32) -> Self { - let mut blocks = vec![0u16; P * P * P]; + let mut blocks = vec![0u32; P * P * P]; let mut light = vec![0u8; P * P * P]; let base_y = MIN_Y + sy * 16; // The section itself is unpacked in one pass; the border cells of the // neighbouring sections are read one by one. - let mut own = Box::new([0u16; 4096]); + let mut own = Box::new([0u32; 4096]); let center = region[1][1].map(|c| &c.sections[sy as usize]); if let Some(section) = center { section.unpack(&mut own); @@ -643,10 +643,8 @@ impl Mesher<'_> { } let state = &info[id as usize]; if state.block_entity { - out.block_entities.push(( - [center.x * 16 + x, base_y + y, center.z * 16 + z], - u32::from(id), - )); + out.block_entities + .push(([center.x * 16 + x, base_y + y, center.z * 16 + z], id)); } if state.solid && Direction::ALL.iter().all(|d| { @@ -665,10 +663,7 @@ impl Mesher<'_> { continue; } let world = BlockPos::new(center.x * 16 + x, base_y + y, center.z * 16 + z); - let Ok(models) = self - .assets - .model_catalog - .collect(BlockStateId(id.into()), world) + let Ok(models) = self.assets.model_catalog.collect(BlockStateId(id), world) else { continue; }; @@ -700,8 +695,8 @@ impl Mesher<'_> { && self .visibility .should_render_face( - BlockStateId(id.into()), - BlockStateId(neighbor.into()), + BlockStateId(id), + BlockStateId(neighbor), d, true, ) diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index 41b1e200e..c29f2b92c 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -159,28 +159,28 @@ struct FlowView<'a> { info: &'a [Info], } impl FlowView<'_> { - fn id(&self, p: BlockPos) -> u16 { + fn id(&self, p: BlockPos) -> u32 { self.pad.blocks[pi(p.x, p.y, p.z)] } } impl FluidFlowWorld for FlowView<'_> { type Error = Infallible; - type Block = u16; + type Block = u32; fn fluid(&mut self, p: BlockPos) -> Result { Ok(self.info[self.id(p) as usize].fluid) } - fn block(&mut self, p: BlockPos) -> Result { + fn block(&mut self, p: BlockPos) -> Result { Ok(self.id(p)) } - fn blocks_fluid_flow(&self, state: u16) -> bool { + fn blocks_fluid_flow(&self, state: u32) -> bool { self.info[state as usize].blocks_flow } - fn is_ice_class(&self, state: u16) -> bool { + fn is_ice_class(&self, state: u32) -> bool { self.info[state as usize].ice } fn is_face_sturdy( &mut self, - state: u16, + state: u32, _: BlockPos, d: Direction, ) -> Result { diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs index 16ea98cef..9369a1ba2 100644 --- a/crates/horizon-client/src/mesher/leaf_culling_tests.rs +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -13,12 +13,12 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); let biomes = Biomes::load(&root).unwrap(); - let state = |name| assets.registry.default_state(name).unwrap().0 as u16; + let state = |name| assets.registry.default_state(name).unwrap().0; let oak = state("minecraft:oak_leaves"); let birch = state("minecraft:birch_leaves"); let roots = state("minecraft:mangrove_roots"); let stone = state("minecraft:stone"); - let mesh = |blocks: &[([i32; 3], u16)], cull_leaves, cutout_leaves| { + let mesh = |blocks: &[([i32; 3], u32)], cull_leaves, cutout_leaves| { let mut center = Chunk::empty(0, 0); let mut east = Chunk::empty(1, 0); for &([x, y, z], state) in blocks { @@ -51,7 +51,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { let vertices = mesh(&[(at, id)], false, true); let models = assets .model_catalog - .collect(BlockStateId(id.into()), BlockPos::new(at[0], at[1], at[2])) + .collect(BlockStateId(id), BlockPos::new(at[0], at[1], at[2])) .unwrap(); let faces: Vec<_> = models.iter().flat_map(|(_, model)| &model.faces).collect(); assert_eq!(vertices.len(), faces.len() * 4); diff --git a/crates/horizon-client/src/mesher/visibility_tests.rs b/crates/horizon-client/src/mesher/visibility_tests.rs index 2f95c45cf..32eb4800c 100644 --- a/crates/horizon-client/src/mesher/visibility_tests.rs +++ b/crates/horizon-client/src/mesher/visibility_tests.rs @@ -105,7 +105,7 @@ fn fixture(mut opaque: impl FnMut(i32, i32, i32) -> bool) -> Padded { for y in 0..16 { for z in 0..16 { for x in 0..16 { - pad.blocks[pi(x, y, z)] = u16::from(opaque(x, y, z)) + 2 * ((x + y + z) as u16 & 1); + pad.blocks[pi(x, y, z)] = u32::from(opaque(x, y, z)) + 2 * ((x + y + z) as u32 & 1); } } } diff --git a/crates/horizon-client/src/minimap.rs b/crates/horizon-client/src/minimap.rs index 8015e2ab2..8b250e1af 100644 --- a/crates/horizon-client/src/minimap.rs +++ b/crates/horizon-client/src/minimap.rs @@ -75,8 +75,8 @@ impl Palette { } } #[inline] - fn get(&self, id: u16) -> (u8, u8) { - let i = usize::from(id); + fn get(&self, id: u32) -> (u8, u8) { + let i = id as usize; ( self.color.get(i).copied().unwrap_or(0), self.flags.get(i).copied().unwrap_or(AIR), @@ -137,7 +137,7 @@ fn scan_column( (0, MIN_Y as i16, 0) } /// The highest block of a chunk worth scanning from. -fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { +fn top_of(chunk: &Chunk, air: u32, layer: Layer) -> i32 { let surface = (0..SECTIONS) .rev() .find(|&s| { @@ -152,7 +152,7 @@ fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 { Layer::Below(head) => surface.min(head), } } -fn scan_tile(chunk: &Chunk, palette: &Palette, air: u16, layer: Layer, revision: u64) -> Tile { +fn scan_tile(chunk: &Chunk, palette: &Palette, air: u32, layer: Layer, revision: u64) -> Tile { let top = top_of(chunk, air, layer); let mut tile = Tile { color: [0; 256], @@ -287,7 +287,7 @@ impl Minimap { ) -> usize { let palette = self.palette.get_or_insert_with(|| Palette::new(facts)); let started = Instant::now(); - let air = world.air.0 as u16; + let air = world.air.0; // Tiles of unloaded or distant chunks go. self.tiles.retain(|k, _| { (k.0 - center.0).abs() <= radius + 2 @@ -417,7 +417,7 @@ mod tests { (LAVA, 2), ]) } - fn chunk(columns: &[(i32, i32, &[(i32, u16)])]) -> Chunk { + fn chunk(columns: &[(i32, i32, &[(i32, u32)])]) -> Chunk { let mut c = Chunk::empty(0, 0); for &(x, z, blocks) in columns { for &(y, id) in blocks { @@ -467,7 +467,7 @@ mod tests { fn below_a_height_shows_the_floor_and_cuts_walls() { let p = palette(); // A cave: stone everywhere from 0 to 20, air at 10 and 11 in column 0. - let mut blocks: Vec<(i32, u16)> = (0..=20).map(|y| (y, 2)).collect(); + let mut blocks: Vec<(i32, u32)> = (0..=20).map(|y| (y, 2)).collect(); let solid = blocks.clone(); blocks.retain(|&(y, _)| y != 10 && y != 11); let c = chunk(&[(0, 0, &blocks), (1, 0, &solid)]); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 8b51593bc..3fe743fab 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -686,10 +686,16 @@ pub struct Extra { pub legs: Option>, pub feet: Option>, pub using_item: i32, + pub using_off_hand: bool, + pub blocking: bool, pub fall_flying: bool, pub fall_fly_ticks: i32, pub main_hand_left: bool, pub elytra: ElytraAnimation, + pub swim: SwimAnimation, + /// The arm the current swing moves (`currentSwing.hand().asArm`): `Some(true)` + /// for the right arm. + pub swing_right_arm: Option, pub flag: bool, pub flag2: bool, /// Species scratch values (the wither's head targets and clocks). @@ -807,6 +813,8 @@ pub struct Mob { /// Entity.wasEyeInWater: the eyes were in water before this tick's fluid /// update (`isUnderWater` reads it). pub was_eye_in_water: bool, + /// `Entity.firstTick`: no splash for a mob that appears in water. + pub first_tick: bool, pub no_gravity: bool, /// `Entity.mainSupportingBlockPos`: the block it stood on after its last /// move. @@ -1392,6 +1400,9 @@ pub struct PlayerView { /// The mobs on the player's team (`isAlliedTo`): combat targeting /// leaves the player alone. pub allies: std::sync::Arc>, + /// A LAN guest: its own client moves it, and touching mobs push it there + /// (`EntitySelector.pushableBy` on the client). + pub remote: bool, } pub struct MobWorld<'a> { pub world: &'a World, @@ -1484,6 +1495,7 @@ impl Mob { extra: Extra::default(), fluids: living::Fluids::default(), was_eye_in_water: false, + first_tick: true, no_gravity: false, supporting: None, no_ai: false, @@ -2068,6 +2080,35 @@ impl ElytraAnimation { } } +/// `LivingEntity.swimAmount` and the render state the swimming pose reads +/// (`isVisuallySwimming`, `isInWater`). +#[derive(Clone, Copy, Debug, Default)] +pub struct SwimAnimation { + pub old: f32, + pub amount: f32, + /// `isVisuallySwimming`: in the swimming pose (or still in the gliding + /// pose after a glide ended). + pub visually: bool, + pub in_water: bool, +} +impl SwimAnimation { + /// `LivingEntity.updateSwimAmount`. + pub fn tick(&mut self, visually: bool, in_water: bool) { + self.old = self.amount; + self.amount = if visually { + (self.amount + 0.09).min(1.0) + } else { + (self.amount - 0.09).max(0.0) + }; + self.visually = visually; + self.in_water = in_water; + } + /// `LivingEntity.getSwimAmount`. + pub fn amount(&self, partial: f32) -> f32 { + self.old + partial * (self.amount - self.old) + } +} + #[cfg(test)] mod elytra_tests { use super::*; diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index 318b37d5c..f74a3c7d1 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -225,6 +225,22 @@ pub fn register(m: &mut Mob) { Family::Bat => super::bat::register(m), Family::Bee => super::bee::register(m), } + // FloatGoal's constructor lets the navigation float, as do the + // constructors of these brain-driven and flying mobs. A floater rises + // 0.04 a tick in Mob.jumpInLiquid, the others 0.3 (the bounce of #542). + if m.ai.goals.has("Float") + || matches!( + m.species(), + Species::Allay + | Species::Armadillo + | Species::Camel + | Species::Goat + | Species::Parrot + | Species::Wither + ) + { + m.ai.nav.can_float = true; + } } /// Mob.tick additions that run before the entity tick (creeper fuse, puffing). fn pre_tick(m: &mut Mob, events: &mut Vec) { @@ -428,10 +444,7 @@ fn tick_swing(m: &mut Mob) { /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { m.was_eye_in_water = m.fluids.eye_in_water; - m.fluids = w.fluids(m.bounds(), m.eye_y()); - if m.fluids.in_water { - m.fall_distance = 0.0; - } + m.update_fluids(w, events); let fire = crate::motion::environment::fire_contact(w.world, w.registry, m.bounds()); if fire > 0.0 { m.ticks_frozen = 0; @@ -474,6 +487,7 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec) { if m.position.y < f64::from(crate::chunk::MIN_Y - 64) { m.damage(4.0, Damage::of(DamageKind::OutOfWorld)); } + m.first_tick = false; if m.alive() { // LivingEntity.baseTick: suffocation inside full blocks. let (ex, ey, ez) = ( @@ -808,10 +822,14 @@ fn push_entities(m: &mut Mob, w: &MobWorld, events: &mut Vec) { za *= pow; xa *= f64::from(0.05_f32); za *= f64::from(0.05_f32); - events.push(MobEvent::Push { - target: who, - velocity: [-xa, 0.0, -za], - }); + // A guest's server-side push never reaches its client (ServerPlayer + // motion is synced only when hurt): its client pushes it itself. + if who != Who::Player || w.player.as_ref().is_none_or(|p| !p.remote) { + events.push(MobEvent::Push { + target: who, + velocity: [-xa, 0.0, -za], + }); + } if self_pushable { m.velocity = Vec3::new(m.velocity.x + xa, m.velocity.y, m.velocity.z + za); } diff --git a/crates/horizon-client/src/mobs/anim.rs b/crates/horizon-client/src/mobs/anim.rs index 161db24f9..1410bf858 100644 --- a/crates/horizon-client/src/mobs/anim.rs +++ b/crates/horizon-client/src/mobs/anim.rs @@ -4,7 +4,7 @@ use super::{Mob, Part, keyframes::AnimationState, living::wrap}; use horizon_core::geometry::trig::Mth; use std::collections::HashMap; -use std::f32::consts::PI; +use std::f32::consts::{FRAC_PI_6, PI}; /// The setupAnim implementation a model uses. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -232,9 +232,12 @@ fn bob(p: &mut Poses, n: &str, age: f32, scale: f32) { pub enum ArmPose { Empty, Item, + Block, Bow, CrossbowHold, CrossbowCharge, + /// Raising a trident to throw it (or to launch with Riptide). + ThrowTrident, } /// HumanoidModel.setupAnim for piglins: `PiglinModel` poses the arms itself. pub fn humanoid_item(p: &mut Poses, s: &State, _holding: bool) { @@ -276,6 +279,12 @@ pub struct Hum { pub charge: (f32, f32), /// `PiglinModel.setupAttackAnimation`: swing a held weapon down. pub weapon_swing: bool, + /// `swimAmount` at this frame. + pub swim: f32, + /// `isUsingItem`: the swim stroke leaves the arms alone. + pub using_item: bool, + /// The arm the current swing moves (`Some(true)` for the right one). + pub swing_right_arm: Option, } impl Hum { pub fn new(right: ArmPose, left: ArmPose) -> Self { @@ -290,6 +299,9 @@ impl Hum { holding: false, charge: (0.0, 0.0), weapon_swing: false, + swim: 0.0, + using_item: false, + swing_right_arm: None, } } } @@ -298,7 +310,7 @@ impl ArmPose { matches!(self, Self::Bow | Self::CrossbowHold | Self::CrossbowCharge) } fn affects_offhand(self) -> bool { - self.two_handed() + self.two_handed() || self == Self::ThrowTrident } } /// `AnimationUtils.animateCrossbowHold`. @@ -344,12 +356,25 @@ fn pose_arm(p: &mut Poses, pose: ArmPose, right: bool, h: &Hum) { p.xrot(arm, x * 0.5 - PI / 10.0); p.yrot(arm, 0.0); } + ArmPose::Block => { + let x = p.get(arm)[3] * 0.5 - 0.942_477_9 + hx.clamp(-1.396_263_4, 0.436_332_32); + p.xrot(arm, x); + p.yrot( + arm, + if right { -FRAC_PI_6 } else { FRAC_PI_6 } + hy.clamp(-FRAC_PI_6, FRAC_PI_6), + ); + } ArmPose::Bow => { p.yrot("right_arm", -0.1 + hy - if right { 0.0 } else { 0.4 }); p.yrot("left_arm", 0.1 + hy + if right { 0.4 } else { 0.0 }); p.xrot("right_arm", -PI / 2.0 + hx); p.xrot("left_arm", -PI / 2.0 + hx); } + ArmPose::ThrowTrident => { + let x = p.get(arm)[3]; + p.xrot(arm, x * 0.5 - PI); + p.yrot(arm, 0.0); + } ArmPose::CrossbowHold => crossbow_hold(p, hx, hy, right), ArmPose::CrossbowCharge => crossbow_charge(p, h.charge.0, h.charge.1, right), } @@ -435,12 +460,17 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { let xm = ((1.0 - (1.0 - swing) * (1.0 - swing)) * PI).msin(); let x = drop + ym * 1.2 - xm * 0.4; let y = 0.1 - ym * 0.6; - p.xrot("right_arm", x); - p.yrot("right_arm", if raise { -y } else { y }); - p.zrot("right_arm", 0.0); - p.xrot("left_arm", x); - p.yrot("left_arm", if raise { y } else { -y }); - p.zrot("left_arm", 0.0); + // An arm raising a trident keeps its pose. + if h.right != ArmPose::ThrowTrident { + p.xrot("right_arm", x); + p.yrot("right_arm", if raise { -y } else { y }); + p.zrot("right_arm", 0.0); + } + if h.left != ArmPose::ThrowTrident { + p.xrot("left_arm", x); + p.yrot("left_arm", if raise { y } else { -y }); + p.zrot("left_arm", 0.0); + } } if h.crouching { p.xrot("body", 0.5); @@ -455,6 +485,86 @@ pub(super) fn humanoid(p: &mut Poses, s: &State, h: &Hum) { } bob(p, "right_arm", s.age, 1.0); bob(p, "left_arm", s.age, -1.0); + if h.swim > 0.0 { + swim(p, s.pos, h); + } +} +/// `Mth.rotLerpRad`. +fn rot_lerp_rad(a: f32, from: f32, to: f32) -> f32 { + let mut diff = to - from; + while diff < -PI { + diff += PI * 2.0; + } + while diff >= PI { + diff -= PI * 2.0; + } + from + a * diff +} +/// `HumanoidModel.setupSwimAnimation`: the stroke of both arms over 26 +/// walk-animation units, the head down and a slow flutter kick. The left arm +/// eases the short way round, the right one linearly, as in vanilla. +fn swim(p: &mut Poses, pos: f32, h: &Hum) { + let amount = h.swim; + if !h.fall_flying { + let x = p.get("head")[3]; + p.xrot( + "head", + rot_lerp_rad(amount, x, -std::f32::consts::FRAC_PI_4), + ); + } + let swim_pos = pos % 26.0; + let right_amount = if h.swing_right_arm == Some(true) { + 0.0 + } else { + amount + }; + let left_amount = if h.swing_right_arm == Some(false) { + 0.0 + } else { + amount + }; + let lerp = |a: f32, from: f32, to: f32| from + a * (to - from); + let quadratic = |x: f32| -65.0 * x + x * x; + if !h.using_item { + // Targets (x, y, z) for the left and right arm. + let targets = if swim_pos < 14.0 { + let stroke = 1.870_796_4 * quadratic(swim_pos) / quadratic(14.0); + Some(([0.0, PI, PI + stroke], [0.0, PI, PI - stroke])) + } else if swim_pos < 22.0 { + let t = (swim_pos - 14.0) / 8.0; + let x = PI / 2.0 * t; + Some(( + [x, PI, 5.012_389 - 1.870_796_4 * t], + [x, PI, 1.270_796_3 + 1.870_796_4 * t], + )) + } else if swim_pos < 26.0 { + let t = (swim_pos - 22.0) / 4.0; + let x = PI / 2.0 - PI / 2.0 * t; + Some(([x, PI, PI], [x, PI, PI])) + } else { + None + }; + if let Some((left, right)) = targets { + for (i, target) in left.into_iter().enumerate() { + let angle = &mut p.get("left_arm")[3 + i]; + *angle = rot_lerp_rad(left_amount, *angle, target); + } + for (i, target) in right.into_iter().enumerate() { + let angle = &mut p.get("right_arm")[3 + i]; + *angle = lerp(right_amount, *angle, target); + } + } + } + let x = p.get("left_leg")[3]; + p.xrot( + "left_leg", + lerp(amount, x, 0.3 * (pos * 0.333_333_34 + PI).mcos()), + ); + let x = p.get("right_leg")[3]; + p.xrot( + "right_leg", + lerp(amount, x, 0.3 * (pos * 0.333_333_34).mcos()), + ); } /// Apply the mob's model animation to `p`. pub fn setup( @@ -526,7 +636,21 @@ pub fn setup( | Anim::ZombieVillager | Anim::ZombifiedPiglin | Anim::Humanoid { zombie_arms: true } => { - let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + // DrownedRenderer.getArmPose: an aggressive drowned raises the + // trident in its main arm. + let throwing = m.kind.anim == Anim::Drowned + && m.ai.aggressive + && m.extra.main_hand.as_deref() == Some("minecraft:trident"); + let main = if throwing { + ArmPose::ThrowTrident + } else { + ArmPose::Empty + }; + let mut h = if m.extra.main_hand_left { + Hum::new(ArmPose::Empty, main) + } else { + Hum::new(main, ArmPose::Empty) + }; h.zombie = Some(m.ai.aggressive); h.holding = m.extra.main_hand.is_some(); h.crouching = m.extra.crouching; @@ -546,10 +670,13 @@ pub fn setup( } else { ArmPose::Empty }; + let using_main = m.extra.using_item > 0 && !m.extra.using_off_hand; let pose = if player { match m.extra.main_hand.as_deref() { - Some("minecraft:bow") if m.extra.using_item > 0 => ArmPose::Bow, - Some("minecraft:crossbow") if m.extra.using_item > 0 && !m.extra.charged => { + Some(_) if using_main && m.extra.blocking => ArmPose::Block, + Some("minecraft:bow") if using_main => ArmPose::Bow, + Some("minecraft:trident") if using_main => ArmPose::ThrowTrident, + Some("minecraft:crossbow") if using_main && !m.extra.charged => { ArmPose::CrossbowCharge } Some("minecraft:crossbow") if m.extra.charged && s.swing == 0.0 => { @@ -561,8 +688,12 @@ pub fn setup( } else { right }; - let off = if player && m.extra.off_hand.is_some() && !pose.two_handed() { - ArmPose::Item + let off = if player && m.extra.off_hand.is_some() && !pose.affects_offhand() { + if m.extra.using_item > 0 && m.extra.using_off_hand && m.extra.blocking { + ArmPose::Block + } else { + ArmPose::Item + } } else { ArmPose::Empty }; @@ -580,6 +711,9 @@ pub fn setup( } h.crouching = m.extra.crouching; h.passenger = m.extra.passenger; + h.swim = m.extra.swim.amount(s.partial); + h.using_item = m.extra.using_item > 0; + h.swing_right_arm = m.extra.swing_right_arm; humanoid(p, s, &h); if m.ai.aggressive && !bow { // SkeletonModel melee pose. @@ -672,6 +806,42 @@ pub fn setup( #[cfg(test)] mod flight_pose_tests { use super::*; + + #[test] + fn blocking_arm_follows_the_head_with_limits_in_both_hands() { + for right in [false, true] { + for (pitch, yaw, expected_pitch, expected_yaw) in [ + (0.0, 0.0, -0.742_477_9, 0.0), + (2.0, 2.0, -0.306_145_58, FRAC_PI_6), + (-2.0, -2.0, -2.138_741_3, -FRAC_PI_6), + ] { + let mut p = Poses { + map: ["head", "right_arm", "left_arm"] + .into_iter() + .map(|n| (n.to_string(), [0.0; 9])) + .collect(), + dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), + }; + let arm = if right { "right_arm" } else { "left_arm" }; + p.xrot("head", pitch); + p.yrot("head", yaw); + p.xrot(arm, 0.4); + pose_arm( + &mut p, + ArmPose::Block, + right, + &Hum::new(ArmPose::Empty, ArmPose::Empty), + ); + let pose = *p.get(arm); + assert!((pose[3] - expected_pitch).abs() < 1e-6); + let side = if right { -FRAC_PI_6 } else { FRAC_PI_6 }; + assert!((pose[4] - (side + expected_yaw)).abs() < 1e-6); + assert_eq!(p.get(if right { "left_arm" } else { "right_arm" })[3], 0.0); + } + } + } #[test] fn flight_slows_limbs_and_sets_the_head_pose() { let state = State { @@ -709,5 +879,74 @@ mod flight_pose_tests { humanoid(&mut flight, &state, &h); assert_eq!(flight.get("head")[3], -std::f32::consts::FRAC_PI_4); assert_eq!(flight.get("right_leg")[3], ground.get("right_leg")[3] / 8.0); + // THROW_TRIDENT: the arm goes up over the head, and zombie arms leave it there. + let mut throw = make(); + let mut h = Hum::new(ArmPose::ThrowTrident, ArmPose::Item); + h.zombie = Some(true); + humanoid(&mut throw, &state, &h); + let still = (state.pos * 0.6662 + PI).mcos() * 2.0 * 0.5; + assert_eq!(throw.get("right_arm")[3], still * 0.5 - PI); + assert_eq!(throw.get("right_arm")[4], 0.0); + assert_eq!(throw.get("left_arm")[3], -PI / 1.5); + } + + #[test] + fn swimming_strokes_the_arms_and_kicks() { + let state = State { + pos: 7.0, + speed: 1.0, + age: 0.0, + y_rot: 0.0, + x_rot: 30.0, + swing: 0.0, + baby: false, + partial: 0.0, + }; + let make = || Poses { + map: ["head", "right_arm", "left_arm", "right_leg", "left_leg"] + .into_iter() + .map(|n| (n.to_string(), [0.0; 9])) + .collect(), + dummy: [0.0; 9], + skipped: Default::default(), + hidden: Default::default(), + }; + let same_angle = |a: f32, b: f32| ((a - b + PI).rem_euclid(PI * 2.0) - PI).abs() < 1e-5; + let mut h = Hum::new(ArmPose::Empty, ArmPose::Empty); + h.swim = 1.0; + let mut p = make(); + humanoid(&mut p, &state, &h); + // Mid-stroke: both arms sweep out from overhead by the quadratic. + let stroke = 1.870_796_4 * (-65.0 * 7.0 + 49.0) / (-65.0 * 14.0 + 196.0); + assert_eq!(p.get("right_arm")[5], PI - stroke); + assert!(same_angle(p.get("left_arm")[5], PI + stroke)); + assert_eq!(p.get("right_arm")[4], PI); + assert!(same_angle(p.get("head")[3], -std::f32::consts::FRAC_PI_4)); + assert!(same_angle( + p.get("right_leg")[3], + 0.3 * (7.0f32 * 0.333_333_34).mcos() + )); + // Using an item keeps the arms; a swing frees its own arm only. + let mut using = make(); + h.using_item = true; + humanoid(&mut using, &state, &h); + assert_eq!(using.get("right_arm")[4], 0.0); + h.using_item = false; + h.swing_right_arm = Some(true); + let mut swinging = make(); + humanoid( + &mut swinging, + &State { + swing: 0.5, + ..state + }, + &h, + ); + assert!(swinging.get("right_arm")[4] < 1.0); + assert!(same_angle(swinging.get("left_arm")[4], PI)); + // Out of the pose nothing changes. + let mut dry = make(); + humanoid(&mut dry, &state, &Hum::new(ArmPose::Empty, ArmPose::Empty)); + assert_eq!(dry.get("head")[3], 30.0f32.to_radians()); } } diff --git a/crates/horizon-client/src/mobs/equine.rs b/crates/horizon-client/src/mobs/equine.rs index 46d33b576..e7d73f0fa 100644 --- a/crates/horizon-client/src/mobs/equine.rs +++ b/crates/horizon-client/src/mobs/equine.rs @@ -83,19 +83,33 @@ pub fn register(m: &mut Mob) { return super::llama::register(m); } let tempt = m.kind.tempt.clone(); - let rears = can_rear(m.species()); + let species = m.species(); + let rears = can_rear(species); + let stand_interval = m.kind.ambient_interval; let g = &mut m.ai.goals; - g.add(0, Float); - g.add(1, MountPanic(Panic::new(1.2))); g.add(1, RunAroundLikeCrazy); g.add(2, Breed::new(1.0)); - g.add(3, Tempt::new(1.25, tempt, false)); g.add(4, FollowParent::new(1.0)); g.add(6, Stroll::avoiding_water(0.7)); g.add(7, LookAtPlayer::new(6.0)); g.add(8, RandomLookAround::default()); if rears { - g.add(9, RandomStand { next: -80 }); + // resetStandInterval: -getAmbientStandInterval (400 for every horse). + g.add( + 9, + RandomStand { + next: -stand_interval, + }, + ); + } + // addBehaviourGoals, after the rest: none for the skeleton horse (it + // sinks), no mount panic for the zombie horse. + if species != Species::SkeletonHorse { + g.add(0, Float); + if species != Species::ZombieHorse { + g.add(1, MountPanic(Panic::new(1.2))); + } + g.add(3, Tempt::new(1.25, tempt, false)); } } /// `generateMaxHealth`, `generateSpeed`, `generateJumpStrength` and the coat. @@ -285,7 +299,7 @@ impl Goal for RandomStand { fn can_use(&mut self, m: &mut Mob, _: &mut Cx) -> bool { self.next += 1; if self.next > 0 && m.random.next_int_bound(1000).unwrap_or(1000) < self.next { - self.next = -80; + self.next = -m.kind.ambient_interval; return m.random.next_int_bound(10).unwrap_or(1) == 0; } false diff --git a/crates/horizon-client/src/mobs/goals.rs b/crates/horizon-client/src/mobs/goals.rs index 0d13b0e81..9419a23ba 100644 --- a/crates/horizon-client/src/mobs/goals.rs +++ b/crates/horizon-client/src/mobs/goals.rs @@ -94,6 +94,10 @@ impl GoalSelector { .map(|g| g.goal.name()) .collect() } + /// Whether a goal of this name is registered, running or not. + pub fn has(&self, name: &str) -> bool { + self.goals.iter().any(|g| g.goal.name() == name) + } pub fn is_running(&self, name: &str) -> bool { self.goals .iter() diff --git a/crates/horizon-client/src/mobs/living.rs b/crates/horizon-client/src/mobs/living.rs index 6bf246541..ebbfabf6b 100644 --- a/crates/horizon-client/src/mobs/living.rs +++ b/crates/horizon-client/src/mobs/living.rs @@ -398,10 +398,7 @@ impl Mob { /// (touching water resets the fall), then Entity.checkFallDamage. fn check_fall_damage(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec) { if !self.fluids.in_water { - self.fluids = w.fluids(self.bounds(), self.eye_y()); - if self.fluids.in_water { - self.fall_distance = 0.0; - } + self.update_fluids(w, events); } if !self.fluids.in_water && moved.y < 0.0 { self.fall_distance -= f64::from(moved.y as f32); @@ -413,6 +410,23 @@ impl Mob { self.fall_distance = 0.0; } } + /// Entity.updateFluidInteraction: the fluid state, then touching water + /// resets the fall and entering it (after the first tick) splashes. + pub(super) fn update_fluids(&mut self, w: &MobWorld, events: &mut Vec) { + let was_touching_water = self.fluids.in_water; + self.fluids = w.fluids(self.bounds(), self.eye_y()); + if self.fluids.in_water { + self.fall_distance = 0.0; + if !was_touching_water && !self.first_tick { + // The splash is the mob's own: Horizon's mobs carry no + // controlling passenger here. + let _ = horizon_world::water_splash::water_splash( + &mut Splash { mob: self, events }, + 1_000_000, + ); + } + } + } /// Entity.applyMovementEmissionAndPlaySound: walked distance, footsteps /// and swimming sounds. fn movement_emission(&mut self, w: &MobWorld, moved: Vec3, events: &mut Vec) { @@ -811,7 +825,8 @@ impl Mob { self.velocity.y += if self.species() == super::Species::Bee { 0.01 } else if self.ai.nav.can_float { - 0.04 + // LivingEntity.jumpInLiquid adds 0.04F. + f64::from(0.04_f32) } else { 0.3 }; @@ -915,3 +930,93 @@ fn free_position( let free = allowed_shape.join(&collisions, ShapeOp::ONLY_FIRST).ok()?; free.closest_point(preferred) } + +/// `Entity.doWaterSplashEffect` for a mob: its own random, its splash sound +/// (`getSwimSplashSound`), particles for the client and the SPLASH game event. +struct Splash<'a> { + mob: &'a mut Mob, + events: &'a mut Vec, +} +impl horizon_world::water_splash::WaterSplashWorld for Splash<'_> { + type Error = std::convert::Infallible; + type Entity = (); + type Sound = &'static str; + fn this_entity(&self) {} + fn controlling_passenger(&mut self) -> Result, Self::Error> { + Ok(None) + } + fn velocity(&mut self, _: ()) -> Result { + Ok(self.mob.velocity) + } + fn splash_sound(&mut self, _high_speed: bool) -> Result<&'static str, Self::Error> { + use super::Species; + // Entity.getSwimSplashSound and getSwimHighSpeedSplashSound: the + // overrides are Monster's, the hoglin's, the dolphin's and the axolotl's. + let species = self.mob.species(); + Ok(match species { + Species::Dolphin => "entity.dolphin.splash", + Species::Axolotl => "entity.axolotl.splash", + _ if species == Species::Hoglin || super::ai::is_monster(species) => { + "entity.hostile.splash" + } + _ => "entity.generic.splash", + }) + } + fn random_float(&mut self) -> Result { + Ok(self.mob.random.next_float()) + } + fn random_double(&mut self) -> Result { + Ok(self.mob.random.next_double()) + } + fn play_sound( + &mut self, + sound: &'static str, + volume: f32, + pitch: f32, + ) -> Result<(), Self::Error> { + if !self.mob.silent { + let at = [ + self.mob.position.x, + self.mob.position.y, + self.mob.position.z, + ]; + self.events.push(MobEvent::Sound(sound, at, volume, pitch)); + } + Ok(()) + } + fn position(&self) -> Vec3 { + self.mob.position + } + fn width(&self) -> f32 { + self.mob.width() + } + fn particle( + &mut self, + kind: horizon_world::water_splash::SplashParticle, + position: Vec3, + velocity: Vec3, + ) -> Result<(), Self::Error> { + self.events.push(MobEvent::ParticleAt { + kind: match kind { + horizon_world::water_splash::SplashParticle::Bubble => "bubble", + horizon_world::water_splash::SplashParticle::Splash => "splash", + }, + at: [position.x, position.y, position.z], + velocity: [velocity.x, velocity.y, velocity.z], + }); + Ok(()) + } + fn splash_event(&mut self) -> Result<(), Self::Error> { + self.events.push(MobEvent::GameEvent { + event: "minecraft:splash", + at: [ + self.mob.position.x, + self.mob.position.y, + self.mob.position.z, + ], + source: self.mob.id, + state: horizon_world::registry::BlockStateId(0), + }); + Ok(()) + } +} diff --git a/crates/horizon-client/src/mobs/render.rs b/crates/horizon-client/src/mobs/render.rs index e8120e92e..a0dce0e08 100644 --- a/crates/horizon-client/src/mobs/render.rs +++ b/crates/horizon-client/src/mobs/render.rs @@ -765,6 +765,17 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 .unwrap_or_else(|| glam::Mat4::from_rotation_y((180.0 - body).to_radians())), }; let mut base = origin * rotation; + if m.death_time > 0 && !super::creaking::tearing_down(m) { + let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) + .sqrt() + .min(1.0); + base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); + } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { + // isEntityUpsideDown + base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) + * glam::Mat4::from_rotation_z(PI); + } + // AvatarRenderer.setupRotations, after LivingEntityRenderer's. if m.extra.fall_flying { let ticks = m.extra.fall_fly_ticks as f32 + alpha; let scale = (ticks * ticks / 100.0).min(1.0); @@ -785,17 +796,20 @@ pub fn base_transform_at(m: &Mob, alpha: f32, origin: glam::Mat4) -> glam::Mat4 (sign * horizon_core::jmath::acos(dot.abs().min(1.0))) as f32, ); } - } - - if m.death_time > 0 && !super::creaking::tearing_down(m) { - let f = ((m.death_time as f32 + alpha - 1.0) / 20.0 * 1.6) - .sqrt() - .min(1.0); - base *= glam::Mat4::from_rotation_z(f * flip_degrees(m).to_radians()); - } else if matches!(m.custom_name.as_deref(), Some("Dinnerbone" | "Grumm")) { - // isEntityUpsideDown - base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, m.height() + 0.1, 0.0)) - * glam::Mat4::from_rotation_z(PI); + } else if m.extra.swim.amount(alpha) > 0.0 { + // AvatarRenderer.setupRotations: tip forward with the swim amount, + // following the pitch in water, then lie along the swimming box. + let amount = m.extra.swim.amount(alpha); + let pitch = m.previous_head_pitch + (m.head_pitch - m.previous_head_pitch) * alpha; + let target = if m.extra.swim.in_water { + -90.0 - pitch + } else { + -90.0 + }; + base *= glam::Mat4::from_rotation_x((amount * target).to_radians()); + if m.extra.swim.visually { + base *= glam::Mat4::from_translation(glam::Vec3::new(0.0, -1.0, 0.3)); + } } base *= species_rotations(m, alpha); base *= glam::Mat4::from_scale(glam::Vec3::new(-1.0, -1.0, 1.0)); @@ -1027,17 +1041,24 @@ fn render_visible( .unwrap_or_else(|| m.kind.model.clone()); let mut poses = Poses::new(&model); anim::setup(m, &s, &mut poses, &data.animations); - if let Some(uv) = atlas(&texture) { - draw( - &model, - base, - &poses, - uv, - body_color(m, alpha), - light, - body_overlay(m, alpha), - out, - ); + let draw_body = |out: &mut Vec| { + if let Some(uv) = atlas(&texture) { + draw( + &model, + base, + &poses, + uv, + body_color(m, alpha), + light, + body_overlay(m, alpha), + out, + ); + } + }; + // The translucent shell writes depth: draw the opaque core before it. + let shell_last = m.species() == Species::SulfurCube; + if !shell_last { + draw_body(out); } for (part, uv, color) in extra { draw(part, base, &poses, *uv, *color, light, overlay, out); @@ -1095,6 +1116,9 @@ fn render_visible( } } } + if shell_last { + draw_body(out); + } } /// The equipment slot of a `HumanoidArmorLayer` model (`zombie#helmet`). fn armor_slot(model: &str) -> Option { @@ -1235,3 +1259,93 @@ pub fn held_item_transform( anim::setup(m, &s, &mut poses, &data.animations); hand_base(m, &model, base, &poses, left) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn sulfur_cube_opaque_core_is_submitted_before_its_translucent_shell() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3"); + if !root.join("entity-models.json").exists() { + return; + } + let mut types = super::super::MobTypes::load(&root).unwrap(); + let kind = std::sync::Arc::new(types.types.remove("minecraft:sulfur_cube").unwrap()); + let data = MobData { + states: Vec::new(), + placements: Default::default(), + heightmaps: Default::default(), + animations: Default::default(), + biome_tags: Default::default(), + entity_tags: Default::default(), + villager_hats: Default::default(), + pois: Default::default(), + }; + let atlas = |name: &str| { + Some(if name.contains("_inner") { + [0.0, 0.0, 0.25, 0.25] + } else { + [0.5, 0.5, 0.75, 0.75] + }) + }; + for baby in [false, true] { + let mut mob = Mob::new(1, kind.clone(), horizon_core::geometry::Vec3::ZERO, 0.0); + mob.extra.age = if baby { -24000 } else { 0 }; + super::super::sulfur_cube::finalize(&mut mob); + assert_eq!(mob.is_baby(), baby); + for posed in [false, true] { + let mut vertices = Vec::new(); + if posed { + render_posed( + &mob, + 0.5, + glam::Mat4::IDENTITY, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } else { + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + } + assert_eq!( + vertices.len(), + 48, + "both real six-face models must be drawn" + ); + assert!( + vertices[..24].iter().all(|v| v.uv[0] <= 0.25), + "opaque core must precede shell" + ); + assert!(vertices[24..].iter().all(|v| v.uv[0] >= 0.5)); + } + mob.extra.head = Some("minecraft:stone".into()); + let mut vertices = Vec::new(); + render( + &mob, + 0.5, + glam::DVec3::ZERO, + &atlas, + 0xf0f0, + &data, + &mut vertices, + ); + assert_eq!( + vertices.len(), + 24, + "a swallowed block still hides the default core" + ); + assert!(vertices.iter().all(|v| v.uv[0] >= 0.5)); + } + } +} diff --git a/crates/horizon-client/src/mobs/species.rs b/crates/horizon-client/src/mobs/species.rs index fcfd61992..28ea729b3 100644 --- a/crates/horizon-client/src/mobs/species.rs +++ b/crates/horizon-client/src/mobs/species.rs @@ -1634,7 +1634,16 @@ impl Def { use Species as S; match self.species { S::Turtle => 200, - S::Horse | S::Donkey | S::Mule | S::Llama | S::TraderLlama => 400, + // AbstractHorse.getAmbientSoundInterval, for every subclass. + S::Horse + | S::Donkey + | S::Mule + | S::ZombieHorse + | S::SkeletonHorse + | S::Llama + | S::TraderLlama + | S::Camel + | S::CamelHusk => 400, S::Ocelot => 900, S::Squid | S::GlowSquid diff --git a/crates/horizon-client/src/mobs/tame.rs b/crates/horizon-client/src/mobs/tame.rs index 4e5e3d290..1e725df80 100644 --- a/crates/horizon-client/src/mobs/tame.rs +++ b/crates/horizon-client/src/mobs/tame.rs @@ -855,8 +855,17 @@ impl Goal for CatSitOnBlock { JUMP | MOVE } fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool { + if !m.extra.tame || m.extra.sitting { + return false; + } + // MoveToBlockGoal.canUse draws the next delay only once the last one + // has run out. + if self.0.next_start > 0 { + self.0.next_start -= 1; + return false; + } let next = reduced(200 + m.random.next_int_bound(200).unwrap_or(0)); - m.extra.tame && !m.extra.sitting && self.0.can_use(m, cx.w, next, can_sit_on) + self.0.can_use(m, cx.w, next, can_sit_on) } fn can_continue(&mut self, _: &mut Mob, cx: &mut Cx) -> bool { self.0.can_continue(cx.w, can_sit_on) diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index f78808da7..1cd155297 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -323,7 +323,7 @@ impl<'a> Plan<'a> { } let list: Vec = by_mod.iter().map(|(m, n)| format!("{m} {n}")).collect(); return Err(format!( - "{next} block states, more than the {MAX_STATES} chunks can hold ({} in the game; \ + "{next} block states, more than the {MAX_STATES} a world can hold ({} in the game; \ the mods: {})", names.len(), list.join(", ") @@ -644,9 +644,11 @@ const NBT_TABLES: [&str; 6] = [ /// In a root built here: the content mods' ids, the namespaces loaders /// read besides `minecraft`. const MARKER: &str = "horizon-mod-content.json"; -/// Block states a world can hold: chunk sections store a state in 16 bits -/// (crate::chunk). Mods past it are refused, not wrapped onto other blocks. -pub const MAX_STATES: u32 = 1 << 16; +/// Block states a world can hold. Chunk sections widen their global palette +/// past vanilla's 16 bits to fit the registry (crate::chunk::set_block_states); +/// this caps it at 20 bits, about 29 times vanilla's 35,723 states. Mods past +/// it are refused, not wrapped onto other blocks. +pub const MAX_STATES: u32 = 1 << 20; /// The content mods' namespaces in a root built by [`build`]; none in any /// other root, so vanilla's loaders read exactly what they did. @@ -672,6 +674,28 @@ pub fn tag_namespaces(root: &Path) -> Vec { /// Bundles of block tag files (tag id → the tag file's text). const TAG_BUNDLES: [&str; 2] = ["block-tags.json", "worldgen/block_tags.json"]; +/// The worldgen loader's bundle of biome tags. +const BIOME_TAGS: &str = "worldgen/biome_tags.json"; +/// Worldgen registries a content mod may add to, and the bundle the +/// worldgen loader reads each from (id → the file's text): what structure +/// mods hold. Biomes, noise and density functions change the terrain and +/// are not read from mods. +const WORLDGEN_BUNDLES: [(&str, &str); 6] = [ + ("structure", "worldgen/structures.json"), + ("structure_set", "worldgen/structure_sets.json"), + ("template_pool", "worldgen/template_pools.json"), + ("processor_list", "worldgen/processor_lists.json"), + ("configured_feature", "worldgen/features.json"), + ("placed_feature", "worldgen/placed_features.json"), +]; + +/// A mod file that adds to a worldgen bundle: (bundle, id). +fn worldgen_entry(file: &str) -> Option<(&'static str, String)> { + let (ns, rest) = file.strip_prefix("data/")?.split_once("/worldgen/")?; + let (kind, path) = rest.split_once('/')?; + let (_, bundle) = WORLDGEN_BUNDLES.iter().find(|(k, _)| *k == kind)?; + Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?))) +} /// The overlay being written: `out` mirrors `base` through links, and a /// directory becomes real only when something inside it is written. @@ -771,6 +795,9 @@ fn merge_tag(text: Option<&str>, more: &[J], what: &str) -> Result { struct Known { blocks: std::collections::BTreeSet, items: std::collections::BTreeSet, + /// The worldgen loader's biomes and biome tags. + biomes: std::collections::BTreeSet, + biome_tags: std::collections::BTreeSet, /// `data//tags//.json` files the mods add. tag_files: std::collections::BTreeSet, } @@ -784,14 +811,27 @@ impl Known { items.extend(o.into_iter().map(|(k, _)| k)); } items.extend(plan.items.iter().map(|i| i.rename.to.clone())); + let keys = |name: &str| -> Result> { + Ok(match base.join(name).exists() { + true => match read_json(&base.join(name))? { + J::Obj(o) => o.into_iter().map(|(k, _)| k).collect(), + _ => Default::default(), + }, + false => Default::default(), + }) + }; Ok(Known { blocks, items, + biomes: keys("worldgen/biomes.json")?, + biome_tags: keys(BIOME_TAGS)?, tag_files: tags.keys().cloned().collect(), }) } /// Whether tag `file` keeps entry `v`: a known id or an existing tag, - /// for block and item tags (other registries are kept as they are). + /// for block, item and biome tags (other registries are kept as they + /// are). The worldgen loader refuses a biome tag naming what it lacks + /// (another mod's biomes, a loader's tags), so those entries go. fn keeps(&self, file: &str, v: &J) -> bool { let id = match v { J::Str(s) => s.as_str(), @@ -801,23 +841,32 @@ impl Known { }, _ => return true, }; - let Some(kind) = file + let Some(rest) = file .strip_prefix("data/") .and_then(|r| r.split_once("/tags/")) - .and_then(|(_, rest)| Some(rest.split_once('/')?.0)) + .map(|(_, rest)| rest) else { return true; }; + let kind = match rest.strip_prefix("worldgen/biome/") { + Some(_) => "worldgen/biome", + None => rest.split_once('/').map_or("", |(k, _)| k), + }; let ids = match kind { "block" => &self.blocks, "item" => &self.items, + "worldgen/biome" => &self.biomes, _ => return true, }; match id.strip_prefix('#') { Some(tag) => { let (tns, path) = tag.split_once(':').unwrap_or(("minecraft", tag)); let rel = format!("data/{tns}/tags/{kind}/{path}.json"); - self.tag_files.contains(&rel) || tns == "minecraft" + self.tag_files.contains(&rel) + || match kind { + "worldgen/biome" => self.biome_tags.contains(&format!("{tns}:{path}")), + _ => tns == "minecraft", + } } None => ids.contains(id), } @@ -854,6 +903,7 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { } // Mod files, and every tag addition gathered per tag file. let mut tags: BTreeMap> = BTreeMap::new(); + let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new(); for m in mods { let declarations = format!("data/{}/horizon/", m.id); for file in &m.content.files { @@ -876,6 +926,18 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { .extend(values.iter().cloned()); } else if !file.starts_with(&declarations) { overlay.write(file, &bytes)?; + if let Some((bundle, id)) = worldgen_entry(file) { + let text = String::from_utf8(bytes).map_err(|e| format!("{file}: {e}"))?; + worldgen.entry(bundle).or_default().push((id, text)); + } else if let Some(template) = file + .strip_prefix("data/") + .and_then(|r| r.split_once("/structure/")) + .filter(|(_, path)| path.ends_with(".nbt")) + { + // The worldgen loader's templates: worldgen/structure//.nbt. + let (ns, path) = template; + overlay.write(&format!("worldgen/structure/{ns}/{path}"), &bytes)?; + } } } } @@ -919,6 +981,38 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { for (name, doc) in &bundles { overlay.write(name, &serde_json::to_vec(doc)?)?; } + // Biome tags, merged into the worldgen loader's bundle as block tags are. + let biome_tags: Vec<(String, &Vec)> = tags + .iter() + .filter_map(|(file, values)| { + let (ns, path) = file + .strip_prefix("data/")? + .split_once("/tags/worldgen/biome/")?; + Some((format!("{ns}:{}", path.strip_suffix(".json")?), values)) + }) + .collect(); + if !biome_tags.is_empty() && base.join(BIOME_TAGS).exists() { + let mut doc = read_json(&base.join(BIOME_TAGS))?; + for (id, values) in biome_tags { + let text = match doc.get(&id) { + Some(J::Str(t)) => Some(t.clone()), + _ => None, + }; + doc.set(&id, J::Str(merge_tag(text.as_deref(), values, BIOME_TAGS)?)); + } + overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?; + } + // Structures and the pools, sets, processors and features they use. + for (bundle, entries) in &worldgen { + if !base.join(bundle).exists() { + continue; + } + let mut doc = read_json(&base.join(bundle))?; + for (id, text) in entries { + doc.set(id, J::Str(text.clone())); + } + overlay.write(bundle, &serde_json::to_vec(&doc)?)?; + } // A block without its own blockstate looks like its template, so every // state still has a model. for m in mods { @@ -941,15 +1035,75 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { /// The root to load: `base` itself with no content, else the mods' overlay /// over it, built in `cache/mod-content`. +/// +/// The root is built once and kept: later starts with the same build, base +/// and mod files reuse it. With ATM10's carried mods a build takes about +/// 25 s and peaks above 3 GB, more than everything the game keeps. pub fn resource_root(base: &Path, mods: &[ContentMod], cache: &Path) -> Result { if mods.iter().all(|m| m.content.is_empty()) { return Ok(base.to_owned()); } let out = cache.join("mod-content"); + let stamp = stamp(base, mods)?; + if fs::read(out.join(STAMP)).is_ok_and(|s| s == stamp.as_bytes()) { + return Ok(out); + } build(base, mods, &out)?; + fs::write(out.join(STAMP), stamp)?; Ok(out) } +/// In a root built by [`resource_root`]: what it was built from. +const STAMP: &str = "horizon-mod-content.stamp"; + +/// What a content root is built from: this build of the game, the base's +/// manifest and the tables [`build`] rewrites, and every file of every mod +/// in order. Files count by size and modification time, as build tools do. +fn stamp(base: &Path, mods: &[ContentMod]) -> Result { + use sha2::{Digest, Sha256}; + let meta = |path: &Path| -> Result { + let m = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?; + let modified = m + .modified()? + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + Ok(format!( + "{} {} {}", + path.display(), + m.len(), + modified.as_nanos() + )) + }; + let mut parts = vec!["horizon mod content 1".to_owned()]; + parts.push(meta(&std::env::current_exe()?)?); + let base = std::path::absolute(base)?; + parts.push( + String::from_utf8_lossy(&fs::read(base.join("horizon-resources.json"))?).into_owned(), + ); + for name in JSON_TABLES.iter().chain(&NBT_TABLES).chain(&TAG_BUNDLES) { + if base.join(name).exists() { + parts.push(meta(&base.join(name))?); + } + } + for m in mods { + parts.push(m.id.clone()); + let source = m.content.source(); + if source.is_dir() { + for file in &m.content.files { + parts.push(meta(&source.join(file))?); + } + } else { + parts.push(meta(source)?); + } + } + let mut hasher = Sha256::new(); + for part in &parts { + hasher.update((part.len() as u64).to_le_bytes()); + hasher.update(part.as_bytes()); + } + Ok(format!("{:x}", hasher.finalize())) +} + #[cfg(test)] #[path = "mod_content_tests.rs"] mod tests; diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 7067eef40..614705562 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -266,17 +266,17 @@ fn refuses_unknown_templates_and_vanilla_ids() { } #[test] -fn refuses_more_states_than_chunks_hold() { +fn refuses_more_states_than_a_world_holds() { let Some(base) = prepared() else { return; }; let scratch = std::env::temp_dir().join(format!("horizon-mod-states-{}", std::process::id())); let _ = fs::remove_dir_all(&scratch); let mut m = ruby_mod(&scratch.join("ruby")); - // Redstone wire has 1296 states: 40 copies pass any game's 65536. + // Redstone wire has 1296 states: 810 copies pass 2^20 with any game. let mut wire = m.content.blocks[0].clone(); wire.template = "minecraft:redstone_wire".into(); - for i in 0..40 { + for i in 0..810 { let mut b = wire.clone(); b.id = format!("ruby:wire_{i}"); m.content.blocks.push(b); @@ -284,13 +284,33 @@ fn refuses_more_states_than_chunks_hold() { let e = build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap_err(); assert!( e.to_string() - .contains("more than the 65536 chunks can hold"), + .contains("more than the 1048576 a world can hold"), "{e}" ); assert!(e.to_string().contains("the mods: ruby "), "{e}"); fs::remove_dir_all(&scratch).unwrap(); } +#[test] +fn builds_past_sixteen_bit_states() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-wide-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let mut m = ruby_mod(&scratch.join("ruby")); + // 40 redstone wires: 51,840 states, past 65,536 with vanilla's 35,723. + let mut wire = m.content.blocks[0].clone(); + wire.template = "minecraft:redstone_wire".into(); + for i in 0..40 { + let mut b = wire.clone(); + b.id = format!("ruby:wire_{i}"); + m.content.blocks.push(b); + } + build(&base, std::slice::from_ref(&m), &scratch.join("out")).unwrap(); + fs::remove_dir_all(&scratch).unwrap(); +} + #[test] fn no_content_keeps_the_base_root() { let base = Path::new("/nonexistent/base"); @@ -482,3 +502,119 @@ fn independent_reloads_read_changed_behaviour_json_and_report_invalid_files() { ); fs::remove_dir_all(&scratch).unwrap(); } + +/// A built root is kept for later starts, and built again when a mod's +/// files change. +#[test] +fn content_root_is_reused_until_a_mod_changes() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-reuse-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let m = ruby_mod(&scratch.join("ruby")); + let cache = scratch.join("cache"); + let root = resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(); + // A rebuild starts from an empty folder: this file tells them apart. + let sentinel = root.join("sentinel"); + fs::write(&sentinel, b"").unwrap(); + assert_eq!( + resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(), + root + ); + assert!(sentinel.exists(), "an unchanged mod rebuilt the root"); + let lang = scratch.join("ruby/assets/ruby/lang/en_us.json"); + fs::write(&lang, r#"{"block.ruby.ruby_block": "Ruby Block"}"#).unwrap(); + let file = fs::File::options().write(true).open(&lang).unwrap(); + file.set_modified(std::time::SystemTime::now() + std::time::Duration::from_secs(5)) + .unwrap(); + resource_root(&base, std::slice::from_ref(&m), &cache).unwrap(); + assert!(!sentinel.exists(), "a changed mod kept the old root"); + assert!( + fs::read_to_string(root.join("assets/ruby/lang/en_us.json")) + .unwrap() + .contains("Ruby Block") + ); + let _ = fs::remove_dir_all(&scratch); +} + +/// A structure mod's worldgen reaches the worldgen loader: its structure, +/// set, pool and templates join the bundles, and its biome tag keeps only +/// what the loader knows. +#[test] +fn content_root_carries_a_structure_mod() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-worldgen-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let dir = scratch.join("huts"); + let files = [ + ( + "horizon-mod.toml", + "id = \"huts\"\nname = \"Huts\"\nversion = \"1.0\"\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", + ), + ( + "data/huts/worldgen/structure/hut.json", + r##"{"type": "minecraft:jigsaw", "biomes": "#huts:has_hut", "step": "surface_structures", + "spawn_overrides": {}, "terrain_adaptation": "beard_thin", "start_pool": "huts:hut/start", + "size": 1, "start_height": {"absolute": 0}, "project_start_to_heightmap": "WORLD_SURFACE_WG", + "max_distance_from_center": 80}"##, + ), + ( + "data/huts/worldgen/template_pool/hut/start.json", + r#"{"fallback": "minecraft:empty", "elements": [{"weight": 1, "element": { + "element_type": "minecraft:single_pool_element", "location": "huts:hut", + "projection": "rigid", "processors": "minecraft:empty"}}]}"#, + ), + ( + "data/huts/worldgen/structure_set/huts.json", + r#"{"structures": [{"structure": "huts:hut", "weight": 1}], + "placement": {"type": "minecraft:random_spread", "salt": 7, "spacing": 4, "separation": 2}}"#, + ), + ( + "data/huts/tags/worldgen/biome/has_hut.json", + r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##, + ), + ]; + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + // The template: vanilla's smallest plains house, as the mod's own file. + let house = + base.join("worldgen/structure/minecraft/village/plains/houses/plains_small_house_1.nbt"); + fs::create_dir_all(dir.join("data/huts/structure")).unwrap(); + fs::copy(&house, dir.join("data/huts/structure/hut.nbt")).unwrap(); + let package = horizon_mods::Package::read(&dir).unwrap(); + let m = ContentMod { + id: "huts".into(), + content: Content::read(&dir, &package.manifest).unwrap(), + }; + let root = resource_root(&base, &[m], &scratch.join("cache")).unwrap(); + assert!(root.join("worldgen/structure/huts/hut.nbt").exists()); + let tags: BTreeMap = + serde_json::from_slice(&fs::read(root.join("worldgen/biome_tags.json")).unwrap()).unwrap(); + let hut: serde_json::Value = serde_json::from_str(&tags["huts:has_hut"]).unwrap(); + assert_eq!( + hut["values"], + serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"]) + ); + + let assets = Assets::load(&root).unwrap(); + let biomes = crate::biome::Biomes::load(&root).unwrap(); + let terrain = crate::vanillagen::VanillaTerrain::new( + &root.join("worldgen"), + assets.registry, + &biomes, + 1234, + ) + .unwrap(); + let (name, at) = terrain + .locate(&["huts:hut".to_owned()], [0, 64, 0], 16) + .expect("the mod's structure generates"); + assert_eq!(name, "huts:hut"); + assert!(at[0].abs() < 1024 && at[2].abs() < 1024, "{at:?}"); + let _ = fs::remove_dir_all(&scratch); +} diff --git a/crates/horizon-client/src/model_library.rs b/crates/horizon-client/src/model_library.rs index 7f7852ad0..c6a1a9d87 100644 --- a/crates/horizon-client/src/model_library.rs +++ b/crates/horizon-client/src/model_library.rs @@ -42,25 +42,52 @@ impl ParsedModels { /// Blocks require every referenced resource, including parents. Items instead /// skip broken resources and use the resolver's missing-model fallback. - pub(crate) fn block_library( + pub(crate) fn block_library(&self, root: &Path, pending: Vec) -> Result { + self.block_models(root, pending, false) + } + /// [`Self::block_library`], but a model that does not read takes the + /// built-in missing model, logged, as vanilla's model discovery does + /// ("Missing block model"). Mods' content gets this; vanilla's resources + /// always read. + pub(crate) fn block_library_or_missing( + &self, + root: &Path, + pending: Vec, + ) -> Result { + self.block_models(root, pending, true) + } + fn block_models( &self, root: &Path, mut pending: Vec, + or_missing: bool, ) -> Result { let mut models = BTreeMap::new(); + let mut skipped = std::collections::BTreeSet::new(); while let Some(name) = pending.pop() { - if models.contains_key(&name) { + if models.contains_key(&name) || skipped.contains(&name) { continue; } let model = match self.models.get(&name) { Some(model) => Arc::clone(model), None => { - let (namespace, path) = - name.split_once(':').ok_or("invalid model identifier")?; - let text = fs::read_to_string( - root.join(format!("assets/{namespace}/models/{path}.json")), - )?; - Arc::new(CuboidModel::from_json(&text)?) + let read = || -> Result { + let (namespace, path) = + name.split_once(':').ok_or("invalid model identifier")?; + let text = fs::read_to_string( + root.join(format!("assets/{namespace}/models/{path}.json")), + )?; + Ok(CuboidModel::from_json(&text)?) + }; + match read() { + Ok(model) => Arc::new(model), + Err(e) if or_missing => { + log::warn!("Horizon: missing block model {name}: {e}"); + skipped.insert(name); + continue; + } + Err(e) => return Err(e), + } } }; if let Some(parent) = &model.parent { @@ -141,6 +168,13 @@ mod tests { .to_string() }; assert_eq!(load(&direct), load(&parsed)); + // Mods' content: vanilla's missing model instead of an error. + let lenient = parsed.block_library_or_missing(&fixture.0, vec![name.into()])?; + assert_eq!( + format!("{:?}", lenient.resolve(name)?.elements()), + format!("{:?}", lenient.resolve(MISSING_MODEL)?.elements()), + "{name}" + ); } let items = parsed.into_item_library()?; let block = shared.resolve("horizon:nested/child")?; diff --git a/crates/horizon-client/src/models.rs b/crates/horizon-client/src/models.rs index 110166f29..5979672e9 100644 --- a/crates/horizon-client/src/models.rs +++ b/crates/horizon-client/src/models.rs @@ -117,13 +117,11 @@ pub fn load_visibility( use horizon_world::{ block_render::{FaceVisibility, RenderDefinition, SkipRendering}, collision::CachedCollisionRegistry, - nbt::{self, Limits}, + registry::BlockTableFile, }; use std::{collections::BTreeMap, fs}; - let data = nbt::read_named(&fs::read(root.join("occlusion.nbt"))?, Limits::tables())? - .0 - .tag; - let occlusion = CachedCollisionRegistry::from_nbt(&data, registry)?; + let file = BlockTableFile::open(&root.join("occlusion.nbt"), registry)?; + let occlusion = CachedCollisionRegistry::from_table(file.table("occlusion")?)?; let raw: BTreeMap = serde_json::from_slice(&fs::read(root.join("render-definitions.json"))?)?; let definitions = raw diff --git a/crates/horizon-client/src/models/catalog.rs b/crates/horizon-client/src/models/catalog.rs index ecedd0f95..be550d8c6 100644 --- a/crates/horizon-client/src/models/catalog.rs +++ b/crates/horizon-client/src/models/catalog.rs @@ -136,11 +136,29 @@ impl StateModels { }) .collect::>()?; let possible: Vec = serde_json::from_value(facts["states"].clone())?; - let resource = fs::read_to_string( + // Vanilla's BlockStateModelLoader: a definition that does not + // read or bind is logged and its block gets no model; the other + // blocks still load. + let loaded = fs::read_to_string( root.join(format!("assets/{namespace}/blockstates/{path}.json")), - )?; - let definition = BlockStateDefinition::from_json(&resource)?; - let bound = definition.bind(&schema, &possible)?; + ) + .map_err(|e| e.to_string()) + .and_then(|text| BlockStateDefinition::from_json(&text).map_err(|e| e.to_string())) + .and_then(|definition| { + let bound = definition + .bind(&schema, &possible) + .map_err(|e| e.to_string())?; + Ok((definition, bound)) + }); + let (definition, bound) = match loaded { + Ok(loaded) => loaded, + Err(e) => { + log::warn!( + "Horizon: blockstate definition of {namespace}:{path} not loaded: {e}" + ); + continue; + } + }; let native_order: Vec<_> = by_name .get(name.as_str()) .map(Vec::as_slice) @@ -185,10 +203,14 @@ impl StateModels { } choices.push(CompiledChoices::new(&definition)?); } - let library = models.block_library( - root, - variants.iter().map(|(name, _, _)| name.clone()).collect(), - )?; + let names: Vec = variants.iter().map(|(name, _, _)| name.clone()).collect(); + let library = match models.block_library(root, names.clone()) { + Ok(library) => library, + Err(e) => { + log::warn!("Horizon: block models incomplete ({e}); using the missing model"); + models.block_library_or_missing(root, names)? + } + }; let mut baked = BTreeMap::new(); for (name, turns, lock) in variants { let model = library.resolve(&name)?; @@ -231,14 +253,20 @@ impl StateModels { &self, state: BlockStateId, position: BlockPos, + ) -> Result> { + // Blocks use their position seed; contained/displayed blocks can supply one. + self.collect_seeded(state, position_seed(position)) + } + pub fn collect_seeded( + &self, + state: BlockStateId, + seed: i64, ) -> Result> { let (choice, selected) = self .states .get(&state) .ok_or("unbound gallery block state")?; - // These inspection blocks use Block's default position seed. Blocks with - // specialized model seeds (e.g. two-block structures) need their callbacks. - let mut random = LegacyRandom::new(position_seed(position)); + let mut random = LegacyRandom::new(seed); let mut variants = Vec::new(); self.choices[*choice].collect(selected, &mut random, &mut variants)?; variants diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 0eb79d65c..bb94898e9 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -31,8 +31,7 @@ use horizon_world::{ movement_restitution::{self, RestitutionInput, RestitutionWorld}, movement_statistics::{self, MovementStat, MovementStatisticsWorld}, movement_support::{self, MovementLocation}, - nbt::{self, Limits}, - registry::BlockStateId, + registry::{BlockStateId, BlockTableFile}, world_movement::{self, MovementRequest}, worldgen::tags::TagDefinitions, }; @@ -57,17 +56,27 @@ pub struct MotionResources { pub fluids: FluidResources, } impl MotionResources { + /// [`Self::load_with_facts`] with the block facts decoded here. pub fn load(root: &Path, assets: &Assets) -> Result { + Self::load_with_facts( + root, + assets, + &crate::blocks::BlockFacts::load(root, assets.registry)?, + ) + } + /// The motion tables, with the block facts the game already decoded + /// (decoding `gameplay-facts.json` again costs a second or more and, with + /// a big modpack, hundreds of megabytes while it runs). + pub fn load_with_facts( + root: &Path, + assets: &Assets, + facts: &crate::blocks::BlockFacts, + ) -> Result { let attributes = Arc::new(Catalog::from_json(&serde_json::from_slice(&fs::read( root.join("attributes.json"), )?)?)?); - let data = nbt::read_named( - &fs::read(root.join("movement-properties.nbt"))?, - Limits::tables(), - )? - .0 - .tag; - let properties = MovementProperties::from_nbt(&data, assets.registry)?; + let file = BlockTableFile::open(&root.join("movement-properties.nbt"), assets.registry)?; + let properties = MovementProperties::from_table(file.table("movement")?)?; let bundle: BTreeMap = serde_json::from_slice(&fs::read(root.join("block-tags.json"))?)?; let mut definitions = TagDefinitions::default(); @@ -91,7 +100,7 @@ impl MotionResources { Ok(Self { landing: crate::landing::load(root, &properties)?, health: crate::health::HealthResources::load(root)?, - fluids: FluidResources::load(root, assets)?, + fluids: FluidResources::new(assets, facts)?, attributes, blocks: properties.bind(&MovementTags { fences: tag("minecraft:fences")?, @@ -292,19 +301,26 @@ impl PlayerMotion { && movement.x * movement.x + movement.z * movement.z < limit * limit && sword } - pub fn load_environment_once( + /// Restore login state once; a later respawn starts with fresh health and food. + pub fn load_saved_state_once( &mut self, pending: &mut bool, - extra: Option<&horizon_world::nbt::Tag>, - ) { + level: &crate::save::Level, + ) -> Result<()> { if std::mem::take(pending) { + let extra = level.player_extra.as_ref(); self.fire_ticks = extra .and_then(|t| crate::save::number(t.get("Fire"))) .unwrap_or(-20) as i32; self.air = extra .and_then(|t| crate::save::number(t.get("Air"))) .unwrap_or(300) as i32; + self.set_health(level.health, false)?; + self.health.food.food = level.food; + self.health.food.saturation = level.saturation; + self.flying = level.flying; } + Ok(()) } pub fn set_remaining_fire_ticks(&mut self, ticks: i32) { self.fire_ticks = if self.invulnerable { @@ -2166,8 +2182,13 @@ mod tests { #[test] fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); if !root.join("movement-properties.nbt").exists() { + eprintln!("skipped damage regression: prepared resources unavailable"); return; } let assets = Assets::load(&root).unwrap(); @@ -2195,6 +2216,8 @@ mod tests { .count(), 1 ); + assert_eq!(player.health.hurt_animation_time, 10); + player.health.advance_clock(); player.events.clear(); assert!( !player @@ -2207,9 +2230,14 @@ mod tests { .iter() .any(|e| matches!(e, MotionEvent::HurtSound(_))) ); + assert_eq!( + player.health.hurt_animation_time, 9, + "cooldown hit must not restart animation" + ); for _ in 0..20 { player.health.advance_clock(); } + assert_eq!(player.health.hurt_animation_time, 0); player.invulnerable = true; player.events.clear(); assert!( @@ -2271,16 +2299,62 @@ mod tests { Default::default(), source, 4.0, - Some(shield), + Some(shield.clone()), ) .unwrap(); assert!(!outcome.hurt && outcome.sound && outcome.blocked == 4.0); + assert_eq!( + player.health.hurt.hurt_time, 10, + "preserve server damage bookkeeping" + ); + assert_eq!( + player.health.hurt_animation_time, 0, + "a fully blocked arrow must not animate hurt" + ); assert!( !player .events .iter() .any(|e| matches!(e, MotionEvent::HurtSound(_))) ); + // An unblocked hit after the shield block must still animate normally. + for _ in 0..20 { + player.health.advance_clock(); + } + assert!( + player + .hurt(&resources.health, Default::default(), source, 4.0) + .unwrap() + ); + assert_eq!(player.health.hurt_animation_time, 10); + player.health.advance_clock(); + assert!( + !player + .hurt_blocking( + &resources.health, + Default::default(), + source, + 4.0, + Some(shield) + ) + .unwrap() + .hurt + ); + assert_eq!( + player.health.hurt_animation_time, 9, + "blocking must not erase or restart an existing animation" + ); + let mut starving = PlayerMotion::new(&resources, Vec3::ZERO).unwrap(); + starving.health.food.food = 0; + starving.health.food.timer = 79; + starving + .food_tick(&resources.health, Default::default()) + .unwrap(); + assert_eq!(starving.health.health(), 19.0); + assert_eq!( + starving.health.hurt_animation_time, 10, + "starvation must still animate hurt" + ); } /// Footsteps on the prepared vanilla resources, when they are present: @@ -2329,8 +2403,13 @@ mod tests { #[test] fn resident_water_and_lava_are_not_treated_as_air() { - let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); if !root.join("movement-properties.nbt").exists() { + eprintln!("skipping resident water/lava test: prepared resources unavailable"); return; } let assets = Assets::load(&root).unwrap(); @@ -2536,12 +2615,44 @@ mod tests { ("Fire", horizon_world::nbt::Tag::Short(160)), ("Air", horizon_world::nbt::Tag::Short(8)), ]); + let mut level = crate::save::Level { + health: 13.0, + food: 11, + saturation: 2.25, + player_extra: Some(extra), + flying: true, + ..Default::default() + }; let mut pending = true; - w.player.load_environment_once(&mut pending, Some(&extra)); + w.player + .load_saved_state_once(&mut pending, &level) + .unwrap(); assert_eq!((w.player.fire_ticks, w.player.air), (160, 8)); + assert!(w.player.flying); + assert_eq!( + ( + w.player.health.health(), + w.player.health.food.food, + w.player.health.food.saturation + ), + (13.0, 11, 2.25) + ); let mut respawn = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); - respawn.load_environment_once(&mut pending, Some(&extra)); + respawn.load_saved_state_once(&mut pending, &level).unwrap(); assert_eq!((respawn.fire_ticks, respawn.air), (-20, 300)); + assert!(!respawn.flying); + assert_eq!( + (respawn.health.health(), respawn.health.food.food), + (20.0, 20) + ); + // Reopening another world restores its state, including a saved death. + pending = true; + level.health = 0.0; + w.player + .load_saved_state_once(&mut pending, &level) + .unwrap(); + assert!(w.player.health.dead_or_dying()); + assert!(!pending); w.player.fluids.was_touching_water = false; assert!( w.player.moving_slowly(), diff --git a/crates/horizon-client/src/motion/fluids.rs b/crates/horizon-client/src/motion/fluids.rs index f85f755a9..89affeb64 100644 --- a/crates/horizon-client/src/motion/fluids.rs +++ b/crates/horizon-client/src/motion/fluids.rs @@ -33,8 +33,7 @@ pub struct FluidResources { pub shapes: Mutex, } impl FluidResources { - pub fn load(root: &Path, assets: &Assets) -> Result { - let facts = crate::blocks::BlockFacts::load(root, assets.registry)?; + pub fn new(assets: &Assets, facts: &crate::blocks::BlockFacts) -> Result { Ok(Self { states: FluidStateTable::new(assets.registry)?, sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(), diff --git a/crates/horizon-client/src/options_file.rs b/crates/horizon-client/src/options_file.rs index 339bb0fdf..49c94613f 100644 --- a/crates/horizon-client/src/options_file.rs +++ b/crates/horizon-client/src/options_file.rs @@ -159,7 +159,7 @@ static TABLE: LazyLock> = LazyLock::new(|| { b("reducedDebugInfo", false), def("renderClouds", O(Clouds), V::Int(2)), i("cloudRange", 2, 128, 128), - i("renderDistance", 2, 32, 12), + i("renderDistance", 2, 64, 12), i("simulationDistance", 5, 32, 12), u("screenEffectScale", 1.0), def("soundDevice", O(AnyStr), V::Str(String::new())), diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index 7e2f7e9f1..b0a64c7e5 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -36,6 +36,8 @@ pub enum HRow { Extra(extras::Item), /// Installed mod `i` (`settings.mods.installed`) and its switch. Mod(usize), + /// Opens the directory where Horizon mods are installed. + OpenModFolder, } /// A sidebar section: name, description, rows. pub struct Section { @@ -192,12 +194,15 @@ pub const SECTIONS: &[Section] = &[ name: "Mods", blurb: "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on; check what it may do first.", rows: |s| { + let mut rows = vec![HRow::OpenModFolder]; if s.mods.installed.is_empty() { - return vec![HRow::Header( + rows.push(HRow::Header( "No mods: put .hmod files in the horizon-mods folder", - )]; + )); + } else { + rows.extend((0..s.mods.installed.len()).map(HRow::Mod)); } - (0..s.mods.installed.len()).map(HRow::Mod).collect() + rows }, }, ]; @@ -271,6 +276,25 @@ enum Target { Style(usize), Level(usize), } +struct HorizonScrollbar { + x: f32, + top: f32, + bottom: f32, + max: f32, + thumb: f32, +} +impl HorizonScrollbar { + fn contains(&self, x: f32, y: f32) -> bool { + x >= self.x && x < self.x + 6.0 && y >= self.top && y < self.bottom + } +} +struct HorizonLayout { + sliders: Vec<(Item, f32, f32)>, + scrollbar: Option, +} +fn horizon_batch(framebuffer: [i32; 2]) -> HudBatch { + HudBatch::new([framebuffer[0].max(1) as u32, framebuffer[1].max(1) as u32]) +} impl OptionsUi { fn horizon_rows(&self, s: &Settings, section: usize) -> Vec { let rows = (SECTIONS[section].rows)(s); @@ -289,13 +313,8 @@ impl OptionsUi { .collect() } /// Lay out (and draw, on a real frame) the Horizon options shell. - /// Returns the sliders' tracks (option, x, width) for dragging. - fn horizon_layout( - &mut self, - s: &Settings, - ui: &mut Ui, - backdrop: f32, - ) -> Vec<(Item, f32, f32)> { + /// Returns the sliders' tracks and the scroll area for pointer input. + fn horizon_layout(&mut self, s: &Settings, ui: &mut Ui, backdrop: f32) -> HorizonLayout { let (w, h) = (ui.w, ui.h); if self.in_world { ui.atmosphere(horizon_theme::VEIL, 1.0); @@ -469,6 +488,18 @@ impl OptionsUi { ui.described_row(x, y, &installed.title, "", 0.0, cost, text, cw - 60.0); ui.switch(ROW + i as u64, control_x, y + ROW_H / 2.0, s.mods.is_on(m)); } + HRow::OpenModFolder => { + ui.row(x, y, "Mod folder", "", 0.0); + let label = "Open Folder"; + let bw = ui.button_width(label, false).max(96.0); + ui.button( + ROW + i as u64, + [control_x - bw, y + 12.0, bw, CONTROL], + label, + Button::Secondary, + true, + ); + } HRow::Extra(item) => { let cy = y + ROW_H / 2.0; let id = ROW + i as u64; @@ -532,6 +563,7 @@ impl OptionsUi { .filter(|h| h.rect[1] >= cy0 && h.rect[3] <= cy1) .collect(); ui.hits.extend(kept); + let mut scrollbar = None; if max > 0.0 { // A thin scroll indicator. let track = bottom - top; @@ -545,11 +577,18 @@ impl OptionsUi { 1.5, color::with_alpha(color::MUTED, 0.35), ); + scrollbar = Some(HorizonScrollbar { + x: x + cw + 14.0, + top: top + oy, + bottom: bottom + oy, + max, + thumb: bar, + }); } let _ = ox; ui.opacity = 1.0; ui.offset = (0.0, 0.0); - sliders + HorizonLayout { sliders, scrollbar } } pub(crate) fn draw_horizon( &mut self, @@ -563,28 +602,50 @@ impl OptionsUi { self.horizon_layout(s, &mut ui, backdrop); ui.finish(); } - fn horizon_target(&mut self, s: &Settings, atlas: &HudAtlas, x: f32, y: f32) -> Option { - let mut batch = t::scratch_batch(); + fn horizon_target( + &mut self, + s: &Settings, + atlas: &HudAtlas, + x: f32, + y: f32, + framebuffer: [i32; 2], + ) -> (Option, Option, (f32, f32)) { + let mut batch = horizon_batch(framebuffer); let mut ui = Ui::dry(atlas, &mut batch, (x, y)); - let sliders = self.horizon_layout(s, &mut ui, 1.0); - let hit = ui.hit((x, y))?; + let layout = self.horizon_layout(s, &mut ui, 1.0); + let scrollbar = layout.scrollbar; + // The UI layer transforms raw GUI-pixel input into its own dp. + let cursor = ui.cursor; + let Some(hit) = ui.hit((x, y)) else { + return (None, scrollbar, cursor); + }; if hit == SEARCH { - return Some(Target::Search); + return (Some(Target::Search), scrollbar, cursor); } let section = self.section.min(SECTIONS.len() - 1); if (NAV..NAV + SECTIONS.len() as u64).contains(&hit) { - return Some(Target::Nav((hit - NAV) as usize)); + return (Some(Target::Nav((hit - NAV) as usize)), scrollbar, cursor); } if hit == DONE { - return Some(Target::Done); + return (Some(Target::Done), scrollbar, cursor); } if hit == STYLE || hit == STYLE + 1 { - return Some(Target::Style((hit - STYLE) as usize)); + return ( + Some(Target::Style((hit - STYLE) as usize)), + scrollbar, + cursor, + ); } if hit == LEVEL || hit == LEVEL + 1 { - return Some(Target::Level((hit - LEVEL) as usize)); + return ( + Some(Target::Level((hit - LEVEL) as usize)), + scrollbar, + cursor, + ); } - let i = hit.checked_sub(ROW)? as usize; + let Some(i) = hit.checked_sub(ROW).map(|i| i as usize) else { + return (None, scrollbar, cursor); + }; let rows = self.horizon_rows(s, section); let item = match rows.get(i) { Some(HRow::Opt(opt)) => Some(Item::Vanilla(*opt)), @@ -592,12 +653,16 @@ impl OptionsUi { _ => None, }; if let Some(item) = item - && let Some(&(_, sx, sw)) = sliders.iter().find(|(o, ..)| *o == item) + && let Some(&(_, sx, sw)) = layout.sliders.iter().find(|(o, ..)| *o == item) { let v = t::slider_value(&ui, sx, sw, x); - return Some(Target::Slider(item, v)); + return (Some(Target::Slider(item, v)), scrollbar, cursor); } - (i < rows.len()).then_some(Target::Row(i)) + ( + (i < rows.len()).then_some(Target::Row(i)), + scrollbar, + cursor, + ) } /// A click (or a drag with the button held) on the Horizon shell. pub(crate) fn click_horizon( @@ -612,14 +677,37 @@ impl OptionsUi { ) -> Vec { let mut events = Vec::new(); if drag { - if let Some(item) = self.hdragging { - let mut batch = t::scratch_batch(); - let mut ui = Ui::dry(atlas, &mut batch, (x, y)); - let sliders = self.horizon_layout(s, &mut ui, 1.0); - if let Some(&(_, sx, sw)) = sliders.iter().find(|(o, ..)| *o == item) { - set_item_slider(item, s, t::slider_value(&ui, sx, sw, x)); - events.push(Event::Changed); + let mut batch = horizon_batch(framebuffer); + let mut ui = Ui::dry(atlas, &mut batch, (x, y)); + let layout = self.horizon_layout(s, &mut ui, 1.0); + // Scrollbar geometry and stored drag positions are in Horizon dp. + let pointer_y = ui.cursor.1; + if let Some(previous_y) = self.scrollbar_drag_y { + if let Some(scrollbar) = layout.scrollbar { + // AbstractScrollArea.mouseDragged (inherited by AbstractSelectionList) + // moves by the pointer delta and sends out-of-range drags to an end. + let track = scrollbar.bottom - scrollbar.top; + self.hscroll = if pointer_y < scrollbar.top { + 0.0 + } else if pointer_y > scrollbar.bottom { + scrollbar.max + } else { + self.hscroll + + (pointer_y - previous_y) * scrollbar.max + / (track - scrollbar.thumb).max(1.0) + }; + self.hscroll = self.hscroll.clamp(0.0, scrollbar.max); + self.scrollbar_drag_y = Some(pointer_y); + } else { + self.scrollbar_drag_y = None; } + return events; + } + if let Some(item) = self.hdragging + && let Some(&(_, sx, sw)) = layout.sliders.iter().find(|(o, ..)| *o == item) + { + set_item_slider(item, s, t::slider_value(&ui, sx, sw, x)); + events.push(Event::Changed); } return events; } @@ -634,8 +722,16 @@ impl OptionsUi { }, ); } - let target = self.horizon_target(s, atlas, x, y); + let (target, scrollbar, cursor) = self.horizon_target(s, atlas, x, y, framebuffer); self.settings_search.focused = false; + // AbstractScrollArea.updateScrolling grabs anywhere in the scrollbar column. + if !right + && let Some(scrollbar) = scrollbar + && scrollbar.contains(cursor.0, cursor.1) + { + self.scrollbar_drag_y = Some(cursor.1); + return events; + } match target { Some(Target::Nav(i)) => { if searchable_section(self.section) || searchable_section(i) { @@ -695,6 +791,10 @@ impl OptionsUi { s.mods.toggle(*m); events.push(Event::Changed); } + Some(HRow::OpenModFolder) if !right => { + events.push(Event::ButtonClick); + events.push(Event::OpenModFolder); + } _ => {} } } @@ -715,3 +815,211 @@ fn set_item_slider(item: Item, s: &mut Settings, v: f32) { Item::Horizon(_) => item.set_slider(s, v), } } + +#[cfg(test)] +mod tests { + use super::*; + + fn atlas() -> HudAtlas { + HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap() + } + + fn section_ui(name: &str) -> OptionsUi { + let mut ui = OptionsUi::default(); + ui.section = SECTIONS + .iter() + .position(|section| section.name == name) + .unwrap(); + ui + } + + fn extras_ui() -> OptionsUi { + section_ui("Extras") + } + + fn scrollbar( + ui: &mut OptionsUi, + settings: &Settings, + atlas: &HudAtlas, + framebuffer: [i32; 2], + ) -> HorizonScrollbar { + let mut batch = horizon_batch(framebuffer); + let mut draw = Ui::dry(atlas, &mut batch, (0.0, 0.0)); + ui.horizon_layout(settings, &mut draw, 1.0) + .scrollbar + .unwrap() + } + + fn gui_pointer(atlas: &HudAtlas, framebuffer: [i32; 2], point: (f32, f32)) -> (f32, f32) { + let mut batch = horizon_batch(framebuffer); + let ui = Ui::dry(atlas, &mut batch, (0.0, 0.0)); + let gui_per_dp = ui.density / ui.batch.scale; + (point.0 * gui_per_dp, point.1 * gui_per_dp) + } + + #[test] + fn horizon_scrollbar_track_drag_is_bounded_and_stops_on_release() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let mut settings = Settings::default(); + let mut ui = section_ui("Controls"); + let bar = scrollbar(&mut ui, &settings, &atlas, framebuffer); + let max = bar.max; + let track = bar.bottom - bar.top; + assert!(max > 0.0); + + // Start on the track below the thumb, then move horizontally away; + // the held scrollbar keeps following the pointer. + let x = bar.x + 2.0; + let y = bar.top + bar.thumb + (track - bar.thumb) / 2.0; + assert!(y < bar.bottom); + let (click_x, click_y) = gui_pointer(&atlas, framebuffer, (x, y)); + assert!( + ui.click_horizon( + &mut settings, + &atlas, + click_x, + click_y, + framebuffer, + false, + false, + ) + .is_empty() + ); + assert_eq!(ui.hscroll, 0.0); + let delta = 5.0; + let (drag_x, drag_y) = gui_pointer(&atlas, framebuffer, (x - 100.0, y + delta)); + assert!( + ui.click_horizon( + &mut settings, + &atlas, + drag_x, + drag_y, + framebuffer, + true, + false, + ) + .is_empty() + ); + assert!((ui.hscroll - delta * max / (track - bar.thumb)).abs() < 0.001); + + let (below_x, below_y) = gui_pointer(&atlas, framebuffer, (x, bar.bottom + 100.0)); + assert!( + ui.click_horizon( + &mut settings, + &atlas, + below_x, + below_y, + framebuffer, + true, + false, + ) + .is_empty() + ); + assert_eq!(ui.hscroll, max); + let (above_x, above_y) = gui_pointer(&atlas, framebuffer, (x, bar.top - 100.0)); + assert!( + ui.click_horizon( + &mut settings, + &atlas, + above_x, + above_y, + framebuffer, + true, + false, + ) + .is_empty() + ); + assert_eq!(ui.hscroll, 0.0); + + assert!(ui.release().is_empty()); + let (below_x, below_y) = gui_pointer(&atlas, framebuffer, (x, bar.bottom + 100.0)); + assert!( + ui.click_horizon( + &mut settings, + &atlas, + below_x, + below_y, + framebuffer, + true, + false, + ) + .is_empty() + ); + assert_eq!(ui.hscroll, 0.0); + assert_eq!(settings.keys, Settings::default().keys); + } + + #[test] + fn horizon_key_rebinding_takes_precedence_over_scrollbar_press() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let mut settings = Settings::default(); + let mut ui = extras_ui(); + let bar = scrollbar(&mut ui, &settings, &atlas, framebuffer); + let dp_y = bar.top + bar.thumb + (bar.bottom - bar.top - bar.thumb) / 2.0; + ui.selected_key = Some(extras::SORT_KEY); + let (x, y) = gui_pointer(&atlas, framebuffer, (bar.x + 2.0, dp_y)); + + assert_eq!( + ui.click_horizon(&mut settings, &atlas, x, y, framebuffer, false, false,), + vec![Event::Changed] + ); + assert_eq!(settings.extras.sort_key, "key.mouse.left"); + assert_eq!(ui.selected_key, None); + assert_eq!(ui.hscroll, 0.0); + + let (x, drag_y) = gui_pointer(&atlas, framebuffer, (bar.x + 2.0, dp_y + 10.0)); + ui.click_horizon(&mut settings, &atlas, x, drag_y, framebuffer, true, false); + assert_eq!(ui.hscroll, 0.0); + } + + #[test] + fn mods_section_opens_folder_from_its_button() { + let atlas = atlas(); + let framebuffer = [2560, 1440]; + let mut options = section_ui("Mods"); + let mut settings = Settings::default(); + let mut batch = horizon_batch(framebuffer); + let mut ui = Ui::dry(&atlas, &mut batch, (0.0, 0.0)); + options.horizon_layout(&settings, &mut ui, 1.0); + let rect = ui + .hits + .iter() + .find(|hit| hit.id == ROW) + .expect("Mods section has an Open Folder button") + .rect; + let scale = ui.density / ui.batch.scale; + let cursor = ( + (rect[0] + rect[2]) * 0.5 * scale, + (rect[1] + rect[3]) * 0.5 * scale, + ); + drop(ui); + + assert_eq!( + options.click_horizon( + &mut settings, + &atlas, + cursor.0, + cursor.1, + framebuffer, + false, + false + ), + vec![Event::ButtonClick, Event::OpenModFolder] + ); + assert!( + options + .click_horizon( + &mut settings, + &atlas, + cursor.0, + cursor.1, + framebuffer, + false, + true + ) + .is_empty() + ); + } +} diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 994cc4793..8e1875f48 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -190,7 +190,7 @@ impl Opt { let unit = |v: f32, lo: f32, hi: f32| Kind::Slider(((v - lo) / (hi - lo)).clamp(0.0, 1.0)); match self { Opt::Fov => unit(s.fov, 30.0, 110.0), - Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 32.0), + Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 64.0), Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0), Opt::Sensitivity => Kind::Slider(s.sensitivity), Opt::WheelSensitivity => unit(s.mouse_wheel_sensitivity, 0.01, 10.0), @@ -484,7 +484,7 @@ impl Opt { let step = |lo: f32, hi: f32| (lo + v * (hi - lo)).round(); match self { Opt::Fov => s.fov = step(30.0, 110.0), - Opt::RenderDistance => s.render_distance = step(2.0, 32.0) as i32, + Opt::RenderDistance => s.render_distance = step(2.0, 64.0) as i32, Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32, Opt::Sensitivity => s.sensitivity = v, Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99, @@ -734,6 +734,7 @@ enum Act { /// Back to Horizon's own menus (Horizon only, see `list_rows`). HorizonMenus, ToggleMod(usize), + OpenModFolder, } enum WKind { Button { @@ -780,6 +781,7 @@ pub enum Event { /// The pack selection changed (reload resources). Packs(Vec), OpenPackFolder, + OpenModFolder, } /// `SliderableValueSet.applyValueImmediately`: these apply 600 ms after /// the last change (`OptionInstanceSliderButton.delayedApplyAt`). @@ -806,7 +808,8 @@ pub struct OptionsUi { /// when it last moved: the handle follows the pointer while the option /// keeps its stepped value, then snaps to it (`resetValue`). slider_value: Option<(Opt, f32, Instant)>, - scrollbar_drag_y: Option, + /// The pointer's last y while a Classic or Horizon scrollbar is held. + pub(crate) scrollbar_drag_y: Option, /// Horizon style: the selected sidebar section, the one last drawn and /// the rows' scroll in dp (`options_horizon`). pub section: usize, @@ -1683,7 +1686,18 @@ impl OptionsUi { } content = y + self.scroll - top + 2.0; out[list_start..].iter_mut().for_each(|w| w.list = true); - out.push(done(h - 27.0)); + if page == Page::Mods { + out.push(button( + cx - 154.0, + h - 27.0, + 150.0, + Text::literal("Open Mod Folder"), + Act::OpenModFolder, + )); + out.push(button(cx + 4.0, h - 27.0, 150.0, tr("gui.done"), Act::Done)); + } else { + out.push(done(h - 27.0)); + } } } // Layout may change the offset (language centering), or the list may @@ -2162,6 +2176,7 @@ impl OptionsUi { s.mods.toggle(i); events.push(Event::Changed); } + Act::OpenModFolder => events.push(Event::OpenModFolder), Act::None => {} } } @@ -2460,6 +2475,25 @@ mod tests { use super::*; use crate::ui_theme::{MenuStyle, set_style, style}; + #[test] + fn render_distance_slider_round_trips_through_extended_options_range() { + let mut s = Settings::default(); + for (position, distance) in [(0.0, 2), (0.5, 33), (1.0, 64)] { + set_slider(Opt::RenderDistance, &mut s, position); + assert_eq!(s.render_distance, distance); + let reloaded = Settings::parse(&s.serialize()); + assert_eq!(reloaded.render_distance, distance); + assert_eq!( + Opt::RenderDistance.slider_position(&reloaded), + Some(position) + ); + } + let mut file = crate::options_file::OptionsFile::default(); + file.set_text("renderDistance", "64").unwrap(); + assert!(file.set_text("renderDistance", "65").is_err()); + assert!(file.set_text("renderDistance", "1").is_err()); + assert_eq!(file.int("renderDistance"), 64); + } fn atlas() -> HudAtlas { HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap() } @@ -2534,6 +2568,31 @@ mod tests { assert!(empty.iter().any(|w| { matches!(&w.kind, WKind::Text { text, .. } if text.plain().contains(".hmod")) })); + let open_folder = empty + .iter() + .find(|w| { + matches!( + &w.kind, + WKind::Button { + act: Act::OpenModFolder, + .. + } + ) + }) + .expect("Mods page has an Open Mod Folder button"); + assert_eq!( + ui.click( + &mut s, + &atlas, + open_folder.x + 1.0, + open_folder.y + 1.0, + size, + [480, 240], + false, + false, + ), + vec![Event::ButtonClick, Event::OpenModFolder] + ); for (id, dev) in [("normal", false), ("dev", true), ("", false)] { s.mods.installed.push(crate::mod_list::Installed { id: id.into(), diff --git a/crates/horizon-client/src/poi_sections.rs b/crates/horizon-client/src/poi_sections.rs index 2116362e0..79ff0441d 100644 --- a/crates/horizon-client/src/poi_sections.rs +++ b/crates/horizon-client/src/poi_sections.rs @@ -54,12 +54,12 @@ impl PoiSections { return cached.pois.clone(); } let pois: SectionPois = if section.blocks.maybe_has(|v| kind(v).is_some()) { - let mut states = [0u16; 4096]; + let mut states = [0u32; 4096]; section.unpack(&mut states); states .iter() .enumerate() - .filter_map(|(i, &state)| kind(u32::from(state)).map(|poi| (i as u16, poi))) + .filter_map(|(i, &state)| kind(state).map(|poi| (i as u16, poi))) .collect() } else { Arc::from([]) diff --git a/crates/horizon-client/src/projectiles.rs b/crates/horizon-client/src/projectiles.rs index bfd0e8a97..c2d4b4e3a 100644 --- a/crates/horizon-client/src/projectiles.rs +++ b/crates/horizon-client/src/projectiles.rs @@ -63,6 +63,8 @@ pub enum ProjectileKind { } #[derive(Clone, Debug, PartialEq)] pub struct Projectile { + /// The entity id a server tracks it by (0 until it is tracked). + pub id: u32, pub kind: ProjectileKind, pub owner: Option, pub position: Vec3, @@ -128,6 +130,7 @@ impl Projectile { pub fn new(kind: ProjectileKind, position: Vec3, owner: Option) -> Self { let kind_is_arrow = matches!(kind, ProjectileKind::Arrow { .. }); Self { + id: 0, kind, owner, position, diff --git a/crates/horizon-client/src/random_tick_sections.rs b/crates/horizon-client/src/random_tick_sections.rs index 97a1f02fa..cd06f2ac9 100644 --- a/crates/horizon-client/src/random_tick_sections.rs +++ b/crates/horizon-client/src/random_tick_sections.rs @@ -134,7 +134,7 @@ mod tests { let mut chunk = Chunk::empty(0, 0); for i in [0, 9, SECTIONS - 1] { Arc::make_mut(&mut chunk.sections[i]).blocks = - Section::from_blocks(&std::array::from_fn(|j| (j % 300) as u16)); + Section::from_blocks(&std::array::from_fn(|j| (j % 300) as u32)); } let chunk = Arc::new(chunk); let mut cache = RandomTickSections::default(); @@ -176,12 +176,9 @@ mod tick_parity { } fn set_raw(&mut self, pos: BlockPos, state: BlockStateId) -> Option { let chunk = self.chunks.get_mut(&(pos.x >> 4, pos.z >> 4))?; - Some(BlockStateId(u32::from(Arc::make_mut(chunk).set( - pos.x, - pos.y, - pos.z, - state.0 as u16, - )))) + Some(BlockStateId( + Arc::make_mut(chunk).set(pos.x, pos.y, pos.z, state.0), + )) } fn is_loaded(&self, pos: BlockPos) -> bool { self.chunks.contains_key(&(pos.x >> 4, pos.z >> 4)) @@ -233,7 +230,7 @@ mod tick_parity { // Every sampled block can run real behaviour and change to dirt. for i in [4, 7] { Arc::make_mut(&mut c.sections[i]).blocks = - crate::chunk::Section::from_blocks(&[grass.0 as u16; 4096]); + crate::chunk::Section::from_blocks(&[grass.0; 4096]); } Arc::new(c) }; diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 2caa68cac..27051bbc6 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -756,6 +756,15 @@ impl RecipeIndex { r.first_display..r.first_display + r.displays as i32 }) } + /// The recipe a display id belongs to (`RecipeManager.getRecipeFromDisplay`). + pub fn recipe_of_display(&self, display: i32) -> Option<&str> { + self.recipes + .iter() + .find(|(_, r)| { + (r.first_display..r.first_display + r.displays as i32).contains(&display) + }) + .map(|(id, _)| id.as_str()) + } pub fn first_display(&self, id: &str) -> Option { self.recipes .get(id) diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 4411a353c..c60da2caa 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -16,7 +16,7 @@ use crate::{ Result, biome::Biomes, - chunk::{BIOME_STRATEGY, BLOCK_STRATEGY, Chunk, Light, MIN_Y, SECTIONS}, + chunk::{BIOME_STRATEGY, Chunk, Light, MIN_Y, SECTIONS, block_strategy}, streaming::ChunkGenerator, }; use horizon_core::{ @@ -238,7 +238,7 @@ pub struct SaveTables { default_state: Vec, block_entity: Vec, heightmaps: crate::assets::Properties, - air: u16, + air: u32, } impl SaveTables { pub fn new(assets: &crate::assets::Assets) -> Self { @@ -266,9 +266,7 @@ impl SaveTables { default_state, block_entity: Vec::new(), heightmaps: assets.properties.clone(), - air: registry - .default_state("minecraft:air") - .map_or(0, |s| s.0 as u16), + air: registry.default_state("minecraft:air").map_or(0, |s| s.0), } } /// Which states carry a block entity (`BlockFacts`), to drop entries for @@ -1035,8 +1033,8 @@ fn decode_column( } } } - let air = registry.default_state("minecraft:air")?.0 as u16; - let mut cache: HashMap = HashMap::new(); + let air = registry.default_state("minecraft:air")?.0; + let mut cache: HashMap = HashMap::new(); let Some(Tag::List(sections)) = tag.get("sections") else { return Some(chunk); }; @@ -1051,7 +1049,7 @@ fn decode_column( if let Some(states) = section.get("block_states") && let Some(Tag::List(palette)) = states.get("palette") { - let ids: Vec = palette + let palette: Vec = palette .iter() .map(|p| { let state = BlockState::from_nbt(p).ok(); @@ -1074,7 +1072,7 @@ fn decode_column( registry.id(&full).or(Some(default)) }) }) - .map_or(air, |id| id.0 as u16) + .map_or(air, |id| id.0) }) }) .collect(); @@ -1085,9 +1083,8 @@ fn decode_column( } _ => None, }; - let palette: Vec = ids.iter().map(|&id| u32::from(id)).collect(); if let Ok(blocks) = - PalettedContainer::from_packed(BLOCK_STRATEGY, palette, data.as_deref()) + PalettedContainer::from_packed(block_strategy(), palette, data.as_deref()) { target.blocks = blocks; } @@ -1980,40 +1977,51 @@ impl Default for WorldGen { } /// Writes a new world's `world_gen_settings` (seed, options and dimensions). pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> { + write_world_gen_settings_with(dir, seed, options, None) +} +/// [`write_world_gen_settings`] with a flat overworld's own generator +/// settings (FlatLevelGeneratorSettings, as `flatgen::settings_from_json` +/// reads them) instead of the Superflat preset's classic layers. +pub fn write_world_gen_settings_with( + dir: &Path, + seed: i64, + options: WorldGen, + flat_settings: Option, +) -> Result<()> { fs::create_dir_all(dir)?; // worldgen/world_preset/flat.json's overworld: the classic flat layers. let layer = |block: &str, height: i32| { Tag::compound([("block", string(block)), ("height", Tag::Int(height))]) }; + let classic = || { + Tag::compound([ + ("biome", string("minecraft:plains")), + ("features", Tag::Byte(0)), + ("lakes", Tag::Byte(0)), + ( + "layers", + Tag::List(vec![ + layer("minecraft:bedrock", 1), + layer("minecraft:dirt", 2), + layer("minecraft:grass_block", 1), + ]), + ), + ( + "structure_overrides", + Tag::List(vec![ + string("minecraft:strongholds"), + string("minecraft:villages"), + ]), + ), + ]) + }; let flat = Tag::compound([ ("type", string("minecraft:overworld")), ( "generator", Tag::compound([ ("type", string("minecraft:flat")), - ( - "settings", - Tag::compound([ - ("biome", string("minecraft:plains")), - ("features", Tag::Byte(0)), - ("lakes", Tag::Byte(0)), - ( - "layers", - Tag::List(vec![ - layer("minecraft:bedrock", 1), - layer("minecraft:dirt", 2), - layer("minecraft:grass_block", 1), - ]), - ), - ( - "structure_overrides", - Tag::List(vec![ - string("minecraft:strongholds"), - string("minecraft:villages"), - ]), - ), - ]), - ), + ("settings", flat_settings.unwrap_or_else(classic)), ]), ), ]); @@ -2138,11 +2146,25 @@ pub struct Level { pub on_ground: bool, pub food_exhaustion: f32, pub food_tick_timer: i32, + /// Abilities.flying: whether creative/spectator flight is active. + pub flying: bool, /// The player compound as loaded, for fields Horizon does not model /// (ender chest, effects, abilities, recipe book, attributes, ...). pub player_extra: Option, } impl Level { + /// Initialize the offline single-player identity before saving or dropping items. + pub fn ensure_player_uuid(&mut self) -> [i32; 4] { + *self.player_uuid.get_or_insert_with(|| { + let u = horizon_protocol::crypto::offline_uuid("Player"); + [ + (u >> 96) as u32 as i32, + (u >> 64) as u32 as i32, + (u >> 32) as u32 as i32, + u as u32 as i32, + ] + }) + } pub fn game_rule(&self, name: &str) -> i32 { self.game_rules .get(name) @@ -2289,6 +2311,10 @@ impl Level { self.creative = mode == 1; self.game_mode = mode as i32; } + self.flying = p + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .is_some_and(|v| v != 0); if let Some(d) = text(p.get("Dimension")) { self.dimension = d; } @@ -2420,7 +2446,9 @@ impl Level { } if spectator { put(&mut abilities, "flying", Tag::Byte(1)); - } else if !creative { + } else if creative { + put(&mut abilities, "flying", Tag::Byte(i8::from(self.flying))); + } else { put(&mut abilities, "flying", Tag::Byte(0)); } if let Tag::Compound(map) = &mut abilities { @@ -2600,17 +2628,7 @@ impl Level { map.remove(&JavaString::from(key)); } } - // A new world's player has the offline profile id of its name - // (UUIDUtil.createOfflinePlayerUUID), as in an offline single-player game. - let uuid = *self.player_uuid.get_or_insert_with(|| { - let u = horizon_protocol::crypto::offline_uuid("Player"); - [ - (u >> 96) as u32 as i32, - (u >> 64) as u32 as i32, - (u >> 32) as u32 as i32, - u as u32 as i32, - ] - }); + let uuid = self.ensure_player_uuid(); // A new world's first spawn point is its world spawn. if self.world_spawn.is_none() { self.world_spawn = self.spawn.map(|s| { @@ -3143,6 +3161,7 @@ mod tests { world_spawn: Some([8, 64, 8]), spawn: Some([20.0, 70.0, 20.0]), difficulty_locked: true, + flying: true, ..Level::default() }; level.weather.raining = true; @@ -3154,6 +3173,7 @@ mod tests { assert_eq!(back.seed, -42); assert_eq!((back.time, back.day_time), (1234, 25000)); assert!(back.creative); + assert!(back.flying); assert_eq!(back.position, Some([1.5, 70.0, -3.25])); assert_eq!(back.rotation, [90.0, 10.0]); assert_eq!((back.health, back.food, back.saturation), (17.0, 15, 2.5)); @@ -3207,6 +3227,17 @@ mod tests { third.ender_items[3].as_ref().map(|s| (&*s.item, s.count)), Some(("minecraft:diamond", 2)) ); + // A dead player's empty inventory replaces the previously loaded items. + let mut dead = third; + dead.health = 0.0; + dead.inventory.clear(); + dead.inventory_components.clear(); + dead.write(&dir).unwrap(); + let dead = Level::read(&dir).unwrap(); + assert_eq!(dead.health, 0.0); + assert!(dead.inventory.is_empty()); + assert!(dead.inventory_components.is_empty()); + assert!(dead.player_extra.unwrap().get("equipment").is_none()); assert!(dir.join("data/minecraft/world_gen_settings.dat").exists()); let _ = fs::remove_dir_all(&dir); } @@ -3225,4 +3256,33 @@ mod tests { level.active_effects.clear(); assert!(level.player_tag().get("active_effects").is_none()); } + + #[test] + fn creative_flight_status_persists_in_save_and_resets_for_survival() { + let mut level = Level { + creative: true, + flying: true, + ..Level::default() + }; + let tag = level.player_tag(); + let flying_byte = tag + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .unwrap_or(0); + assert_eq!(flying_byte, 1); + + let mut loaded = Level::default(); + loaded.read_player(&tag); + assert!(loaded.flying); + + // Survival mode resets flying ability to 0 in save. + level.creative = false; + level.game_mode = 0; + let tag_survival = level.player_tag(); + let flying_survival = tag_survival + .get("abilities") + .and_then(|a| number(a.get("flying"))) + .unwrap_or(0); + assert_eq!(flying_survival, 0); + } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 1754f1550..bff0a8fd6 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -200,8 +200,10 @@ pub struct Streaming { /// Chunks come from a server (`insert_remote`/`forget`): nothing is /// generated and columns are only unloaded when the server says so. pub remote: bool, - /// More areas to keep loaded (centre chunk, radius), e.g. around guests - /// of a world open to the network. They are generated and kept but not meshed. + /// More areas to keep loaded (centre chunk, radius), e.g. around the + /// players of a server. Each is a square, like vanilla's ticket levels: + /// chunks finish out to `radius + 1` (Chebyshev) and generation reaches + /// past that as around the player. They are generated and kept but not meshed. pub extra: Vec<((i32, i32), i32)>, /// Mesh the sections for drawing (false on a server thread). pub mesh: bool, @@ -264,25 +266,34 @@ impl GenerationScan { } { let mut wanted = Vec::new(); - let areas: Vec<((i32, i32), i32)> = - std::iter::once((input.ranges.center, input.ranges.radius)) - .chain(input.ranges.extra.iter().copied()) - .collect(); - for (center, radius) in areas { + // Each area's square of columns, as one run per row. Players' + // areas overlap (a server's players often stand together), so + // the runs of a row are merged and each column is looked at once. + let mut runs: Vec<(i32, i32, i32)> = Vec::new(); + for (center, radius) in std::iter::once((input.ranges.center, input.ranges.radius)) + .chain(input.ranges.extra.iter().copied()) + { let r = radius + margin.max(reach + 1); - for dz in -r..=r { - for dx in -r..=r { - let (x, z) = (center.0 + dx, center.1 + dz); - if !input.ranges.requested(x, z, input.decorates) - || input.world.chunks.contains_key(&(x, z)) - || input.generating.contains(&(x, z)) - || input.protos.contains_key(&(x, z)) - || input.finishing.contains(&(x, z)) - { - continue; - } - wanted.push((input.ranges.distance(x, z), x, z)); + runs.extend((center.1 - r..=center.1 + r).map(|z| (z, center.0 - r, center.0 + r))); + } + runs.sort_unstable(); + let mut runs = runs.into_iter().peekable(); + while let Some((z, x0, mut x1)) = runs.next() { + while let Some((_, _, next_x1)) = + runs.next_if(|&(nz, nx0, _)| nz == z && nx0 <= x1.saturating_add(1)) + { + x1 = x1.max(next_x1); + } + for x in x0..=x1 { + if !input.ranges.requested(x, z, input.decorates) + || input.world.chunks.contains_key(&(x, z)) + || input.generating.contains(&(x, z)) + || input.protos.contains_key(&(x, z)) + || input.finishing.contains(&(x, z)) + { + continue; } + wanted.push((input.ranges.distance(x, z), x, z)); } } // Forced chunks and their generation neighbourhood. @@ -580,7 +591,7 @@ impl Streaming { } world .block_entities - .extend(std::mem::take(&mut chunk.block_entities)); + .load_chunk(std::mem::take(&mut chunk.block_entities)); world .block_names .extend(std::mem::take(&mut chunk.block_names)); @@ -779,20 +790,17 @@ impl Streaming { world.dirty_sections.retain(|k| !far.contains(&(k.0, k.2))); } // Drop far proto chunks that are not checked out. - let areas: Vec<((i32, i32), i64)> = - std::iter::once((self.center, i64::from(self.radius + 4))) - .chain(self.extra.iter().map(|&(c, r)| (c, i64::from(r + 4)))) - .collect(); - let forced = &self.forced; + let (center, r4) = (self.center, i64::from(self.radius + 4)); + let ranges = self.ranges(); let far: Vec<(i32, i32)> = self .protos .iter() .filter(|&(&(x, z), p)| { p.is_some() - && !areas.iter().any(|&((cx, cz), r4)| { - i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2) <= r4 * r4 - }) - && !forced + && i64::from(x - center.0).pow(2) + i64::from(z - center.1).pow(2) > r4 * r4 + && !ranges.in_extra(x, z, 4) + && !ranges + .forced .iter() .any(|f| (x - f.0).abs() <= 3 && (z - f.1).abs() <= 3) }) @@ -1268,21 +1276,21 @@ impl Ranges<'_> { /// circles, so a fixed margin alone misses the corners of those squares /// (render distance 2 never finished the chunks next to the player). fn near_finished(&self, x: i32, z: i32, reach: i32) -> bool { - let near = |c: (i32, i32), radius: i32| { - let gap = |d: i32| i64::from((d.abs() - reach).max(0)); - let (dx, dz) = (gap(x - c.0), gap(z - c.1)); - let r = i64::from(radius + 1); - dx * dx + dz * dz <= r * r - }; - near(self.center, self.radius) || self.extra.iter().any(|&(c, r)| near(c, r)) + let gap = |d: i32| i64::from((d.abs() - reach).max(0)); + let (dx, dz) = (gap(x - self.center.0), gap(z - self.center.1)); + let r = i64::from(self.radius + 1); + // The extra areas are squares: their finished square grown by `reach`. + dx * dx + dz * dz <= r * r || self.in_extra(x, z, 1 + reach) } fn in_range(&self, x: i32, z: i32, margin: i32) -> bool { - self.in_main_range(x, z, margin) - || self.extra.iter().any(|&(c, radius)| { - let r = i64::from(radius + margin); - let (dx, dz) = (i64::from(x - c.0), i64::from(z - c.1)); - dx * dx + dz * dz <= r * r - }) + self.in_main_range(x, z, margin) || self.in_extra(x, z, margin) + } + /// Within `margin` of an extra area's square (Chebyshev distance, as + /// vanilla's ticket levels spread). + fn in_extra(&self, x: i32, z: i32, margin: i32) -> bool { + self.extra + .iter() + .any(|&(c, radius)| (x - c.0).abs().max((z - c.1).abs()) <= radius + margin) } /// The columns meshed for drawing: those vanilla draws around the /// player (`in_view_distance`), and forced ones. @@ -1569,6 +1577,38 @@ mod tests { } } + #[test] + fn generation_scan_looks_at_overlapping_areas_once() { + // A server's players: many areas around one spot, some apart, one + // touching another only at a corner, and part of the land present. + for decorates in [false, true] { + let mut f = GenerationFixture::new(10, decorates); + for i in 0..40 { + f.extra.push(((i % 7 - 3, i / 7 - 3), 19)); + } + f.extra.push(((200, -150), 19)); + f.extra.push(((243, -107), 19)); + f.extra.push(((-60, 5), 4)); + f.forced.insert((90, 90)); + let chunk = Arc::new(Chunk::empty(0, 0)); + for x in -40i32..40 { + for z in -40i32..40 { + match (x * 7 + z * 13).rem_euclid(5) { + 0 => drop(f.world.chunks.insert((x, z), chunk.clone())), + 1 => drop(f.protos.insert((x, z), None)), + 2 if x % 3 == 0 => drop(f.generating.insert((x, z))), + _ => {} + } + } + } + assert!(baseline_candidates(f.input(), usize::MAX).len() > 1000); + for capacity in [usize::MAX, f.generating.len() + 7] { + let mut gate = GenerationScan::default(); + assert!(f.assert_same(&mut gate, capacity)); + } + } + } + #[test] #[ignore = "reproducible actual generation scheduler benchmark; run with --ignored --nocapture"] fn generation_scan_benchmark() { @@ -1737,4 +1777,58 @@ mod tests { } } } + + /// A server player's area (`lan_update_streaming`: the server view + /// distance + 1) finishes vanilla's FULL square: PLAYER_LOADING tickets at + /// level 31 out to the view distance, FULL (33) two chunks past it. Every + /// chunk the player tracks has its 3x3 neighbourhood finished, so it can + /// be lit and sent, and generation reaches vanilla's FEATURES (34) and + /// TERRAIN (35) rings. + #[test] + fn server_player_areas_finish_vanillas_full_square() { + let forced = HashSet::new(); + for view in 2..=32 { + let extra = [((40, -9), view + 1)]; + let r = Ranges { + // The window's own area, far away. + center: (-400, 300), + radius: 2, + extra: &extra, + forced: &forced, + }; + let level = |x: i32, z: i32| 31 + ((x - 40).abs().max((z + 9).abs()) - view).max(0); + for x in 40 - view - 8..=40 + view + 8 { + for z in -9 - view - 8..=-9 + view + 8 { + assert_eq!( + r.in_range(x, z, 1), + level(x, z) <= 33, + "view {view}: ({x}, {z})" + ); + assert_eq!( + r.requested(x, z, true), + level(x, z) <= 35, + "view {view}: ({x}, {z})" + ); + assert_eq!( + r.unloaded(x, z, true), + level(x, z) > 35, + "view {view}: ({x}, {z})" + ); + // ChunkTrackingView.contains, at any view distance the player may ask for. + let tracked = |v: i64| { + let gap = |d: i32| i64::from(((d).abs() - 2).max(0)); + gap(x - 40).pow(2) + gap(z + 9).pow(2) < v * v + }; + if tracked(i64::from(view)) { + for (dx, dz) in (-1..=1).flat_map(|dx| (-1..=1).map(move |dz| (dx, dz))) { + assert!( + r.in_range(x + dx, z + dz, 1), + "view {view}: ({x}, {z}) tracked, not lit" + ); + } + } + } + } + } + } } diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 4689e7d2b..504d197aa 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -31,6 +31,10 @@ struct Globals { @group(0) @binding(5) var sprites_1: texture_2d_array; @group(0) @binding(6) var sprites_2: texture_2d_array; @group(0) @binding(7) var sprites_3: texture_2d_array; +@group(0) @binding(8) var sprites_4: texture_2d_array; +@group(0) @binding(9) var sprites_5: texture_2d_array; +@group(0) @binding(10) var sprites_6: texture_2d_array; +@group(0) @binding(11) var sprites_7: texture_2d_array; // How many sprite arrays hold layers (a pipeline constant): 1 for vanilla, // which then samples exactly as before. override SPRITE_ARRAYS: u32 = 1u; @@ -47,7 +51,11 @@ fn sprite(uv: vec2, layer: u32) -> vec4 { case 0u: { return textureSampleGrad(sprites, sprite_sampler, uv, l, dx, dy); } case 1u: { return textureSampleGrad(sprites_1, sprite_sampler, uv, l, dx, dy); } case 2u: { return textureSampleGrad(sprites_2, sprite_sampler, uv, l, dx, dy); } - default: { return textureSampleGrad(sprites_3, sprite_sampler, uv, l, dx, dy); } + case 3u: { return textureSampleGrad(sprites_3, sprite_sampler, uv, l, dx, dy); } + case 4u: { return textureSampleGrad(sprites_4, sprite_sampler, uv, l, dx, dy); } + case 5u: { return textureSampleGrad(sprites_5, sprite_sampler, uv, l, dx, dy); } + case 6u: { return textureSampleGrad(sprites_6, sprite_sampler, uv, l, dx, dy); } + default: { return textureSampleGrad(sprites_7, sprite_sampler, uv, l, dx, dy); } } } @@ -68,7 +76,24 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4 { @location(0) position: vec3, @location(1) uv: vec2, @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2, @location(5) origin: vec4) -> TerrainOut { - let pos = position + origin.xyz; + return terrain_vertex(position, uv, layer, color, light, origin.xyz); +} +// Flat section draws (gfx/flat.rs): one draw per arena page over the frame's +// index list. A section's vertices fill whole 256-vertex blocks of its page: +// the block gives its resident slot, the slot its camera-relative origin. +@group(1) @binding(0) var block_slots: array; +@group(1) @binding(1) var slot_origins: array>; +@vertex fn vs_terrain_flat( + @builtin(vertex_index) vertex: u32, + @location(0) position: vec3, @location(1) uv: vec2, + @location(2) layer: u32, @location(3) color: vec4, @location(4) light: vec2 +) -> TerrainOut { + let origin = slot_origins[block_slots[vertex >> 8u]]; + return terrain_vertex(position, uv, layer, color, light, origin.xyz); +} +fn terrain_vertex(position: vec3, uv: vec2, layer: u32, color: vec4, + light: vec2, origin: vec3) -> TerrainOut { + let pos = position + origin; var out: TerrainOut; out.clip = globals.view_proj * vec4(pos, 1.0); out.uv = uv; diff --git a/crates/horizon-client/src/testgen.rs b/crates/horizon-client/src/testgen.rs index e0a5d49b3..6268a8b6c 100644 --- a/crates/horizon-client/src/testgen.rs +++ b/crates/horizon-client/src/testgen.rs @@ -4,24 +4,24 @@ use crate::{chunk::Chunk, streaming::ChunkGenerator}; use horizon_world::registry::BlockRegistry; pub struct TestTerrain { - stone: u16, - dirt: u16, - grass: u16, - water: u16, - sand: u16, - bedrock: u16, - log: u16, - leaves: u16, - short_grass: u16, + stone: u32, + dirt: u32, + grass: u32, + water: u32, + sand: u32, + bedrock: u32, + log: u32, + leaves: u32, + short_grass: u32, plains: u16, } impl TestTerrain { pub fn new(registry: &BlockRegistry, biomes: &crate::biome::Biomes) -> crate::Result { - let id = |name: &str| -> crate::Result { + let id = |name: &str| -> crate::Result { Ok(registry .default_state(name) .ok_or_else(|| format!("missing {name}"))? - .0 as u16) + .0) }; Ok(Self { stone: id("minecraft:stone")?, @@ -41,7 +41,7 @@ impl TestTerrain { ] .into(), })? - .0 as u16, + .0, short_grass: id("minecraft:short_grass")?, plains: biomes.id("minecraft:plains"), }) diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index e9710e442..ea11d4163 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -233,6 +233,10 @@ impl Text { } /// The `Component` as vanilla's JSON (ComponentSerialization): the one /// built through the constructors, else the spans as literal siblings. + /// The key of a `Component.translatable` built through [`Text::translate`]. + pub fn translation_key(&self) -> Option<&str> { + self.source.as_deref()?.get("translate")?.as_str() + } pub fn component(&self) -> Value { if let Some(c) = &self.source { return (**c).clone(); @@ -263,6 +267,18 @@ impl Text { _ => c, } } + /// Style fields the spans don't model (an entity hover, an insertion), + /// set on the component sent to vanilla only. + pub fn with_component_fields(mut self, fields: Vec<(String, Value)>) -> Self { + let mut c = self.component(); + if let Value::Object(o) = &mut c { + for (k, v) in fields { + o.entry(k).or_insert(v); + } + } + self.source = Some(c.into()); + self + } pub fn with_color(self, color: u32) -> Self { self.with_style(&Style::color(color)) } diff --git a/crates/horizon-client/src/vanillagen.rs b/crates/horizon-client/src/vanillagen.rs index 6f0c4edaf..6c94ea67d 100644 --- a/crates/horizon-client/src/vanillagen.rs +++ b/crates/horizon-client/src/vanillagen.rs @@ -56,6 +56,19 @@ impl VanillaTerrain { biomes: &Biomes, seed: i64, dimension: &str, + ) -> crate::Result { + Self::for_world(dir, registry, biomes, seed, dimension, true) + } + /// A dimension of a world whose `generate_structures` is `structures` + /// (`ChunkGenerator.createStructures` and `findNearestMapStructure` do + /// nothing without). + pub fn for_world( + dir: &Path, + registry: &'static BlockRegistry, + biomes: &Biomes, + seed: i64, + dimension: &str, + structures: bool, ) -> crate::Result { let data: Arc = shared_data(dir, registry)?; let biome_map = data @@ -64,7 +77,7 @@ impl VanillaTerrain { .map(|name| biomes.id(name)) .collect(); let generator = - OverworldGenerator::for_dimension(data, seed, "minecraft:normal", dimension)?; + OverworldGenerator::for_world(data, seed, "minecraft:normal", dimension, structures)?; let unsupported = generator.unsupported_features(); if !unsupported.is_empty() { log::warn!( @@ -119,7 +132,7 @@ impl VanillaTerrain { chunk.terrain.min_y().max(MIN_Y), (chunk.terrain.min_y() + chunk.terrain.height()).min(MIN_Y + HEIGHT), ); - let mut values = Box::new([0u16; 4096]); + let mut values = Box::new([0u32; 4096]); for si in 0..SECTIONS as i32 { let base = MIN_Y + si * 16; if base + 16 <= lo || base >= hi { @@ -130,7 +143,7 @@ impl VanillaTerrain { for y in base.max(lo)..(base + 16).min(hi) { for z in 0..16 { for x in 0..16 { - let id = chunk.block(bx + x, y, bz + z).0 as u16; + let id = chunk.block(bx + x, y, bz + z).0; values[((y & 15) << 8 | z << 4 | x) as usize] = id; any |= id != 0; } diff --git a/crates/horizon-client/src/window.rs b/crates/horizon-client/src/window.rs index 7c77d85c6..33ff52111 100644 --- a/crates/horizon-client/src/window.rs +++ b/crates/horizon-client/src/window.rs @@ -128,6 +128,20 @@ pub fn vsync_present_mode(supported: &[PresentMode], vsync: bool) -> Option, +) -> Option { + setting + .filter(|m| !vsync && supported.contains(m)) + .or_else(|| vsync_present_mode(supported, vsync)) +} + /// `FramerateLimiter.limitDisplayFPS` with an injectable clock so the sleep /// and spin decisions are testable. #[derive(Clone, Debug)] @@ -415,4 +429,23 @@ mod tests { Some(PresentMode::Fifo) ); } + #[test] + fn vsync_on_waits_for_the_display_whatever_the_present_mode() { + use PresentMode::*; + let all = [Mailbox, Fifo, Immediate]; + for setting in [None, Some(Fifo), Some(Mailbox), Some(Immediate)] { + assert_eq!(chosen_present_mode(&all, true, setting), Some(Fifo)); + } + assert_eq!(chosen_present_mode(&all, false, None), Some(Immediate)); + assert_eq!( + chosen_present_mode(&all, false, Some(Mailbox)), + Some(Mailbox) + ); + assert_eq!(chosen_present_mode(&all, false, Some(Fifo)), Some(Fifo)); + // Metal has no Mailbox: vanilla's choice instead. + assert_eq!( + chosen_present_mode(&[Fifo, Immediate], false, Some(Mailbox)), + Some(Immediate) + ); + } } diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index 44e442ec1..f6fbcd04d 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -21,12 +21,13 @@ pub struct World { pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>, /// Edits on lit chunks (position, old state, new state), relit /// incrementally by streaming. - pub light_edits: Vec<((i32, i32, i32), u16, u16)>, + pub light_edits: Vec<((i32, i32, i32), u32, u32)>, /// Saved entities of chunks that just loaded, spawned by the game. pub loaded_entities: Vec<((i32, i32), Vec)>, /// Chunks changed since the last save. pub modified: HashSet<(i32, i32)>, - pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>, + /// Block entities, and the order they tick in. + pub block_entities: crate::block_entities::BlockEntities, /// Each chest's `ContainerOpenersCounter`: opener count and largest /// interaction range. pub chest_openers: HashMap<(i32, i32, i32), (i32, f64)>, @@ -36,7 +37,7 @@ pub struct World { /// blocks, which need a block entity). pub watched: Vec, /// Writes of watched states: position, previous and new state. - pub watched_writes: Vec<((i32, i32, i32), u16, u16)>, + pub watched_writes: Vec<((i32, i32, i32), u32, u32)>, /// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent /// within spawning range (local difficulty). pub inhabited: HashMap<(i32, i32), i64>, @@ -122,7 +123,7 @@ impl World { light_edits: Vec::new(), loaded_entities: Vec::new(), modified: HashSet::new(), - block_entities: HashMap::new(), + block_entities: Default::default(), chest_openers: HashMap::new(), block_names: HashMap::new(), watched: Vec::new(), @@ -198,12 +199,13 @@ impl World { if y < MIN_Y || y >= MIN_Y + (SECTIONS as i32) * 16 { return Err("write outside world height".into()); } - let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0 as u16); - if u32::from(previous) != state.0 { - let watches = |id: u16| self.watched.get(usize::from(id)).copied().unwrap_or(false); - if watches(previous) || watches(state.0 as u16) { - self.watched_writes - .push(((x, y, z), previous, state.0 as u16)); + let previous = Arc::make_mut(chunk).set(x & 15, y, z & 15, state.0); + if previous != state.0 { + self.block_entities + .state_changed((x, y, z), previous, state.0); + let watches = |id: u32| self.watched.get(id as usize).copied().unwrap_or(false); + if watches(previous) || watches(state.0) { + self.watched_writes.push(((x, y, z), previous, state.0)); } self.revision = self.revision.wrapping_add(1); if let Some(log) = &mut self.block_log { @@ -225,7 +227,7 @@ impl World { } let _ = sy; if self.chunks.get(&(x >> 4, z >> 4)).is_some_and(|c| c.lit) { - self.light_edits.push(((x, y, z), previous, state.0 as u16)); + self.light_edits.push(((x, y, z), previous, state.0)); } else { for dz in -1..=1 { for dx in -1..=1 { @@ -241,6 +243,16 @@ impl World { .get(&(x >> 4, z >> 4)) .map_or(self.air, |chunk| chunk.block(x & 15, y, z & 15)) } + /// The block entities to tick this tick, in order (`BlockEntities::tickers`). + pub fn block_entity_tickers(&mut self) -> Vec<(crate::block_entities::Pos, u32)> { + let (chunks, air) = (&self.chunks, self.air); + self.block_entities.tickers(|(x, y, z)| { + chunks + .get(&(x >> 4, z >> 4)) + .map_or(air, |chunk| chunk.block(x & 15, y, z & 15)) + .0 + }) + } pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { self.chunks .get(&(x >> 4, z >> 4)) diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 36f53444c..7a8209939 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -38,7 +38,7 @@ fn resources() -> Option { root.join("items.json").exists().then_some(root) } -const STONE: u16 = 1; +const STONE: u32 = 1; fn flat_world() -> World { let mut world = World::new(BlockStateId(0), 0); @@ -163,7 +163,7 @@ struct Server { hub: Hub, world: World, next_entity: u32, - placed: Vec<(u32, [i32; 3], u16, i32)>, + placed: Vec<(u32, [i32; 3], u32, i32)>, } impl Server { fn tick(&mut self, entities: &[EntityState]) { @@ -193,6 +193,7 @@ impl Server { clock_rate: 1.0, tick_rate: 20.0, tick_frozen: false, + collision: None, }; let events = self.hub.tick(&mut ctx); for event in events { @@ -202,7 +203,7 @@ impl Server { if let S::UseItemOn(p) = *packet { let at = [p.pos[0], p.pos[1] + 1, p.pos[2]]; ctx.world - .set(at[0], at[1], at[2], BlockStateId(u32::from(STONE))) + .set(at[0], at[1], at[2], BlockStateId(STONE)) .unwrap(); self.placed.push((conn, at, STONE, p.sequence)); self.hub.ack(conn, p.sequence); @@ -341,14 +342,12 @@ fn status_and_join() { C::PlayerInfoUpdate(u) => { info |= u.entries.iter().any(|e| e.name.as_deref() == Some("Host")); } - C::Unknown(id, _) if id == horizon_protocol::ids::play::clientbound::COMMANDS => { - commands = true - } + C::Commands(_) => commands = true, C::LevelChunkWithLight(l) => { chunks += 1; let sections = l.chunk.sections(24, 16, 7).map_err(|e| e.to_string())?; // The floor is in the lowest section. - assert_eq!(sections[0].states.get(4 * 256), i32::from(STONE)); + assert_eq!(sections[0].states.get(4 * 256), STONE as i32); assert_eq!(sections[0].non_empty, 256); assert_eq!(sections[1].non_empty, 0); assert!(!l.light.sky.is_empty()); @@ -394,7 +393,7 @@ fn status_and_join() { assert!(chunks >= 9, "only {chunks} chunks"); assert_eq!( block_update, - Some(([9, MIN_Y + 5, 9], i32::from(STONE))), + Some(([9, MIN_Y + 5, 9], STONE as i32)), "placed block was not broadcast" ); Ok(bot.name) @@ -423,6 +422,7 @@ fn guests_see_each_other_and_the_world_entities() { data: 0, meta: Vec::new(), equipment: Vec::new(), + precise: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 74edd5049..6804d197e 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -107,7 +107,7 @@ fn columns_loaded_past_the_render_distance_mesh_when_they_come_in_range() { /// A one-block cave under the sky: a stone floor at y 62 with a glowstone, /// and a roof at y 64 with holes, so that every light change in the cave is /// sampled by a face. -fn roofed(x: i32, z: i32, stone: u16, glowstone: u16) -> Chunk { +fn roofed(x: i32, z: i32, stone: u32, glowstone: u32) -> Chunk { let mut chunk = Chunk::empty(x, z); for lz in 0..16 { for lx in 0..16 { @@ -143,7 +143,7 @@ fn relit_columns_keep_every_mesh_current() { biomes: Arc::new(Biomes::load(&root).unwrap()), assets: assets.clone(), }); - let state = |name: &str| assets.registry.default_state(name).unwrap().0 as u16; + let state = |name: &str| assets.registry.default_state(name).unwrap().0; let (stone, glowstone, torch) = ( state("minecraft:stone"), state("minecraft:glowstone"), @@ -185,9 +185,7 @@ fn relit_columns_keep_every_mesh_current() { let (bx, bz) = (16 + lx, lz); world.set(bx, 64, bz, BlockStateId(0)).unwrap(); if i % 3 == 0 { - world - .set(bx, 63, bz, BlockStateId(u32::from(torch))) - .unwrap(); + world.set(bx, 63, bz, BlockStateId(torch)).unwrap(); } } } diff --git a/crates/horizon-client/tests/wide_states.rs b/crates/horizon-client/tests/wide_states.rs new file mode 100644 index 000000000..690732ceb --- /dev/null +++ b/crates/horizon-client/tests/wide_states.rs @@ -0,0 +1,40 @@ +//! Block states past vanilla's 16-bit global palette (docs/modpacks.md): +//! content mods can take the registry past 65,536 states. Its own test binary, +//! since the palette width is set once for the whole process. + +use horizon_client::chunk::{Chunk, Section, block_strategy, set_block_states}; + +#[test] +fn sections_hold_states_past_sixteen_bits() { + // Vanilla's width until the registry needs more (one test: the width is + // global to the process). + assert_eq!(block_strategy().global_bits, 16); + set_block_states(35_723); + assert_eq!(block_strategy().global_bits, 16); + set_block_states(100_000); + assert_eq!(block_strategy().global_bits, 17); + + // A few states past 65,536 stay in the section's own palette. + let mut chunk = Chunk::empty(0, 0); + chunk.set(1, 70, 2, 70_000); + chunk.set(3, 70, 4, 99_999); + assert_eq!(chunk.get(1, 70, 2), 70_000); + assert_eq!(chunk.get(3, 70, 4), 99_999); + assert_eq!(chunk.get(0, 70, 0), 0); + + // More than 256 distinct states take the global palette at 17 bits. + let mut values = [0u32; 4096]; + for (i, v) in values.iter_mut().enumerate() { + *v = 65_000 + (i as u32 % 1000) * 30; + } + let mut section = Section { + blocks: Section::from_blocks(&values), + ..Section::default() + }; + let mut out = [0u32; 4096]; + section.unpack(&mut out); + assert_eq!(out, values); + section.set(17, 99_998); + assert_eq!(section.get(17), 99_998); + assert_eq!(section.get(18), values[18]); +} diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index f162404f5..5c0ec374c 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -391,17 +391,24 @@ impl PalettedContainer { assert_eq!(out.len(), self.strategy.entries()); match &self.palette { Palette::Single(value) => out.fill(*value), - palette => { + Palette::List(list) => { let bits = usize::from(self.bits); let per = 64 / bits; let m = mask(self.bits); for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { for (slot, cell) in chunk.iter_mut().enumerate() { - let id = ((word >> (slot * bits)) & m) as u32; - *cell = match palette { - Palette::List(list) => list[id as usize], - _ => id, - }; + let id = ((word >> (slot * bits)) & m) as usize; + *cell = list[id]; + } + } + } + Palette::Global => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + *cell = ((word >> (slot * bits)) & m) as u32; } } } @@ -412,17 +419,24 @@ impl PalettedContainer { debug_assert_eq!(self.strategy.entries(), 4096); match &self.palette { Palette::Single(value) => out.fill(*value as u16), - palette => { + Palette::List(list) => { let bits = usize::from(self.bits); let per = 64 / bits; let m = mask(self.bits); for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { for (slot, cell) in chunk.iter_mut().enumerate() { let id = ((word >> (slot * bits)) & m) as usize; - *cell = match palette { - Palette::List(list) => list[id] as u16, - _ => id as u16, - }; + *cell = list[id] as u16; + } + } + } + Palette::Global => { + let bits = usize::from(self.bits); + let per = 64 / bits; + let m = mask(self.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&self.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + *cell = ((word >> (slot * bits)) & m) as u16; } } } @@ -738,4 +752,80 @@ mod tests { } } } + + /// The pre-optimization `unpack`, kept to compare against in the benchmark. + fn baseline_unpack(c: &PalettedContainer, out: &mut [u32]) { + match &c.palette { + Palette::Single(value) => out.fill(*value), + palette => { + let bits = usize::from(c.bits); + let per = 64 / bits; + let m = mask(c.bits); + for (chunk, &word) in out.chunks_mut(per).zip(&c.words) { + for (slot, cell) in chunk.iter_mut().enumerate() { + let id = ((word >> (slot * bits)) & m) as u32; + *cell = match palette { + Palette::List(list) => list[id as usize], + _ => id, + }; + } + } + } + } + } + + /// `unpack` against the pre-optimization implementation, for a list palette + /// and the global palette. The result is checked before timing; 25 measured + /// rounds alternate order and report the median and best microsecond-per-call. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_unpack() { + use std::{hint::black_box, time::Instant}; + let values: Vec = (0..4096).map(|i| (i % 12) as u32).collect(); + let list = PalettedContainer::from_values(BLOCKS, &values); + let global = PalettedContainer::from_values( + BLOCKS, + &(0..4096).map(|i| (i * 3) as u32).collect::>(), + ); + for (name, container) in [("list", &list), ("global", &global)] { + let mut expected = vec![0u32; 4096]; + baseline_unpack(container, &mut expected); + let mut out = vec![0u32; 4096]; + container.unpack(&mut out); + assert_eq!(expected, out, "unpack {name} differs"); + let mut times = [Vec::new(), Vec::new()]; + for round in 0..25 { + for optimized in [round % 2 == 0, round % 2 != 0] { + let started = Instant::now(); + for _ in 0..2000 { + if optimized { + container.unpack(black_box(&mut out)); + } else { + baseline_unpack(black_box(container), black_box(&mut out)); + } + } + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e6 / 2000.0); + } + } + } + for values in &mut times { + values.sort_by(f64::total_cmp); + } + let median = |v: &[f64]| v[v.len() / 2]; + println!( + "unpack {name} median: baseline {:.3} us optimized {:.3} us speedup {:.3}x", + median(×[0]), + median(×[1]), + median(×[0]) / median(×[1]) + ); + println!( + "unpack {name} best: baseline {:.3} us optimized {:.3} us speedup {:.3}x", + times[0][0], + times[1][0], + times[0][0] / times[1][0] + ); + } + } } diff --git a/crates/horizon-core/src/storage.rs b/crates/horizon-core/src/storage.rs index 61f8c505f..6b8a8ec38 100644 --- a/crates/horizon-core/src/storage.rs +++ b/crates/horizon-core/src/storage.rs @@ -88,6 +88,28 @@ impl PackedStorage { Ok(((self.words[word] >> shift) & self.mask) as u32) } + /// Reads `index` without a bounds check. Callers use this once they hold a + /// slice length or a section index they have already validated. + /// `index` must be less than `len`. + pub fn read(&self, index: usize) -> u32 { + debug_assert!(index < self.len); + let word = index / self.per_word; + let shift = (index % self.per_word) * usize::from(self.bits); + ((self.words[word] >> shift) & self.mask) as u32 + } + + /// Writes `value` at `index` without revalidating either. `index` must be + /// less than `len` and `value` must fit `bits`, which holds for a section + /// palette index from the same container. Returns the previous value. + pub fn write(&mut self, index: usize, value: u32) -> u32 { + debug_assert!(index < self.len && u64::from(value) <= self.mask); + let word = index / self.per_word; + let shift = (index % self.per_word) * usize::from(self.bits); + let old = ((self.words[word] >> shift) & self.mask) as u32; + self.words[word] = (self.words[word] & !(self.mask << shift)) | (u64::from(value) << shift); + old + } + /// Validation fails before mutation. Writes accept nonnegative Java ints; /// imported 32-bit words may still decode to any u32 bit pattern. pub fn set(&mut self, index: usize, value: u32) -> Result { diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs index 40b641759..9afe95d0a 100644 --- a/crates/horizon-mods/src/content.rs +++ b/crates/horizon-mods/src/content.rs @@ -192,6 +192,13 @@ impl Content { Ok(content) } + /// Where the files are read from: the mod's folder or its `.hmod`. + pub fn source(&self) -> &Path { + match &self.source { + Source::Dir(path) | Source::Zip(path) => path, + } + } + /// No files: a mod with code only. pub fn is_empty(&self) -> bool { self.files.is_empty() diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index dfe4d3dbc..c73570684 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -25,6 +25,9 @@ pub struct Report { pub unreadable: BTreeMap, pub recipes_upgraded: usize, pub loot_tables_upgraded: usize, + /// Blocks whose jar has no loot table but drop themselves in the oracle: + /// the mod registers that table in code, and carry-over writes it. + pub loot_tables_added: usize, /// Worldgen and structure files (`data//worldgen/`, `structure/`). pub worldgen: usize, /// Recipes left as they were: custom types, NeoForge conditions. @@ -44,6 +47,11 @@ pub struct Report { pub items_unknown: BTreeMap, /// Convention (`c:`) tags the recipes use, filled in from the oracle. pub convention_tags: usize, + /// Structure, placement and pool element types rewritten as vanilla's, + /// and those left as they are. + pub worldgen_types: crate::worldgen::Upgrade, + /// The loader's convention biome tags the structures name, carried. + pub convention_biome_tags: usize, } /// Vanilla blocks by their sorted property names. @@ -330,6 +338,7 @@ pub fn carry( out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, + conventions: &BTreeMap, ) -> Result { let id = &info.mod_id; if id.is_empty() @@ -351,6 +360,9 @@ pub fn carry( let mut blockstates: BTreeMap = BTreeMap::new(); let mut item_models = BTreeSet::new(); let mut convention = BTreeSet::new(); + let mut block_loot = BTreeSet::new(); + let mut biome_conventions = BTreeSet::new(); + let set_tags = crate::worldgen::structure_set_tags(&mut zip); for i in 0..zip.len() { let mut entry = zip.by_index(i).map_err(|e| e.to_string())?; let name = entry.name().to_owned(); @@ -400,7 +412,32 @@ pub fn carry( report.recipes_kept.push(file.to_owned()); } } + } else if let Some(kind) = rel + .strip_prefix("worldgen/") + .and_then(|r| r.split_once('/')) + .map(|(kind, _)| kind) + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + if let Ok(mut v) = serde_json::from_slice::(&bytes) { + if kind == "structure" { + crate::worldgen::convention_tags(&v["biomes"], &mut biome_conventions); + } + if crate::worldgen::upgrade(kind, &mut v, &mut report.worldgen_types, &set_tags) + { + bytes = serde_json::to_vec_pretty(&v).unwrap_or(bytes); + } + } + } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { + if let Ok(v) = serde_json::from_slice::(&bytes) { + crate::worldgen::convention_tags(&v, &mut biome_conventions); + } } else if rel.starts_with("loot_table/") && name.starts_with("data/") { + if let Some(b) = rel + .strip_prefix("loot_table/blocks/") + .and_then(|b| b.strip_suffix(".json")) + { + block_loot.insert(b.to_owned()); + } if let Ok(mut table) = serde_json::from_slice::(&bytes) { let before = table.clone(); upgrade_loot(&mut table); @@ -435,6 +472,18 @@ pub fn carry( report.item_definitions_added += 1; } } + // The loader's convention biome tags the structures and their tags name + // (NeoForge's `c:is_plains`...): the game has no loader, so they come along. + for tag in crate::worldgen::with_included(&biome_conventions, conventions) { + let file = inside.join(format!("data/c/tags/worldgen/biome/{tag}.json")); + if !file.exists() { + write( + &file, + &serde_json::to_vec_pretty(&conventions[&tag]).unwrap_or_default(), + )?; + report.convention_biome_tags += 1; + } + } let decl = inside.join(format!("data/{id}/horizon")); let write_decl = |kind: &str, name: &str, v: &Value| { let text = serde_json::to_vec_pretty(v).unwrap_or_default(); @@ -470,6 +519,34 @@ pub fn carry( .push(format!("its item is {}", block.item)); } else { declared.insert(full.clone()); + let drop = (!block_loot.contains(b)) + .then(|| block.drops_itself(full)) + .flatten(); + if let Some(drop) = drop { + let mut entry = json!({"type": "minecraft:item", "name": full}); + if let crate::oracle::SelfDrop::When(property, value) = drop { + entry["condition"] = json!({ + "type": "minecraft:match_block", + "blocks": full, + "state": {property: value} + }); + } + let table = json!({ + "type": "minecraft:block", + "pools": [{ + "condition": {"type": "minecraft:survives_explosion"}, + "entries": [entry], + "rolls": 1 + }], + "random_sequence": format!("{id}:blocks/{b}") + }); + let file = inside.join(format!("data/{id}/loot_table/blocks/{b}.json")); + write( + &file, + &serde_json::to_vec_pretty(&table).unwrap_or_default(), + )?; + report.loot_tables_added += 1; + } } write_decl("block", b, &v)?; report.blocks.insert(b.to_owned(), choice.template); @@ -781,7 +858,7 @@ mod tests { ); assert_eq!(info.census.classes, 1); let out = dir.join("work/mods/gem"); - let report = carry(&jar, &info, &out, None, &|_| true).unwrap(); + let report = carry(&jar, &info, &out, None, &|_| true, &BTreeMap::new()).unwrap(); assert_eq!(report.copied, 13); let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect(); assert_eq!( diff --git a/crates/horizon-port-pack/src/fetch.rs b/crates/horizon-port-pack/src/fetch.rs index 011e99e1f..f8f7b2dc7 100644 --- a/crates/horizon-port-pack/src/fetch.rs +++ b/crates/horizon-port-pack/src/fetch.rs @@ -139,6 +139,28 @@ pub fn fetch( } fetched.files.push(o); } + // The loader's own data (its convention tags), from its own repository. + if let Some((dest, url)) = crate::worldgen::loader_jar(work, &pack.loader, &pack.loader_version) + .filter(|(dest, _)| !dest.exists()) + { + let sha1 = ureq::get(&format!("{url}.sha1")) + .set("User-Agent", modrinth::AGENT) + .call() + .ok() + .and_then(|r| r.into_string().ok()) + .map(|s| s.trim().to_owned()); + let made = dest.parent().map(fs::create_dir_all); + match made + .unwrap_or(Ok(())) + .map_err(|e| e.to_string()) + .and_then(|()| download(&url, sha1.as_deref(), &dest)) + { + Ok(()) => log(format!("loader: {}", dest.display())), + Err(e) => log(format!( + "loader: {e} (structures keep only vanilla biome tags)" + )), + } + } write_json(&work.join("fetch.json"), &fetched)?; log(format!( "jars: {} downloaded, {} copied, {} already here, {} need a CurseForge key, {} not found, {} failed", diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index ecd61956c..0e678fb9a 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -15,3 +15,4 @@ pub mod modrinth; pub mod oracle; pub mod pipeline; pub mod report; +pub mod worldgen; diff --git a/crates/horizon-port-pack/src/oracle.rs b/crates/horizon-port-pack/src/oracle.rs index 1fa9a717c..7e04aa9ef 100644 --- a/crates/horizon-port-pack/src/oracle.rs +++ b/crates/horizon-port-pack/src/oracle.rs @@ -60,6 +60,10 @@ pub struct State { pub sound: Value, pub outline: Value, pub collision: Value, + /// What breaking the state drops, per tool (`hand`, `diamond_pickaxe`, + /// `shears`, `silk_touch_pickaxe`...): item id → count. + #[serde(default)] + pub drops: BTreeMap>, } #[derive(Debug, Deserialize)] @@ -76,6 +80,23 @@ pub struct Item { const VANILLA_PACKAGE: &str = "net.minecraft."; /// A state key with its properties sorted, so keys compare across blocks. +/// Which states of a block drop the block itself. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SelfDrop { + /// Every state: `dropSelf`. + Always, + /// Only the states where this property has this value. + When(String, String), +} + +/// A state key's `property=value` pairs. +fn pairs(key: &str) -> BTreeSet<(String, String)> { + key.split(',') + .filter_map(|p| p.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect() +} + pub fn state_key(key: &str) -> String { let mut parts: Vec<&str> = key.split(',').filter(|p| !p.is_empty()).collect(); parts.sort_unstable(); @@ -96,6 +117,45 @@ impl Block { .first() .is_some_and(|c| !c.starts_with(VANILLA_PACKAGE)) } + /// Every state drops one `item` (the block's own) with every tool, except + /// where the state needs a tool and gets none: vanilla's `dropSelf`. Or + /// only the states where one property has one value do, and the others + /// drop nothing with any tool: a door's lower half (`createDoorTable`). + /// Mods often register these tables in code, so their jar has no file. + pub fn drops_itself(&self, item: &str) -> Option { + let one = BTreeMap::from([(item.to_owned(), 1)]); + let (mut dropping, mut nothing) = (Vec::new(), Vec::new()); + for (key, state) in &self.states { + if state.drops.is_empty() { + continue; + } + let mut drops = false; + let mut short = false; + for got in state.drops.values() { + if *got == one { + drops = true; + } else if got.is_empty() { + short = true; + } else { + return None; + } + } + match (drops, short) { + (true, true) if !state.requires_tool => return None, + (true, _) => dropping.push(pairs(key)), + (false, _) => nothing.push(pairs(key)), + } + } + let (first, rest) = dropping.split_first()?; + if nothing.is_empty() { + return Some(SelfDrop::Always); + } + first + .iter() + .filter(|pair| rest.iter().all(|s| s.contains(*pair))) + .find(|pair| nothing.iter().all(|s| !s.contains(*pair))) + .map(|(p, v)| SelfDrop::When(p.clone(), v.clone())) + } fn default_state(&self) -> Option<&State> { self.states .get(&self.default) @@ -373,6 +433,65 @@ mod tests { assert_eq!(tile.differences[0], "sounds: no vanilla block has them"); } + #[test] + fn drops_itself_is_vanillas_drop_self() { + let cube = json!([[0, 0, 0, 1, 1, 1]]); + let with = |requires_tool: bool, drops: Value| { + let mut s = state(1.5, "stone", cube.clone()); + s["requires_tool"] = json!(requires_tool); + s["drops"] = drops; + let b: Block = serde_json::from_value(block(&[], json!({}), json!({"": s}))).unwrap(); + b.drops_itself("m:tile") + }; + let me = json!({"m:tile": 1}); + let always = Some(SelfDrop::Always); + assert_eq!(with(false, json!({"hand": me, "shears": me})), always); + // A state that needs a tool drops nothing by hand, as dropSelf does. + assert_eq!( + with(true, json!({"hand": {}, "diamond_pickaxe": me})), + always + ); + assert_eq!( + with(false, json!({"hand": {}, "diamond_pickaxe": me})), + None + ); + // Two of itself (a double slab), or something else, is not dropSelf. + assert_eq!(with(false, json!({"hand": {"m:tile": 2}})), None); + assert_eq!(with(false, json!({"hand": {"m:other": 1}})), None); + assert_eq!(with(false, json!({})), None); + } + + #[test] + fn a_door_drops_from_its_lower_half() { + let cube = json!([[0, 0, 0, 1, 1, 1]]); + let me = json!({"hand": {"m:door": 1}, "shears": {"m:door": 1}}); + let none = json!({"hand": {}, "shears": {}}); + let door = |upper: &Value| { + let mut states = serde_json::Map::new(); + for (key, drops) in [ + ("half=lower,open=false", &me), + ("half=lower,open=true", &me), + ("half=upper,open=false", upper), + ("half=upper,open=true", upper), + ] { + let mut s = state(3.0, "wood", cube.clone()); + s["drops"] = drops.clone(); + states.insert(key.to_owned(), s); + } + let props = json!({"half": ["upper", "lower"], "open": ["true", "false"]}); + let b: Block = + serde_json::from_value(block(&[], props, Value::Object(states))).unwrap(); + b.drops_itself("m:door") + }; + assert_eq!( + door(&none), + Some(SelfDrop::When("half".to_owned(), "lower".to_owned())) + ); + assert_eq!(door(&me), Some(SelfDrop::Always)); + // Something else from the upper half: not a door table. + assert_eq!(door(&json!({"hand": {"m:other": 1}})), None); + } + #[test] fn state_keys_sort() { assert_eq!( diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 80a88ee18..3afe5b3a3 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -119,6 +119,7 @@ pub fn carry( .ok() }); let allowed = |b: &str| vanilla.as_ref().is_none_or(|v| v.contains(b)); + let conventions = crate::worldgen::loader_biome_tags(work); let mut done = 0; for r in &records { let chosen = if only.is_empty() { @@ -154,16 +155,18 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, + &conventions, ) { Ok(report) => { done += 1; log(format!( - "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded, {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", + "{}: {} files, {} recipes upgraded ({} kept), {} loot tables upgraded ({} added), {} item definitions added, {} blocks ({} left out, {} with differences), {} items ({} left out), {} convention tags, {} outside", r.key, report.copied, report.recipes_upgraded, report.recipes_kept.len(), report.loot_tables_upgraded, + report.loot_tables_added, report.item_definitions_added, report.blocks.len(), report.blocks_unknown.len(), diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs new file mode 100644 index 000000000..25e0dbbea --- /dev/null +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -0,0 +1,702 @@ +//! Structure mods' worldgen, carried over: block and fluid states in 26.3's +//! shape, the structure, placement and pool element types of the common +//! structure libraries rewritten as vanilla's, and the loader's convention +//! biome tags (`c:`) the structures name. +//! +//! The libraries' types add rules on top of vanilla's. The start and +//! placement rules of Repurposed Structures' and Moog's jigsaws (no start in +//! liquid, biomes and terrain height in a radius, a minimum distance from +//! the world origin, sets to keep away from) are written under `horizon:` +//! keys the game reads (`horizon_world::worldgen::structure::start_checks`), +//! so those structures start where the mod would. Rules that change how the +//! pieces are laid out (piece caps, burying, clipping) are lost and counted +//! by name. Each rewrite is counted in the carry report, and every type left +//! as it is is listed, so the coverage report can say what generates and how +//! closely. +use serde_json::Value; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::Read, + path::{Path, PathBuf}, +}; + +/// Structure types that are vanilla's jigsaw with extra start rules. +const JIGSAWS: [&str; 3] = [ + "lithostitched:jigsaw", + "moogs_structures:moogs_structures_generic_jigsaw_structure", + "repurposed_structures:generic_jigsaw_structure", +]; +/// Placements that are vanilla's random spread with extra rules. +const SPREADS: [&str; 2] = [ + "moogs_structures:advanced_random_spread", + "repurposed_structures:advanced_random_spread", +]; +/// Moog's Structure Lib spreads its structures 1.65 times as far apart as +/// its files say (AdvancedRandomSpread's constructor). +const MOOGS_SPACING: f64 = 1.65; +/// The jigsaws' start rules and the `horizon:start_checks` key each maps to. +const START_RULES: [(&str, &str); 3] = [ + ("valid_biome_radius_check", "biome_radius"), + ("terrain_height_radius_check", "terrain_radius"), + ("allowed_terrain_height_range", "terrain_range"), +]; +/// The jigsaws' rules on laying out pieces, which vanilla's jigsaw has no +/// place for. +const LAYOUT_RULES: [&str; 6] = [ + "y_allowance", + "burying_type", + "use_bounding_box_hack", + "pools_that_ignore_boundaries", + "enhanced_terrain_adaptation", + "vertical_distance_from_start_piece", +]; +/// Pool elements that are vanilla's with extra fields: (mod type, vanilla type). +const ELEMENTS: [(&str, &str); 3] = [ + ( + "moogs_structures:versioned_single_pool_element", + "minecraft:single_pool_element", + ), + ( + "repurposed_structures:legacy_ocean_bottom_single_pool_element", + "minecraft:legacy_single_pool_element", + ), + ("empty_pool_element", "minecraft:empty_pool_element"), +]; + +/// What carry-over did to a mod's worldgen files. +#[derive(Debug, Default, serde::Serialize)] +pub struct Upgrade { + /// Files rewritten to vanilla types. + pub mapped: usize, + /// Files whose block and fluid states were written in 26.3's shape. + pub block_states: usize, + /// Types left as they are (Horizon skips what it cannot run), by type. + pub unsupported: BTreeMap, + /// Rules of mapped types the game does not run, by field. + pub rules_lost: BTreeMap, + /// Processors written in Java, taken out of their lists, by type. + pub processors_dropped: BTreeMap, +} + +/// Rewrites one `data//worldgen//...` file in place; whether it +/// changed. +/// `set_tags` are the mod's structure set tags, expanded +/// ([`structure_set_tags`]). +pub fn upgrade( + kind: &str, + v: &mut Value, + report: &mut Upgrade, + set_tags: &BTreeMap>, +) -> bool { + let states = block_states(v); + report.block_states += usize::from(states); + let dropped = match kind { + "processor_list" => drop_java_processors(v, &mut report.processors_dropped), + "template_pool" => { + let mut changed = false; + for e in v["elements"].as_array_mut().into_iter().flatten() { + let element = &mut e["element"]; + if let Some(list) = element.get_mut("elements").and_then(Value::as_array_mut) { + for inner in list { + if let Some(p) = inner.get_mut("processors") { + changed |= drop_java_processors(p, &mut report.processors_dropped); + } + } + } else if let Some(p) = element.get_mut("processors") { + changed |= drop_java_processors(p, &mut report.processors_dropped); + } + } + changed + } + _ => false, + }; + upgrade_types(kind, v, report, set_tags) || states || dropped +} + +/// Takes the processors written in Java (any type outside `minecraft:`) +/// out of a processor list: `{"processors": [...]}`, a bare list, or an id +/// (left as it is). The game, like vanilla, refuses a list holding a type it +/// does not know, and with it every pool that names the list, so without +/// this the structure does not generate at all. Without them it generates +/// undecorated: no pillars under it, spawners left as the template has +/// them, blocks not swapped. Whether anything was taken out. +fn drop_java_processors(list: &mut Value, dropped: &mut BTreeMap) -> bool { + let processors = match list { + Value::Array(a) => a, + Value::Object(o) => match o.get_mut("processors") { + Some(Value::Array(a)) => a, + _ => return false, + }, + _ => return false, + }; + let before = processors.len(); + processors.retain(|p| { + let t = p["processor_type"].as_str().unwrap_or_default(); + let java = !t.starts_with("minecraft:"); + if java { + *dropped.entry(t.to_owned()).or_default() += 1; + } + !java + }); + processors.len() != before +} + +/// 1.21.1 writes a block or fluid state as `{"Name": ..., "Properties": +/// {...}}`; 26.3's codec reads `{"id": ..., "properties": {...}}` and +/// refuses the old shape, which fails the processor list, feature or pool +/// holding it. Whether anything changed. +fn block_states(v: &mut Value) -> bool { + match v { + Value::Object(o) => { + let state = o.get("Name").is_some_and(Value::is_string) + && o.keys().all(|k| k == "Name" || k == "Properties"); + if state { + if let Some(name) = o.remove("Name") { + o.insert("id".into(), name); + } + if let Some(properties) = o.remove("Properties") { + o.insert("properties".into(), properties); + } + return true; + } + o.values_mut() + .fold(false, |changed, x| block_states(x) | changed) + } + Value::Array(a) => a + .iter_mut() + .fold(false, |changed, x| block_states(x) | changed), + _ => false, + } +} + +/// The library types of one file rewritten as vanilla's; whether it changed. +fn upgrade_types( + kind: &str, + v: &mut Value, + report: &mut Upgrade, + set_tags: &BTreeMap>, +) -> bool { + let lost = &mut report.rules_lost; + let mut unsupported = |t: &str| *report.unsupported.entry(t.to_owned()).or_default() += 1; + let changed = match kind { + "structure" => match v["type"].as_str() { + Some(t) if JIGSAWS.contains(&t) => { + let liquid = match t.split_once(':').map(|(ns, _)| ns) { + Some("moogs_structures") => "top", + _ => "lowest", + }; + start_checks(v, liquid, lost); + v["type"] = "minecraft:jigsaw".into(); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "structure_set" => match v["placement"]["type"].as_str() { + Some(t) if SPREADS.contains(&t) => { + let moogs = t.starts_with("moogs_structures:"); + let p = &mut v["placement"]; + if moogs { + moogs_spacing(p, lost); + } + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + true + } + Some(t) if !t.starts_with("minecraft:") => { + unsupported(t); + false + } + _ => false, + }, + "template_pool" => { + let mut changed = false; + let mut elements: Vec<&mut Value> = Vec::new(); + for e in v["elements"].as_array_mut().into_iter().flatten() { + let element = &mut e["element"]; + // A list element holds elements of its own. + if element.get("elements").is_some_and(Value::is_array) { + elements.extend(element["elements"].as_array_mut().into_iter().flatten()); + } else { + elements.push(element); + } + } + for element in elements { + let Some(t) = element["element_type"].as_str() else { + continue; + }; + if let Some((_, to)) = ELEMENTS.iter().find(|(from, _)| *from == t) { + element["element_type"] = (*to).into(); + changed = true; + } else if !t.starts_with("minecraft:") { + unsupported(t); + } + } + changed + } + _ => false, + }; + report.mapped += usize::from(changed); + changed +} + +/// Moves a Repurposed Structures or Moog's jigsaw's start rules under +/// `horizon:start_checks`, and counts the layout rules it loses. `liquid` is +/// the block its no-start-in-liquid rule reads. +fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap) { + let Some(o) = v.as_object_mut() else { + return; + }; + let mut checks = serde_json::Map::new(); + for (from, to) in START_RULES { + if let Some(n) = o.remove(from) { + checks.insert(to.into(), n); + } + } + if o.remove("cannot_spawn_in_liquid").and_then(|b| b.as_bool()) == Some(true) { + checks.insert("liquid".into(), liquid.into()); + } + // y_allowance bounds the terrain heights checked; it also clips pieces, + // which is lost. + for (from, to) in [("min_y_allowed", "min_y"), ("max_y_allowed", "max_y")] { + if let Some(n) = o.get("y_allowance").and_then(|y| y.get(from)) { + checks.insert(to.into(), n.clone()); + } + } + for rule in LAYOUT_RULES { + if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) { + *lost.entry(rule.into()).or_default() += 1; + } + } + if !checks.is_empty() { + o.insert("horizon:start_checks".into(), checks.into()); + } +} + +/// AdvancedRandomSpread's spacing and separation, as Moog's computes them +/// with its default config: 1.65 times the file's, rounded, the separation +/// below the spacing. `when_replacing` (other numbers while a preset +/// replaces a vanilla structure) is lost. +fn moogs_spacing(p: &mut Value, lost: &mut BTreeMap) { + let scaled = |k: &str| (p[k].as_f64().unwrap_or(0.) * MOOGS_SPACING).round() as i64; + let spacing = scaled("spacing").max(1); + let separation = scaled("separation").min(spacing - 1); + p["spacing"] = spacing.into(); + p["separation"] = separation.into(); + if let Some(o) = p.as_object_mut() { + if o.remove("when_replacing").is_some() { + *lost.entry("when_replacing".into()).or_default() += 1; + } + } +} + +/// An advanced random spread's minimum distance from the world origin and +/// its super exclusion zone (sets named by a tag) under `horizon:` keys. +fn placement_rules( + p: &mut Value, + set_tags: &BTreeMap>, + lost: &mut BTreeMap, +) { + let Some(o) = p.as_object_mut() else { + return; + }; + if let Some(d) = o.remove("min_distance_from_world_origin") { + o.insert("horizon:min_distance_from_world_origin".into(), d); + } + if let Some(zone) = o.remove("super_exclusion_zone") { + let sets: Vec = match &zone["other_set"] { + Value::String(s) => match s.strip_prefix('#') { + Some(tag) => set_tags.get(tag).cloned().unwrap_or_default(), + None => vec![s.clone()], + }, + Value::Array(a) => a + .iter() + .filter_map(|s| Some(s.as_str()?.to_owned())) + .collect(), + _ => Vec::new(), + }; + if sets.is_empty() { + *lost.entry("super_exclusion_zone".into()).or_default() += 1; + } else { + o.insert( + "horizon:exclusion_zone".into(), + serde_json::json!({"other_sets": sets, "chunk_count": zone["chunk_count"]}), + ); + } + } +} + +/// The mod's structure set tags (`data//tags/worldgen/structure_set/`), +/// by tag id, with the tags they include expanded. Optional entries +/// (`{"id": ..., "required": false}`) count as their id. +pub fn structure_set_tags( + zip: &mut zip::ZipArchive, +) -> BTreeMap> { + let mut raw: BTreeMap> = BTreeMap::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some(id) = entry + .name() + .strip_prefix("data/") + .and_then(|r| r.split_once("/tags/worldgen/structure_set/")) + .and_then(|(ns, path)| Some(format!("{ns}:{}", path.strip_suffix(".json")?))) + else { + continue; + }; + let mut text = String::new(); + let Ok(v) = entry.read_to_string(&mut text).map_err(drop).and_then(|_| { + serde_json::from_str::(text.trim_start_matches('\u{feff}')).map_err(drop) + }) else { + continue; + }; + let values = v["values"].as_array().into_iter().flatten(); + raw.insert( + id, + values + .filter_map(|e| e.as_str().or_else(|| e["id"].as_str()).map(str::to_owned)) + .collect(), + ); + } + let expand = |tag: &str| { + let (mut out, mut seen, mut todo) = (Vec::new(), BTreeSet::new(), vec![tag.to_owned()]); + while let Some(t) = todo.pop() { + if !seen.insert(t.clone()) { + continue; + } + for e in raw.get(&t).into_iter().flatten() { + match e.strip_prefix('#') { + Some(inner) => todo.push(inner.to_owned()), + None if !out.contains(e) => out.push(e.clone()), + None => {} + } + } + } + out + }; + raw.keys().map(|t| (t.clone(), expand(t))).collect() +} + +/// The `#c:` biome tags `v` names. +pub fn convention_tags(v: &Value, out: &mut BTreeSet) { + match v { + Value::String(s) => { + if let Some(tag) = s.strip_prefix("#c:") { + out.insert(tag.to_owned()); + } + } + Value::Array(a) => a.iter().for_each(|x| convention_tags(x, out)), + Value::Object(o) => o.values().for_each(|x| convention_tags(x, out)), + _ => {} + } +} + +/// The loader's own convention biome tags (`data/c/tags/worldgen/biome/`), +/// by path, read from the loader jar `fetch` keeps in `/loader/`. +pub fn loader_biome_tags(work: &Path) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(dir) = std::fs::read_dir(work.join("loader")) else { + return out; + }; + for jar in dir.flatten().map(|e| e.path()) { + let Some(mut zip) = std::fs::File::open(&jar) + .ok() + .and_then(|f| zip::ZipArchive::new(f).ok()) + else { + continue; + }; + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some(path) = entry + .name() + .strip_prefix("data/c/tags/worldgen/biome/") + .and_then(|p| p.strip_suffix(".json")) + .map(str::to_owned) + else { + continue; + }; + let mut text = String::new(); + if entry.read_to_string(&mut text).is_ok() { + if let Ok(v) = serde_json::from_str(&text) { + out.insert(path, v); + } + } + } + } + out +} + +/// `tags` and the convention tags they include, in `conventions`. +pub fn with_included( + tags: &BTreeSet, + conventions: &BTreeMap, +) -> BTreeSet { + let mut all = BTreeSet::new(); + let mut todo: Vec = tags.iter().cloned().collect(); + while let Some(tag) = todo.pop() { + if !conventions.contains_key(&tag) || !all.insert(tag.clone()) { + continue; + } + let mut more = BTreeSet::new(); + convention_tags(&conventions[&tag], &mut more); + todo.extend(more); + } + all +} + +/// Where `fetch` keeps the pack's loader jar, and where it comes from: +/// NeoForge's own Maven repository. Only NeoForge packs need it today. +pub fn loader_jar(work: &Path, loader: &str, version: &str) -> Option<(PathBuf, String)> { + (loader == "neoforge" && !version.is_empty()).then(|| { + ( + work.join("loader").join(format!("neoforge-{version}-universal.jar")), + format!( + "https://maven.neoforged.net/releases/net/neoforged/neoforge/{version}/neoforge-{version}-universal.jar" + ), + ) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + const NO_TAGS: BTreeMap> = BTreeMap::new(); + + #[test] + fn maps_library_types_to_vanillas() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "lithostitched:jigsaw", "start_pool": "a:b"}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + let mut nether = + json!({"type": "moogs_structures:moogs_structures_generic_nether_jigsaw_structure"}); + assert!(!upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + let mut set = json!({"placement": {"type": "moogs_structures:advanced_random_spread", + "spacing": 10, "separation": 5, "min_distance_from_world_origin": 250}}); + assert!(upgrade("structure_set", &mut set, &mut report, &NO_TAGS)); + assert_eq!(set["placement"]["type"], "minecraft:random_spread"); + // Moog's spreads 1.65 times as far as its file says. + assert_eq!(set["placement"]["spacing"], 17); + assert_eq!(set["placement"]["separation"], 8); + assert_eq!( + set["placement"]["horizon:min_distance_from_world_origin"], + 250 + ); + assert!( + set["placement"] + .get("min_distance_from_world_origin") + .is_none() + ); + let mut pool = json!({"elements": [ + {"weight": 1, "element": {"element_type": "moogs_structures:versioned_single_pool_element", "location": "m:x"}}, + {"weight": 1, "element": {"element_type": "minecraft:list_pool_element", "elements": [ + {"element_type": "empty_pool_element"}]}}, + {"weight": 1, "element": {"element_type": "yungsapi:yung_single_element"}} + ]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + assert_eq!( + pool["elements"][0]["element"]["element_type"], + "minecraft:single_pool_element" + ); + assert_eq!( + pool["elements"][1]["element"]["elements"][0]["element_type"], + "minecraft:empty_pool_element" + ); + assert_eq!(report.mapped, 3); + assert_eq!(report.block_states, 0); + assert_eq!( + report.unsupported, + BTreeMap::from([ + ( + "moogs_structures:moogs_structures_generic_nether_jigsaw_structure".into(), + 1 + ), + ("yungsapi:yung_single_element".into(), 1), + ]) + ); + } + + #[test] + fn keeps_the_jigsaws_start_rules() { + let mut report = Upgrade::default(); + let mut moogs = json!({"type": "moogs_structures:moogs_structures_generic_jigsaw_structure", + "cannot_spawn_in_liquid": true, "terrain_height_radius_check": 2, + "allowed_terrain_height_range": 12, "valid_biome_radius_check": 1, + "y_allowance": {"min_y_allowed": 60}, "burying_type": "lowest_corner", + "use_bounding_box_hack": false, "size": 7}); + assert!(upgrade("structure", &mut moogs, &mut report, &NO_TAGS)); + assert_eq!( + moogs["horizon:start_checks"], + json!({"liquid": "top", "terrain_radius": 2, "terrain_range": 12, + "biome_radius": 1, "min_y": 60}) + ); + for gone in [ + "cannot_spawn_in_liquid", + "y_allowance", + "burying_type", + "use_bounding_box_hack", + ] { + assert!(moogs.get(gone).is_none(), "{gone}"); + } + assert_eq!(moogs["size"], 7); + // Repurposed Structures reads the block above the bottom. + let mut rs = json!({"type": "repurposed_structures:generic_jigsaw_structure", + "cannot_spawn_in_liquid": true}); + assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); + assert_eq!(rs["horizon:start_checks"], json!({"liquid": "lowest"})); + // Nothing to check: no key. + let mut plain = json!({"type": "lithostitched:jigsaw", "cannot_spawn_in_liquid": false}); + assert!(upgrade("structure", &mut plain, &mut report, &NO_TAGS)); + assert!(plain.get("horizon:start_checks").is_none()); + assert_eq!( + report.rules_lost, + BTreeMap::from([("burying_type".into(), 1), ("y_allowance".into(), 1)]) + ); + } + + #[test] + fn super_exclusion_zones_name_their_sets() { + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, text) in [ + ( + "data/rs/tags/worldgen/structure_set/avoid.json", + r##"{"values": ["minecraft:villages", "#rs:more", {"id": "x:y", "required": false}]}"##, + ), + ( + "data/rs/tags/worldgen/structure_set/more.json", + r##"{"values": ["minecraft:villages", "rs:cities", "#rs:avoid"]}"##, + ), + ] { + zip.start_file(name, opts).unwrap(); + std::io::Write::write_all(&mut zip, text.as_bytes()).unwrap(); + } + let mut zip = zip::ZipArchive::new(zip.finish().unwrap()).unwrap(); + let tags = structure_set_tags(&mut zip); + assert_eq!(tags["rs:avoid"], ["minecraft:villages", "x:y", "rs:cities"]); + let mut report = Upgrade::default(); + let mut set = json!({"placement": {"type": "repurposed_structures:advanced_random_spread", + "spacing": 30, "separation": 10, + "super_exclusion_zone": {"chunk_count": 4, "other_set": "#rs:avoid"}}}); + assert!(upgrade("structure_set", &mut set, &mut report, &tags)); + assert_eq!(set["placement"]["spacing"], 30); + assert_eq!( + set["placement"]["horizon:exclusion_zone"], + json!({"other_sets": ["minecraft:villages", "x:y", "rs:cities"], "chunk_count": 4}) + ); + let mut unknown = json!({"placement": {"type": "repurposed_structures:advanced_random_spread", + "spacing": 30, "separation": 10, + "super_exclusion_zone": {"chunk_count": 4, "other_set": "#rs:none"}}}); + assert!(upgrade("structure_set", &mut unknown, &mut report, &tags)); + assert_eq!(report.rules_lost["super_exclusion_zone"], 1); + } + + #[test] + fn drops_processors_written_in_java() { + let mut report = Upgrade::default(); + let mut list = json!({"processors": [ + {"processor_type": "repurposed_structures:bottom_pillar_processor"}, + {"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": -1}, + {"processor_type": "moogs_structures:spawner_randomizing_processor"}]}); + assert!(upgrade("processor_list", &mut list, &mut report, &NO_TAGS)); + assert_eq!( + list["processors"], + json!([{"processor_type": "minecraft:gravity", + "heightmap": "WORLD_SURFACE_WG", "offset": -1}]) + ); + let mut pool = json!({"elements": [ + {"weight": 1, "element": {"element_type": "minecraft:single_pool_element", + "processors": {"processors": [{"processor_type": "lithostitched:block_swap"}]}}}, + {"weight": 1, "element": {"element_type": "minecraft:list_pool_element", "elements": [ + {"element_type": "minecraft:single_pool_element", "processors": "x:named"}]}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + assert_eq!( + pool["elements"][0]["element"]["processors"], + json!({"processors": []}) + ); + assert_eq!( + pool["elements"][1]["element"]["elements"][0]["processors"], + "x:named" + ); + let mut vanilla = json!({"processors": [{"processor_type": "minecraft:nop"}]}); + assert!(!upgrade( + "processor_list", + &mut vanilla, + &mut report, + &NO_TAGS + )); + assert_eq!( + report.processors_dropped, + BTreeMap::from([ + ("lithostitched:block_swap".into(), 1), + ("moogs_structures:spawner_randomizing_processor".into(), 1), + ("repurposed_structures:bottom_pillar_processor".into(), 1), + ]) + ); + } + + #[test] + fn writes_block_states_in_26_3_shape() { + let mut report = Upgrade::default(); + let mut list = json!({"processors": [{"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": "minecraft:oak_stairs", "Properties": {"facing": "east"}}}]}]}); + assert!(upgrade("processor_list", &mut list, &mut report, &NO_TAGS)); + assert_eq!( + list["processors"][0]["rules"][0]["output_state"], + json!({"id": "minecraft:oak_stairs", "properties": {"facing": "east"}}) + ); + let mut spring = json!({"type": "minecraft:spring_feature", "config": { + "state": {"Name": "minecraft:water"}, "valid_blocks": ["minecraft:stone"]}}); + assert!(upgrade( + "configured_feature", + &mut spring, + &mut report, + &NO_TAGS + )); + assert_eq!(spring["config"]["state"], json!({"id": "minecraft:water"})); + // An object with other keys is not a state; a 26.3 state is left as it is. + let mut other = json!({"Name": "x", "weight": 1, "state": {"id": "minecraft:stone"}}); + assert!(!upgrade( + "configured_feature", + &mut other, + &mut report, + &NO_TAGS + )); + assert_eq!(report.block_states, 2); + assert_eq!(report.mapped, 0); + } + + #[test] + fn convention_tags_include_theirs() { + let conventions = BTreeMap::from([ + ( + "is_hot".to_owned(), + json!({"values": ["#c:is_desert", "#minecraft:is_badlands"]}), + ), + ( + "is_desert".to_owned(), + json!({"values": ["minecraft:desert"]}), + ), + ("is_cold".to_owned(), json!({"values": []})), + ]); + let mut used = BTreeSet::new(); + convention_tags( + &json!({"biomes": ["#c:is_hot", "#c:unknown", "#minecraft:x"]}), + &mut used, + ); + assert_eq!(used, BTreeSet::from(["is_hot".into(), "unknown".into()])); + assert_eq!( + with_included(&used, &conventions), + BTreeSet::from(["is_hot".into(), "is_desert".into()]) + ); + } +} diff --git a/crates/horizon-protocol/Cargo.toml b/crates/horizon-protocol/Cargo.toml index fad282080..66a0af162 100644 --- a/crates/horizon-protocol/Cargo.toml +++ b/crates/horizon-protocol/Cargo.toml @@ -8,11 +8,13 @@ description = "Horizon's Minecraft Java Edition 26.3 network protocol (version 7 [dependencies] horizon-world = { path = "../horizon-world" } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } serde_json = "1.0.151" # The shared secret and RSA padding (OS randomness) and the server hash. getrandom = "0.3" sha1 = "0.10" +# Secure chat: SHA256withRSA message signatures. +sha2 = "0.10" [lints] workspace = true diff --git a/crates/horizon-protocol/src/buf.rs b/crates/horizon-protocol/src/buf.rs index d937ff8b9..349ec74cf 100644 --- a/crates/horizon-protocol/src/buf.rs +++ b/crates/horizon-protocol/src/buf.rs @@ -23,6 +23,10 @@ impl<'a> Reader<'a> { pub fn position(&self) -> usize { self.pos } + /// The bytes read since `start` (a `position()`). + pub fn since(&self, start: usize) -> &'a [u8] { + &self.data[start.min(self.pos)..self.pos] + } pub fn rest(&mut self) -> &'a [u8] { let rest = &self.data[self.pos..]; self.pos = self.data.len(); @@ -307,6 +311,16 @@ impl Codec> for Bytes { w.byte_array(v) } } +/// ByteBufCodecs.byteArray(N): VarInt-prefixed bytes, at most N. +pub struct BytesN; +impl Codec> for BytesN { + fn read(r: &mut Reader) -> Result> { + r.byte_array(N) + } + fn write(v: &Vec, w: &mut Writer) { + w.byte_array(v) + } +} /// Everything left in the packet (custom payloads). pub struct Rest; impl Codec> for Rest { diff --git a/crates/horizon-protocol/src/connection.rs b/crates/horizon-protocol/src/connection.rs index 4deda020c..8f7ae28cc 100644 --- a/crates/horizon-protocol/src/connection.rs +++ b/crates/horizon-protocol/src/connection.rs @@ -289,7 +289,12 @@ impl ConnReader { impl ConnWriter { /// Send one packet body (VarInt id + payload). pub fn send(&mut self, body: &[u8]) -> Result<()> { - let mut framed = frame::encode(body, self.threshold)?; + self.send_contents(&frame::contents(body, self.threshold)?) + } + /// Send a frame whose contents [`frame::contents`] made with this + /// writer's threshold. + pub fn send_contents(&mut self, contents: &[u8]) -> Result<()> { + let mut framed = frame::prefixed(contents); if let Some(c) = &mut self.encrypt { c.encrypt(&mut framed); } diff --git a/crates/horizon-protocol/src/frame.rs b/crates/horizon-protocol/src/frame.rs index 9a1402e0b..a403148f5 100644 --- a/crates/horizon-protocol/src/frame.rs +++ b/crates/horizon-protocol/src/frame.rs @@ -16,6 +16,12 @@ pub const MAX_UNCOMPRESSED: usize = 8_388_608; /// length prefix, and with compression enabled the uncompressed-length /// field (0 when below the threshold). pub fn encode(body: &[u8], threshold: Option) -> Result> { + Ok(prefixed(&contents(body, threshold)?)) +} + +/// What [`encode`] puts after the length prefix: the same for every +/// connection with the same threshold. +pub fn contents(body: &[u8], threshold: Option) -> Result> { let inner = match threshold { None => body.to_vec(), Some(t) if body.len() < t => { @@ -38,10 +44,15 @@ pub fn encode(body: &[u8], threshold: Option) -> Result> { inner.len() ))); } - let mut out = Vec::with_capacity(inner.len() + 3); - write_varint(&mut out, inner.len() as i32); - out.extend_from_slice(&inner); - Ok(out) + Ok(inner) +} + +/// A frame: the length prefix, then the [`contents`]. +pub fn prefixed(contents: &[u8]) -> Vec { + let mut out = Vec::with_capacity(contents.len() + 3); + write_varint(&mut out, contents.len() as i32); + out.extend_from_slice(contents); + out } /// Split one complete frame off the front of `buffer`, if available. diff --git a/crates/horizon-protocol/src/lib.rs b/crates/horizon-protocol/src/lib.rs index e49031b77..1d0f081f7 100644 --- a/crates/horizon-protocol/src/lib.rs +++ b/crates/horizon-protocol/src/lib.rs @@ -13,6 +13,7 @@ pub mod item; pub mod packets; pub mod registry; pub mod rsa; +pub mod secure_chat; pub mod servers; pub mod text; diff --git a/crates/horizon-protocol/src/packets/mod.rs b/crates/horizon-protocol/src/packets/mod.rs index 57c4f7f36..4ef8ac21a 100644 --- a/crates/horizon-protocol/src/packets/mod.rs +++ b/crates/horizon-protocol/src/packets/mod.rs @@ -7,6 +7,7 @@ pub mod configuration; pub mod handshake; pub mod login; pub mod play; +pub mod recipes; pub mod status; use crate::buf::{Codec, Reader, Writer}; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 2d9f7e629..895db9755 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -2,9 +2,9 @@ use crate::{ Error, Result, buf::{ - Bool, Byte, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, Opt, - OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, Vec3d, - Writer, + Bool, Byte, BytesN, ChunkPos, Codec, Double, Float, Ident, Int, List, Long, LpVec3, Nbt, + Opt, OptVarInt, Pos, Reader, SectionPos, Short, Str, StrN, UByte, Uuid, VarInt, VarLong, + Vec3d, Writer, }, chunk::{ChunkData, LightData}, entity_data::{EntityData, Value}, @@ -567,6 +567,10 @@ packet!(PlayerPosition { pitch: f32 => Float, relatives: i32 => Int, }); +packet!( + /// ClientboundProjectilePowerPacket: an AbstractHurtingProjectile's accelerationPower. + ProjectilePower { id: i32 => VarInt, power: f64 => Double } +); packet!(PlayerRotation { yaw: f32 => Float, relative_yaw: bool => Bool, pitch: f32 => Float, relative_pitch: bool => Bool }); packet!(RemoveEntities { ids: Vec => List }); packet!(Respawn { spawn: SpawnInfo => SpawnInfo, keep: i8 => Byte }); @@ -590,6 +594,10 @@ packet!(SetCursorItem { item: Option => Slot }); packet!(SetDefaultSpawnPosition { pos: GlobalPos => GlobalPos, yaw: f32 => Float, pitch: f32 => Float }); packet!(SetEntityData { id: i32 => VarInt, values: Vec<(u8, i32, Value)> => EntityData }); packet!(SetEntityMotion { id: i32 => VarInt, velocity: [f64; 3] => LpVec3 }); +packet!( + /// ClientboundSetPassengersPacket: a vehicle and every entity riding it. + SetPassengers { vehicle: i32 => VarInt, passengers: Vec => List } +); /// ClientboundSetEquipmentPacket: (EquipmentSlot ordinal, stack) pairs. pub struct Equipment; impl Codec)>> for Equipment { @@ -901,6 +909,177 @@ pub struct CommandNode { /// Custom suggestion provider (`minecraft:ask_server`). pub suggestions: Option, } +/// The `minecraft:command_argument_type` registry of 26.3 in id order +/// (ArgumentTypeInfos.bootstrap). +pub const ARGUMENT_TYPES: &[&str] = &[ + "brigadier:bool", + "brigadier:float", + "brigadier:double", + "brigadier:integer", + "brigadier:long", + "brigadier:string", + "minecraft:entity", + "minecraft:game_profile", + "minecraft:block_pos", + "minecraft:column_pos", + "minecraft:vec3", + "minecraft:vec2", + "minecraft:block_state", + "minecraft:block_predicate", + "minecraft:item_stack", + "minecraft:item_predicate", + "minecraft:team_color", + "minecraft:hex_color", + "minecraft:component", + "minecraft:style", + "minecraft:message", + "minecraft:nbt_compound_tag", + "minecraft:nbt_tag", + "minecraft:nbt_path", + "minecraft:objective", + "minecraft:objective_criteria", + "minecraft:operation", + "minecraft:particle", + "minecraft:angle", + "minecraft:rotation", + "minecraft:scoreboard_slot", + "minecraft:score_holder", + "minecraft:swizzle", + "minecraft:team", + "minecraft:item_slot", + "minecraft:item_slots", + "minecraft:resource_location", + "minecraft:function", + "minecraft:entity_anchor", + "minecraft:int_range", + "minecraft:float_range", + "minecraft:dimension", + "minecraft:gamemode", + "minecraft:time", + "minecraft:resource_or_tag", + "minecraft:resource_or_tag_key", + "minecraft:resource", + "minecraft:resource_key", + "minecraft:resource_selector", + "minecraft:template_mirror", + "minecraft:template_rotation", + "minecraft:heightmap", + "minecraft:loot_table", + "minecraft:loot_predicate", + "minecraft:loot_modifier", + "minecraft:context_float_provider", + "minecraft:context_int_provider", + "minecraft:slot_source", + "minecraft:dialog", + "minecraft:feature", + "minecraft:swing_animation", + "minecraft:uuid", +]; + +/// The properties of an argument parser (`ArgumentTypeInfo.Template`) as +/// one of the 26.3 parsers decoded from the network. +#[derive(Clone, Debug, PartialEq)] +pub enum ArgumentProperties { + None, + Integer { + min: Option, + max: Option, + }, + Long { + min: Option, + max: Option, + }, + Float { + min: Option, + max: Option, + }, + Double { + min: Option, + max: Option, + }, + /// StringArgumentType.StringType: 0 word, 1 phrase, 2 greedy. + String(i32), + Entity { + single: bool, + players_only: bool, + }, + ScoreHolder { + multiple: bool, + }, + Time { + min: i32, + }, + /// The resource arguments' registry. + Registry(String), +} + +impl ArgumentProperties { + /// ArgumentTypeInfo.deserializeFromNetwork for parser `id`. + pub fn read(r: &mut Reader, id: i32) -> Result { + let name = usize::try_from(id) + .ok() + .and_then(|i| ARGUMENT_TYPES.get(i)) + .ok_or_else(|| crate::Error::new(format!("unknown argument type {id}")))?; + let flagged = |r: &mut Reader| -> Result<(bool, bool)> { + let f = r.u8()?; + Ok((f & 1 != 0, f & 2 != 0)) + }; + Ok(match *name { + "brigadier:integer" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.i32()?) } else { None }; + let max = if max { Some(r.i32()?) } else { None }; + Self::Integer { min, max } + } + "brigadier:long" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.i64()?) } else { None }; + let max = if max { Some(r.i64()?) } else { None }; + Self::Long { min, max } + } + "brigadier:float" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.f32()?) } else { None }; + let max = if max { Some(r.f32()?) } else { None }; + Self::Float { min, max } + } + "brigadier:double" => { + let (min, max) = flagged(r)?; + let min = if min { Some(r.f64()?) } else { None }; + let max = if max { Some(r.f64()?) } else { None }; + Self::Double { min, max } + } + "brigadier:string" => Self::String(r.varint()?), + "minecraft:entity" => { + let f = r.u8()?; + Self::Entity { + single: f & 1 != 0, + players_only: f & 2 != 0, + } + } + "minecraft:score_holder" => Self::ScoreHolder { + multiple: r.u8()? & 1 != 0, + }, + "minecraft:time" => Self::Time { min: r.i32()? }, + "minecraft:resource" + | "minecraft:resource_key" + | "minecraft:resource_or_tag" + | "minecraft:resource_or_tag_key" + | "minecraft:resource_selector" => Self::Registry(r.string(32767)?), + _ => Self::None, + }) + } + /// Decodes a node's raw `parser` bytes. + pub fn decode(id: i32, bytes: &[u8]) -> Result { + Self::read(&mut Reader::new(bytes), id) + } +} + +/// Reads past an argument node's parser properties. +fn read_argument_properties(r: &mut Reader, id: i32) -> Result<()> { + ArgumentProperties::read(r, id).map(|_| ()) +} + /// The command tree: nodes and the index of the root. #[derive(Clone, Debug, PartialEq)] pub struct Commands { @@ -926,11 +1105,14 @@ impl Codec for Commands { name = r.string(32767)?; } if kind == 2 { - // Properties are parser specific; only the property-less parsers - // can be skipped without a table, so keep the rest of the packet. - return Err(crate::Error::new("argument nodes are not decoded")); + let id = r.varint()?; + let start = r.position(); + read_argument_properties(r, id)?; + parser = Some((id, r.since(start).to_vec())); + if flags & 16 != 0 { + suggestions = Some(r.string(32767)?); + } } - let _ = (&mut parser, &mut suggestions); nodes.push(CommandNode { kind, executable: flags & 4 != 0, @@ -1189,6 +1371,10 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { ChunkBatchStart(Empty) = CHUNK_BATCH_START, ClearTitles(Bool1) = CLEAR_TITLES, Commands(Commands) = COMMANDS, + RecipeBookAdd(super::recipes::RecipeBookAdd) = RECIPE_BOOK_ADD, + RecipeBookRemove(super::recipes::RecipeBookRemove) = RECIPE_BOOK_REMOVE, + RecipeBookSettings(super::recipes::RecipeBookSettings) = RECIPE_BOOK_SETTINGS, + PlaceGhostRecipe(super::recipes::PlaceGhostRecipe) = PLACE_GHOST_RECIPE, ContainerClose(ContainerClose) = CONTAINER_CLOSE, ContainerSetContent(ContainerSetContent) = CONTAINER_SET_CONTENT, ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA, @@ -1248,6 +1434,8 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { SetHealth(SetHealth) = SET_HEALTH, SetHeldSlot(SetHeldSlot) = SET_HELD_SLOT, SetObjective(SetObjective) = SET_OBJECTIVE, + SetPassengers(SetPassengers) = SET_PASSENGERS, + ProjectilePower(ProjectilePower) = PROJECTILE_POWER, SetPlayerInventory(SetPlayerInventory) = SET_PLAYER_INVENTORY, SetPlayerTeam(SetPlayerTeam) = SET_PLAYER_TEAM, SetScore(SetScore) = SET_SCORE, @@ -1269,12 +1457,126 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, + TrackedWaypoint(TrackedWaypoint) = WAYPOINT, }); packet!( /// ClientboundClearTitlesPacket: whether to also reset the timings. Bool1 { value: bool => Bool } ); +/// ClientboundTrackedWaypointPacket.Operation, by ordinal. +pub mod waypoint_operation { + pub const TRACK: i32 = 0; + pub const UNTRACK: i32 = 1; + pub const UPDATE: i32 = 2; +} + +/// TrackedWaypoint's identifier: `Either`. +#[derive(Clone, Debug, PartialEq)] +pub enum WaypointId { + Uuid(u128), + Name(String), +} + +/// What a TrackedWaypoint points at (its `Type` and contents). +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum WaypointTarget { + /// `TrackedWaypoint.empty`: an untracked waypoint. + Empty, + /// A block position (`Vec3iWaypoint`). + Block([i32; 3]), + /// A chunk (`ChunkWaypoint`). + Chunk([i32; 2]), + /// An angle in radians (`AzimuthWaypoint`). + Azimuth(f32), +} + +/// ClientboundTrackedWaypointPacket: the locator bar's waypoints. +#[derive(Clone, Debug, PartialEq)] +pub struct TrackedWaypoint { + /// `waypoint_operation`. + pub operation: i32, + pub id: WaypointId, + /// Waypoint.Icon: the style (a `waypoint_style_asset` key) and an RGB colour. + pub style: String, + pub color: Option, + pub target: WaypointTarget, +} + +impl Codec for TrackedWaypoint { + fn read(r: &mut Reader) -> Result { + let operation = r.varint()?; + if !(0..=2).contains(&operation) { + return Err(Error::new(format!("waypoint operation {operation}"))); + } + let id = if r.bool()? { + WaypointId::Uuid(r.uuid()?) + } else { + WaypointId::Name(r.string(32767)?) + }; + let style = Ident::read(r)?; + // ByteBufCodecs.RGB_COLOR: three bytes, read back as an opaque ARGB colour. + let color = if r.bool()? { + let [red, green, blue] = [r.u8()?, r.u8()?, r.u8()?].map(i32::from); + Some(-16_777_216 | red << 16 | green << 8 | blue) + } else { + None + }; + let target = match r.varint()? { + 0 => WaypointTarget::Empty, + 1 => WaypointTarget::Block([r.varint()?, r.varint()?, r.varint()?]), + 2 => WaypointTarget::Chunk([r.varint()?, r.varint()?]), + 3 => WaypointTarget::Azimuth(r.f32()?), + other => return Err(Error::new(format!("waypoint type {other}"))), + }; + Ok(TrackedWaypoint { + operation, + id, + style, + color, + target, + }) + } + fn write(v: &TrackedWaypoint, w: &mut Writer) { + w.varint(v.operation); + match &v.id { + WaypointId::Uuid(uuid) => { + w.bool(true); + w.uuid(*uuid); + } + WaypointId::Name(name) => { + w.bool(false); + w.string(name); + } + } + w.string(&v.style); + w.bool(v.color.is_some()); + if let Some(color) = v.color { + for shift in [16, 8, 0] { + w.u8((color >> shift) as u8); + } + } + match v.target { + WaypointTarget::Empty => w.varint(0), + WaypointTarget::Block([x, y, z]) => { + w.varint(1); + w.varint(x); + w.varint(y); + w.varint(z); + } + WaypointTarget::Chunk([x, z]) => { + w.varint(2); + w.varint(x); + w.varint(z); + } + WaypointTarget::Azimuth(angle) => { + w.varint(3); + w.f32(angle); + } + } + } +} + // ---- serverbound ------------------------------------------------------- packet!(AcceptTeleportation { id: i32 => VarInt, x: f64 => Double, y: f64 => Double, z: f64 => Double, yaw: f32 => Float, pitch: f32 => Float }); @@ -1302,6 +1604,42 @@ packet!(Chat { last_seen: LastSeenUpdate => LastSeenUpdate, }); packet!(ChatCommand { command: String => Str }); +packet!(ChatAck { offset: i32 => VarInt }); +/// ArgumentSignatures: each signed argument's name (at most 16 chars) and +/// signature, at most 8. +pub struct ArgumentSignatures; +impl Codec)>> for ArgumentSignatures { + fn read(r: &mut Reader) -> Result)>> { + let n = r.count(8)?; + (0..n) + .map(|_| Ok((r.string(16)?, r.bytes(256)?.to_vec()))) + .collect() + } + fn write(v: &Vec<(String, Vec)>, w: &mut Writer) { + w.varint(v.len() as i32); + for (name, signature) in v { + w.string(name); + w.bytes(signature); + } + } +} +packet!(ChatCommandSigned { + command: String => Str, + timestamp: i64 => Long, + salt: i64 => Long, + arguments: Vec<(String, Vec)> => ArgumentSignatures, + last_seen: LastSeenUpdate => LastSeenUpdate, +}); +packet!( + /// RemoteChatSession.Data: the session id, then ProfilePublicKey.Data + /// (expiry in epoch milliseconds, X.509 key, the services' signature). + ChatSessionUpdate { + session: u128 => Uuid, + expires_at: i64 => Long, + key: Vec => BytesN<512>, + key_signature: Vec => BytesN<4096>, + } +); packet!(ChangeDifficultyRequest { difficulty: i32 => VarInt }); packet!(LockDifficulty { locked: bool => Bool }); packet!(SetGameRule { entries: Vec => List }); @@ -1395,7 +1733,11 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { Attack(Attack) = ATTACK, ChangeGameMode(ChangeGameMode) = CHANGE_GAME_MODE, Chat(Chat) = CHAT, + ChatAck(ChatAck) = CHAT_ACK, ChatCommand(ChatCommand) = CHAT_COMMAND, + ChatCommandSigned(ChatCommandSigned) = CHAT_COMMAND_SIGNED, + ChatSessionUpdate(ChatSessionUpdate) = CHAT_SESSION_UPDATE, + PlaceRecipe(super::recipes::PlaceRecipe) = PLACE_RECIPE, ChunkBatchReceived(ChunkBatchReceived) = CHUNK_BATCH_RECEIVED, ClientCommand(ClientCommand) = CLIENT_COMMAND, ClientInformation(ClientInformation) = CLIENT_INFORMATION, @@ -1489,6 +1831,42 @@ mod tests { } } + #[test] + fn tracked_waypoint_bytes() { + // TRACK, a UUID, the default style, red (#FF5555), a block position. + let track = Clientbound::TrackedWaypoint(TrackedWaypoint { + operation: waypoint_operation::TRACK, + id: WaypointId::Uuid(0x0102_0304_0506_0708_090a_0b0c_0d0e_0f10), + style: "minecraft:default".into(), + color: Some(0xFFFF_5555_u32 as i32), + target: WaypointTarget::Block([1, -2, 300]), + }); + let mut expected = vec![141, 1, 0, 1]; + expected.extend(1..=16u8); + expected.push(17); + expected.extend(b"minecraft:default"); + expected.extend([ + 1, 0xFF, 0x55, 0x55, 1, 1, 0xFE, 0xFF, 0xFF, 0xFF, 0x0F, 0xAC, 0x02, + ]); + assert_eq!(track.encode(), expected); + assert_eq!(Clientbound::decode(141, &expected[2..]).unwrap(), track); + for target in [ + WaypointTarget::Empty, + WaypointTarget::Chunk([-3, 4]), + WaypointTarget::Azimuth(-1.25), + ] { + let packet = Clientbound::TrackedWaypoint(TrackedWaypoint { + operation: waypoint_operation::UPDATE, + id: WaypointId::Name("spawn".into()), + style: "minecraft:bowtie".into(), + color: None, + target, + }); + let bytes = packet.encode(); + assert_eq!(Clientbound::decode(141, &bytes[2..]).unwrap(), packet); + } + } + #[test] fn clientbound_round_trips() { let packets = vec![ @@ -1723,6 +2101,11 @@ mod tests { id: 2, velocity: [0.0; 3], }), + Clientbound::SetPassengers(SetPassengers { + vehicle: 2, + passengers: vec![3, 300], + }), + Clientbound::ProjectilePower(ProjectilePower { id: 4, power: 0.1 }), Clientbound::SetEquipment(SetEquipment { id: 2, slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], @@ -1840,6 +2223,24 @@ mod tests { Serverbound::ChatCommand(ChatCommand { command: "time set day".into(), }), + Serverbound::ChatAck(ChatAck { offset: 3 }), + Serverbound::ChatCommandSigned(ChatCommandSigned { + command: "say hi".into(), + timestamp: 1_700_000_000_000, + salt: -5, + arguments: vec![("message".into(), vec![9; 256])], + last_seen: LastSeenUpdate { + offset: 1, + acknowledged: [1, 0, 8], + checksum: -3, + }, + }), + Serverbound::ChatSessionUpdate(ChatSessionUpdate { + session: 0x1234, + expires_at: 1_800_000_000_000, + key: vec![0x30; 294], + key_signature: vec![7; 512], + }), Serverbound::ChunkBatchReceived(ChunkBatchReceived { chunks_per_tick: 9.5, }), diff --git a/crates/horizon-protocol/src/packets/recipes.rs b/crates/horizon-protocol/src/packets/recipes.rs new file mode 100644 index 000000000..c289b8943 --- /dev/null +++ b/crates/horizon-protocol/src/packets/recipes.rs @@ -0,0 +1,607 @@ +//! The recipe book's packets and the recipe displays they carry +//! (`RecipeDisplay`, `SlotDisplay`, `RecipeDisplayEntry`): the 26.3 +//! `minecraft:recipe_display` and `minecraft:slot_display` types in id order. +use crate::{ + Result, + buf::{Codec, Reader, Writer}, + item::{Stack, Template}, +}; +use horizon_world::nbt::Tag; + +/// `HolderSet` on the network: a tag by name, or item ids. +#[derive(Clone, Debug, PartialEq)] +pub enum HolderSet { + Tag(String), + Items(Vec), +} +impl HolderSet { + pub fn read(r: &mut Reader) -> Result { + let n = r.varint()? - 1; + if n == -1 { + return Ok(Self::Tag(r.string(32767)?)); + } + let n = usize::try_from(n).map_err(|_| crate::Error::new("negative holder set size"))?; + if n > r.remaining() { + return Err(crate::Error::new("holder set larger than the packet")); + } + Ok(Self::Items( + (0..n).map(|_| r.varint()).collect::>()?, + )) + } + pub fn write(&self, w: &mut Writer) { + match self { + Self::Tag(name) => { + w.varint(0); + w.string(name); + } + Self::Items(ids) => { + w.varint(ids.len() as i32 + 1); + ids.iter().for_each(|id| w.varint(*id)); + } + } + } +} + +/// A trim pattern as `ByteBufCodecs.holder` sends it: a registry id, or +/// the pattern itself. +#[derive(Clone, Debug, PartialEq)] +pub enum TrimPattern { + Id(i32), + Direct { + asset: String, + description: Tag, + decal: bool, + }, +} + +/// `SlotDisplay`: what a recipe book slot shows. +#[derive(Clone, Debug, PartialEq)] +pub enum SlotDisplay { + Empty, + AnyFuel, + WithAnyPotion(Box), + /// The source, kept to the stacks with this data component type. + OnlyWithComponent(Box, i32), + Item(i32), + ItemStack(Stack), + Tag(HolderSet), + Dyed { + dye: Box, + target: Box, + }, + SmithingTrim { + base: Box, + material: Box, + pattern: TrimPattern, + }, + WithRemainder { + input: Box, + remainder: Box, + }, + Composite(Vec), +} + +/// How deep slot displays may nest (composites of composites…). +const MAX_DEPTH: u32 = 32; + +impl SlotDisplay { + pub fn read(r: &mut Reader) -> Result { + Self::read_at(r, 0) + } + fn read_at(r: &mut Reader, depth: u32) -> Result { + if depth > MAX_DEPTH { + return Err(crate::Error::new("slot displays nest too deep")); + } + let inner = |r: &mut Reader| Self::read_at(r, depth + 1).map(Box::new); + Ok(match r.varint()? { + 0 => Self::Empty, + 1 => Self::AnyFuel, + 2 => Self::WithAnyPotion(inner(r)?), + 3 => { + let source = inner(r)?; + Self::OnlyWithComponent(source, r.varint()?) + } + 4 => Self::Item(r.varint()?), + 5 => Self::ItemStack(Template::read(r)?), + 6 => Self::Tag(HolderSet::read(r)?), + 7 => Self::Dyed { + dye: inner(r)?, + target: inner(r)?, + }, + 8 => { + let base = inner(r)?; + let material = inner(r)?; + let pattern = match r.varint()? { + 0 => TrimPattern::Direct { + asset: r.string(32767)?, + description: r.nbt()?, + decal: r.bool()?, + }, + id => TrimPattern::Id(id - 1), + }; + Self::SmithingTrim { + base, + material, + pattern, + } + } + 9 => Self::WithRemainder { + input: inner(r)?, + remainder: inner(r)?, + }, + 10 => { + let n = r.count(r.remaining())?; + let mut out = Vec::with_capacity(n.min(256)); + for _ in 0..n { + out.push(Self::read_at(r, depth + 1)?); + } + Self::Composite(out) + } + id => return Err(crate::Error::new(format!("unknown slot display {id}"))), + }) + } + pub fn write(&self, w: &mut Writer) { + match self { + Self::Empty => w.varint(0), + Self::AnyFuel => w.varint(1), + Self::WithAnyPotion(d) => { + w.varint(2); + d.write(w); + } + Self::OnlyWithComponent(d, component) => { + w.varint(3); + d.write(w); + w.varint(*component); + } + Self::Item(id) => { + w.varint(4); + w.varint(*id); + } + Self::ItemStack(stack) => { + w.varint(5); + Template::write(stack, w); + } + Self::Tag(set) => { + w.varint(6); + set.write(w); + } + Self::Dyed { dye, target } => { + w.varint(7); + dye.write(w); + target.write(w); + } + Self::SmithingTrim { + base, + material, + pattern, + } => { + w.varint(8); + base.write(w); + material.write(w); + match pattern { + TrimPattern::Id(id) => w.varint(id + 1), + TrimPattern::Direct { + asset, + description, + decal, + } => { + w.varint(0); + w.string(asset); + w.nbt(description); + w.bool(*decal); + } + } + } + Self::WithRemainder { input, remainder } => { + w.varint(9); + input.write(w); + remainder.write(w); + } + Self::Composite(list) => { + w.varint(10); + w.varint(list.len() as i32); + list.iter().for_each(|d| d.write(w)); + } + } + } +} + +fn read_list(r: &mut Reader) -> Result> { + let n = r.count(r.remaining())?; + let mut out = Vec::with_capacity(n.min(256)); + for _ in 0..n { + out.push(SlotDisplay::read(r)?); + } + Ok(out) +} +fn write_list(list: &[SlotDisplay], w: &mut Writer) { + w.varint(list.len() as i32); + list.iter().for_each(|d| d.write(w)); +} + +/// `RecipeDisplay`: a recipe as the recipe book draws it. +#[derive(Clone, Debug, PartialEq)] +pub enum RecipeDisplay { + Shapeless { + ingredients: Vec, + result: SlotDisplay, + station: SlotDisplay, + }, + Shaped { + width: i32, + height: i32, + ingredients: Vec, + result: SlotDisplay, + station: SlotDisplay, + }, + Furnace { + ingredient: SlotDisplay, + fuel: SlotDisplay, + result: SlotDisplay, + station: SlotDisplay, + duration: i32, + experience: f32, + }, + Stonecutter { + input: SlotDisplay, + result: SlotDisplay, + station: SlotDisplay, + }, + Smithing { + template: SlotDisplay, + base: SlotDisplay, + addition: SlotDisplay, + result: SlotDisplay, + station: SlotDisplay, + }, +} +impl RecipeDisplay { + pub fn result(&self) -> &SlotDisplay { + match self { + Self::Shapeless { result, .. } + | Self::Shaped { result, .. } + | Self::Furnace { result, .. } + | Self::Stonecutter { result, .. } + | Self::Smithing { result, .. } => result, + } + } +} +impl Codec for RecipeDisplay { + fn read(r: &mut Reader) -> Result { + let slot = SlotDisplay::read; + Ok(match r.varint()? { + 0 => Self::Shapeless { + ingredients: read_list(r)?, + result: slot(r)?, + station: slot(r)?, + }, + 1 => { + let (width, height) = (r.varint()?, r.varint()?); + let ingredients = read_list(r)?; + if i64::from(width) * i64::from(height) != ingredients.len() as i64 { + return Err(crate::Error::new("shaped display size mismatch")); + } + Self::Shaped { + width, + height, + ingredients, + result: slot(r)?, + station: slot(r)?, + } + } + 2 => Self::Furnace { + ingredient: slot(r)?, + fuel: slot(r)?, + result: slot(r)?, + station: slot(r)?, + duration: r.varint()?, + experience: r.f32()?, + }, + 3 => Self::Stonecutter { + input: slot(r)?, + result: slot(r)?, + station: slot(r)?, + }, + 4 => Self::Smithing { + template: slot(r)?, + base: slot(r)?, + addition: slot(r)?, + result: slot(r)?, + station: slot(r)?, + }, + id => return Err(crate::Error::new(format!("unknown recipe display {id}"))), + }) + } + fn write(v: &Self, w: &mut Writer) { + match v { + Self::Shapeless { + ingredients, + result, + station, + } => { + w.varint(0); + write_list(ingredients, w); + result.write(w); + station.write(w); + } + Self::Shaped { + width, + height, + ingredients, + result, + station, + } => { + w.varint(1); + w.varint(*width); + w.varint(*height); + write_list(ingredients, w); + result.write(w); + station.write(w); + } + Self::Furnace { + ingredient, + fuel, + result, + station, + duration, + experience, + } => { + w.varint(2); + ingredient.write(w); + fuel.write(w); + result.write(w); + station.write(w); + w.varint(*duration); + w.f32(*experience); + } + Self::Stonecutter { + input, + result, + station, + } => { + w.varint(3); + input.write(w); + result.write(w); + station.write(w); + } + Self::Smithing { + template, + base, + addition, + result, + station, + } => { + w.varint(4); + template.write(w); + base.write(w); + addition.write(w); + result.write(w); + station.write(w); + } + } + } +} + +/// `RecipeDisplayEntry` with `ClientboundRecipeBookAddPacket.Entry`'s flags +/// (1 show a notification, 2 highlight as new). +#[derive(Clone, Debug, PartialEq)] +pub struct RecipeBookEntry { + pub id: i32, + pub display: RecipeDisplay, + /// The recipe group (0 none, else the group's index + 1). + pub group: i32, + /// `minecraft:recipe_book_category` id. + pub category: i32, + /// The ingredients the "craftable" filter checks, if the recipe has any. + pub requirements: Option>, + pub flags: i8, +} + +/// ClientboundRecipeBookAddPacket: the entries, and whether they replace the +/// client's book. +#[derive(Clone, Debug, PartialEq)] +pub struct RecipeBookAdd { + pub entries: Vec, + pub replace: bool, +} +impl RecipeBookEntry { + pub fn read(r: &mut Reader) -> Result { + let id = r.varint()?; + let display = RecipeDisplay::read(r)?; + let group = r.varint()?; + let category = r.varint()?; + let requirements = if r.bool()? { + let k = r.count(r.remaining())?; + let mut list = Vec::with_capacity(k.min(64)); + for _ in 0..k { + list.push(HolderSet::read(r)?); + } + Some(list) + } else { + None + }; + Ok(Self { + id, + display, + group, + category, + requirements, + flags: r.i8()?, + }) + } +} +impl Codec for RecipeBookAdd { + fn read(r: &mut Reader) -> Result { + let n = r.count(r.remaining())?; + let mut entries = Vec::with_capacity(n.min(4096)); + for _ in 0..n { + entries.push(RecipeBookEntry::read(r)?); + } + Ok(Self { + entries, + replace: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.entries.len() as i32); + for e in &v.entries { + w.varint(e.id); + RecipeDisplay::write(&e.display, w); + w.varint(e.group); + w.varint(e.category); + w.bool(e.requirements.is_some()); + if let Some(list) = &e.requirements { + w.varint(list.len() as i32); + list.iter().for_each(|s| s.write(w)); + } + w.i8(e.flags); + } + w.bool(v.replace); + } +} + +/// ClientboundRecipeBookRemovePacket: the display ids. +#[derive(Clone, Debug, PartialEq)] +pub struct RecipeBookRemove { + pub ids: Vec, +} +impl Codec for RecipeBookRemove { + fn read(r: &mut Reader) -> Result { + let n = r.count(r.remaining())?; + Ok(Self { + ids: (0..n).map(|_| r.varint()).collect::>()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.ids.len() as i32); + v.ids.iter().for_each(|id| w.varint(*id)); + } +} + +/// RecipeBookSettings: each book's (open, filtering), in `RecipeBookType` +/// order (crafting, furnace, blast furnace, smoker). +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RecipeBookSettings { + pub books: [(bool, bool); 4], +} +impl Codec for RecipeBookSettings { + fn read(r: &mut Reader) -> Result { + let mut books = [(false, false); 4]; + for b in &mut books { + *b = (r.bool()?, r.bool()?); + } + Ok(Self { books }) + } + fn write(v: &Self, w: &mut Writer) { + for (open, filtering) in v.books { + w.bool(open); + w.bool(filtering); + } + } +} + +/// ClientboundPlaceGhostRecipePacket: the recipe to show faded in a menu +/// whose items were missing. +#[derive(Clone, Debug, PartialEq)] +pub struct PlaceGhostRecipe { + pub container: i32, + pub display: RecipeDisplay, +} +impl Codec for PlaceGhostRecipe { + fn read(r: &mut Reader) -> Result { + Ok(Self { + container: r.varint()?, + display: RecipeDisplay::read(r)?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.container); + RecipeDisplay::write(&v.display, w); + } +} + +/// ServerboundPlaceRecipePacket: place the recipe with this display id in +/// the open menu, as many times as possible when `use_max` (shift). +#[derive(Clone, Debug, PartialEq)] +pub struct PlaceRecipe { + pub container: i32, + pub recipe: i32, + pub use_max: bool, +} +impl Codec for PlaceRecipe { + fn read(r: &mut Reader) -> Result { + Ok(Self { + container: r.varint()?, + recipe: r.varint()?, + use_max: r.bool()?, + }) + } + fn write(v: &Self, w: &mut Writer) { + w.varint(v.container); + w.varint(v.recipe); + w.bool(v.use_max); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn book_entries_round_trip() { + let add = RecipeBookAdd { + entries: vec![ + RecipeBookEntry { + id: 7, + display: RecipeDisplay::Shaped { + width: 2, + height: 1, + ingredients: vec![ + SlotDisplay::Tag(HolderSet::Tag("minecraft:planks".into())), + SlotDisplay::Empty, + ], + result: SlotDisplay::ItemStack(Stack::new(12, 4)), + station: SlotDisplay::Item(300), + }, + group: 3, + category: 3, + requirements: Some(vec![HolderSet::Items(vec![1, 2])]), + flags: 3, + }, + RecipeBookEntry { + id: 8, + display: RecipeDisplay::Smithing { + template: SlotDisplay::Composite(vec![SlotDisplay::Item(1)]), + base: SlotDisplay::WithRemainder { + input: Box::new(SlotDisplay::AnyFuel), + remainder: Box::new(SlotDisplay::Item(2)), + }, + addition: SlotDisplay::OnlyWithComponent( + Box::new(SlotDisplay::WithAnyPotion(Box::new(SlotDisplay::Item(3)))), + 9, + ), + result: SlotDisplay::SmithingTrim { + base: Box::new(SlotDisplay::Item(4)), + material: Box::new(SlotDisplay::Dyed { + dye: Box::new(SlotDisplay::Item(5)), + target: Box::new(SlotDisplay::Item(6)), + }), + pattern: TrimPattern::Id(2), + }, + station: SlotDisplay::Item(7), + }, + group: 0, + category: 11, + requirements: None, + flags: 0, + }, + ], + replace: true, + }; + let mut w = Writer::new(); + RecipeBookAdd::write(&add, &mut w); + let mut r = Reader::new(&w.data); + assert_eq!(RecipeBookAdd::read(&mut r).unwrap(), add); + assert_eq!(r.remaining(), 0); + } +} diff --git a/crates/horizon-protocol/src/rsa.rs b/crates/horizon-protocol/src/rsa.rs index fe31e425e..d34489fb4 100644 --- a/crates/horizon-protocol/src/rsa.rs +++ b/crates/horizon-protocol/src/rsa.rs @@ -3,8 +3,10 @@ //! and challenge (Crypt.encryptUsingKey, Java's "RSA" cipher = //! RSA/ECB/PKCS1Padding), and on the server's side the key pair it makes at //! startup (Crypt.generateKeyPair: 1024 bits) and the decryption -//! (Crypt.decryptUsingKey). Modular exponentiation uses Montgomery -//! multiplication on 32-bit limbs; RSA moduli are always odd. +//! (Crypt.decryptUsingKey); and the PKCS#1 v1.5 signature checks of secure +//! chat (SHA256withRSA for messages, SHA1withRSA for the services' profile +//! key signatures). Modular exponentiation uses Montgomery multiplication on +//! 32-bit limbs; RSA moduli are always odd. use crate::{Error, Result}; /// A non-negative integer, little-endian 32-bit limbs. @@ -291,6 +293,63 @@ impl RsaPublicKey { } } +/// The digest a PKCS#1 v1.5 signature covers: Java's `SHA1withRSA` and +/// `SHA256withRSA`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum SignatureHash { + Sha1, + Sha256, +} + +impl SignatureHash { + /// The DER DigestInfo before the digest (RFC 8017 9.2, note 1). + fn prefix(self) -> &'static [u8] { + match self { + Self::Sha1 => &[ + 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, + 0x14, + ], + Self::Sha256 => &[ + 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, + 0x01, 0x05, 0x00, 0x04, 0x20, + ], + } + } + fn digest(self, message: &[u8]) -> Vec { + use sha1::Digest; + match self { + Self::Sha1 => sha1::Sha1::digest(message).to_vec(), + Self::Sha256 => sha2::Sha256::digest(message).to_vec(), + } + } +} + +impl RsaPublicKey { + /// `Signature.verify` for RSASSA-PKCS1-v1_5 (RFC 8017 8.2.2): the + /// signature is exactly the modulus' length and below it, and opens to + /// `00 01 FF.. 00 DigestInfo`. Anything else is a failed check, as + /// SignatureValidator reports Java's exceptions. + pub fn verify(&self, hash: SignatureHash, message: &[u8], signature: &[u8]) -> bool { + let k = self.size(); + // Equal lengths compare as big-endian numbers. + if signature.len() != k || signature >= self.modulus.as_slice() { + return false; + } + let (prefix, digest) = (hash.prefix(), hash.digest(message)); + let t = prefix.len() + digest.len(); + if k < t + 11 { + return false; + } + let mut expected = vec![0xff; k]; + expected[0] = 0; + expected[1] = 1; + expected[k - t - 1] = 0; + expected[k - t..k - digest.len()].copy_from_slice(prefix); + expected[k - digest.len()..].copy_from_slice(&digest); + self.apply(signature, &self.exponent) == expected + } +} + /// Small odd primes for sieving prime candidates. const SMALL_PRIMES: [u32; 53] = [ 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, @@ -604,5 +663,34 @@ pub(crate) mod tests { assert!(block.ends_with(&hex( "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824" ))); + let signature = hex(TEST_SIG_HELLO); + assert!(key.verify(SignatureHash::Sha256, b"hello", &signature)); + assert!(!key.verify(SignatureHash::Sha256, b"hellO", &signature)); + assert!(!key.verify(SignatureHash::Sha1, b"hello", &signature)); + let mut flipped = signature.clone(); + flipped[40] ^= 1; + assert!(!key.verify(SignatureHash::Sha256, b"hello", &flipped)); + assert!(!key.verify(SignatureHash::Sha256, b"hello", &signature[1..])); + assert!(!key.verify(SignatureHash::Sha256, b"hello", &key.modulus)); + } + + /// Signatures made here with the private exponent (EMSA-PKCS1-v1_5 by + /// hand) check out for both digests. + #[test] + fn verifies_both_digests() { + let key = RsaPublicKey::from_der(&hex(TEST_SPKI)).unwrap(); + for hash in [SignatureHash::Sha1, SignatureHash::Sha256] { + let (prefix, digest) = (hash.prefix(), hash.digest(b"payload")); + let mut block = vec![0xff; 128]; + block[0] = 0; + block[1] = 1; + let t = prefix.len() + digest.len(); + block[127 - t] = 0; + block[128 - t..128 - digest.len()].copy_from_slice(prefix); + block[128 - digest.len()..].copy_from_slice(&digest); + let signature = key.apply(&block, &hex(TEST_D)); + assert!(key.verify(hash, b"payload", &signature)); + assert!(!key.verify(hash, b"payloaD", &signature)); + } } } diff --git a/crates/horizon-protocol/src/secure_chat.rs b/crates/horizon-protocol/src/secure_chat.rs new file mode 100644 index 000000000..534c132f6 --- /dev/null +++ b/crates/horizon-protocol/src/secure_chat.rs @@ -0,0 +1,491 @@ +//! Secure chat as vanilla 26.3's server keeps it: a player's profile key, +//! validated against the services' keys (ProfilePublicKey, +//! RemoteChatSession), the message chain each player signs +//! (SignedMessageChain), what a signature covers (PlayerChatMessage, +//! SignedMessageLink, SignedMessageBody), the window of messages a client +//! acknowledges (LastSeenMessagesValidator) and the cache a connection packs +//! signatures against (MessageSignatureCache). +use crate::rsa::{RsaPublicKey, SignatureHash}; +use std::collections::{HashSet, VecDeque}; + +/// MessageSignature.BYTES. +pub const SIGNATURE_BYTES: usize = 256; +/// A message signature (MessageSignature). +pub type Signature = [u8; SIGNATURE_BYTES]; +/// LastSeenMessages.LAST_SEEN_MESSAGES_MAX_LENGTH: the window a client acknowledges. +pub const LAST_SEEN: usize = 20; +/// PlayerChatMessage.MESSAGE_EXPIRES_AFTER_SERVER, in milliseconds. +pub const EXPIRES_AFTER_SERVER: i64 = 5 * 60 * 1000; + +/// A signature from its packet bytes (always 256 on the wire). +pub fn signature(bytes: &[u8]) -> Option { + bytes.try_into().ok() +} + +/// ProfilePublicKey.Data: the player's chat key (X.509 DER), when it +/// expires (epoch milliseconds), and the services' signature over both. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ProfileKey { + pub expires_at: i64, + pub key: Vec, + pub signature: Vec, +} + +impl ProfileKey { + /// Data.signedPayload: the profile id, the expiry and the key. + fn signed_payload(&self, profile: u128) -> Vec { + let mut out = Vec::with_capacity(24 + self.key.len()); + out.extend_from_slice(&profile.to_be_bytes()); + out.extend_from_slice(&self.expires_at.to_be_bytes()); + out.extend_from_slice(&self.key); + out + } + /// Data.validateSignature with the services' profile-key keys + /// (SignatureValidator.from(keySet, PROFILE_KEY): any of them, SHA1withRSA). + pub fn signed_by(&self, services: &[RsaPublicKey], profile: u128) -> bool { + let payload = self.signed_payload(profile); + services + .iter() + .any(|k| k.verify(SignatureHash::Sha1, &payload, &self.signature)) + } + /// Data.hasExpired. + pub fn has_expired(&self, now: i64) -> bool { + self.expires_at < now + } +} + +/// A validated RemoteChatSession: its id and the player's profile key. +#[derive(Clone, Debug)] +pub struct ChatSession { + pub id: u128, + pub profile_key: ProfileKey, + key: RsaPublicKey, +} + +impl ChatSession { + /// RemoteChatSession.Data.validate (ProfilePublicKey.createValidated); + /// the error is the disconnect message's translation key. + pub fn validate( + id: u128, + profile_key: ProfileKey, + services: &[RsaPublicKey], + profile: u128, + ) -> Result { + const INVALID: &str = "multiplayer.disconnect.invalid_public_key_signature"; + let key = RsaPublicKey::from_der(&profile_key.key).map_err(|_| INVALID)?; + if !profile_key.signed_by(services, profile) { + return Err(INVALID); + } + Ok(Self { + id, + profile_key, + key, + }) + } + /// RemoteChatSession.Data, as ClientboundPlayerInfoUpdatePacket's + /// INITIALIZE_CHAT carries it. + pub fn data(&self) -> (u128, i64, Vec, Vec) { + let k = &self.profile_key; + (self.id, k.expires_at, k.key.clone(), k.signature.clone()) + } +} + +/// SignedMessageBody: what a player signed besides the chain link. +#[derive(Clone, Copy, Debug)] +pub struct Body<'a> { + pub content: &'a str, + /// Epoch milliseconds. + pub timestamp: i64, + pub salt: i64, + pub last_seen: &'a [Signature], +} + +/// PlayerChatMessage.updateSignature: the version, the link (sender, +/// session, index) and the body (salt, time in seconds, content, last seen). +pub fn signed_payload(sender: u128, session: u128, index: i32, body: &Body) -> Vec { + let content = body.content.as_bytes(); + let mut out = Vec::with_capacity(64 + content.len() + body.last_seen.len() * SIGNATURE_BYTES); + out.extend_from_slice(&1i32.to_be_bytes()); + out.extend_from_slice(&sender.to_be_bytes()); + out.extend_from_slice(&session.to_be_bytes()); + out.extend_from_slice(&index.to_be_bytes()); + out.extend_from_slice(&body.salt.to_be_bytes()); + out.extend_from_slice(&body.timestamp.div_euclid(1000).to_be_bytes()); + out.extend_from_slice(&(content.len() as i32).to_be_bytes()); + out.extend_from_slice(content); + out.extend_from_slice(&(body.last_seen.len() as i32).to_be_bytes()); + for s in body.last_seen { + out.extend_from_slice(s); + } + out +} + +/// SignedMessageChain.DecodeException's messages, and the signed command +/// mismatch (ServerGamePacketListenerImpl.INVALID_COMMAND_SIGNATURE). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DecodeError { + MissingProfileKey, + ChainBroken, + ExpiredProfileKey, + InvalidSignature, + OutOfOrderChat, + InvalidCommandSignature, +} + +impl DecodeError { + pub fn key(self) -> &'static str { + match self { + Self::MissingProfileKey => "chat.disabled.missingProfileKey", + Self::ChainBroken => "chat.disabled.chain_broken", + Self::ExpiredProfileKey => "chat.disabled.expiredProfileKey", + Self::InvalidSignature => "chat.disabled.invalid_signature", + Self::OutOfOrderChat => "chat.disabled.out_of_order_chat", + Self::InvalidCommandSignature => "chat.disabled.invalid_command_signature", + } + } +} + +/// A message the chain let through: unsigned (PlayerChatMessage.unsigned) +/// or signed at a link of the sender's chain. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Unpacked { + Unsigned, + Signed { index: i32, signature: Signature }, +} + +/// A player's SignedMessageChain.Decoder: unsigned until the player sends a +/// chat session, then keyed to it. +#[derive(Clone, Debug, Default)] +pub struct Chain { + session: Option, + /// The next link's index; None once the chain is broken. + next: Option, + /// The last message's time (lastTimeStamp, from Instant.EPOCH). + last_timestamp: i64, +} + +impl Chain { + /// RemoteChatSession.createMessageDecoder: a new chain from link 0. + pub fn keyed(session: ChatSession) -> Self { + Self { + session: Some(session), + next: Some(0), + last_timestamp: 0, + } + } + pub fn session(&self) -> Option<&ChatSession> { + self.session.as_ref() + } + /// Decoder.unpack for `sender`'s message. Without a session the message + /// is unsigned unless the server enforces secure chat; with one it must + /// be the next link, in order, signed by the player's key. + pub fn unpack( + &mut self, + sender: u128, + signature: Option<&Signature>, + body: &Body, + enforce: bool, + now: i64, + ) -> Result { + let Some(session) = &self.session else { + return if enforce { + Err(DecodeError::MissingProfileKey) + } else { + Ok(Unpacked::Unsigned) + }; + }; + let signature = signature.ok_or(DecodeError::MissingProfileKey)?; + if session.profile_key.has_expired(now) { + return Err(DecodeError::ExpiredProfileKey); + } + let index = self.next.ok_or(DecodeError::ChainBroken)?; + if body.timestamp < self.last_timestamp { + self.next = None; + return Err(DecodeError::OutOfOrderChat); + } + self.last_timestamp = body.timestamp; + let payload = signed_payload(sender, session.id, index, body); + if !session + .key + .verify(SignatureHash::Sha256, &payload, signature) + { + self.next = None; + return Err(DecodeError::InvalidSignature); + } + self.next = index.checked_add(1); + Ok(Unpacked::Signed { + index, + signature: *signature, + }) + } + /// Decoder.setChainBroken (nothing for the unsigned decoder). + pub fn set_broken(&mut self) { + if self.session.is_some() { + self.next = None; + } + } +} + +/// Arrays.hashCode(byte[]). +fn java_hash(bytes: &[u8]) -> i32 { + bytes.iter().fold(1i32, |h, &b| { + h.wrapping_mul(31).wrapping_add(i32::from(b as i8)) + }) +} + +/// LastSeenMessages.computeChecksum: never 0, which means "not checked". +pub fn checksum(entries: &[Signature]) -> i8 { + let c = entries + .iter() + .fold(1i32, |c, e| c.wrapping_mul(31).wrapping_add(java_hash(e))); + match c as i8 { + 0 => 1, + b => b, + } +} + +/// LastSeenMessagesValidator: the messages sent to a player that its next +/// acknowledgement may name, each pending until it does. +#[derive(Clone, Debug)] +pub struct LastSeenValidator { + tracked: VecDeque>, + last_pending: Option, +} + +impl Default for LastSeenValidator { + fn default() -> Self { + Self { + tracked: std::iter::repeat_n(None, LAST_SEEN).collect(), + last_pending: None, + } + } +} + +impl LastSeenValidator { + pub fn add_pending(&mut self, signature: &Signature) { + if self.last_pending.as_ref() != Some(signature) { + self.tracked.push_back(Some((*signature, true))); + self.last_pending = Some(*signature); + } + } + pub fn tracked_count(&self) -> usize { + self.tracked.len() + } + /// applyOffset: drop the `offset` oldest messages. + pub fn apply_offset(&mut self, offset: i32) -> Result<(), String> { + let max = self.tracked.len() as i64 - LAST_SEEN as i64; + if offset >= 0 && i64::from(offset) <= max { + self.tracked.drain(..offset as usize); + Ok(()) + } else { + Err(format!( + "Advanced last seen window by {offset} messages, but expected at most {max}" + )) + } + } + /// applyUpdate: the offset, then the acknowledged messages of the + /// window (a 20-bit set, little-endian bytes), checked against the + /// client's checksum unless it sent 0. + pub fn apply_update( + &mut self, + offset: i32, + acknowledged: [u8; 3], + checksum: i8, + ) -> Result, String> { + self.apply_offset(offset)?; + let bit = |i: usize| acknowledged[i / 8] >> (i % 8) & 1 != 0; + let length = (0..24).rev().find(|&i| bit(i)).map_or(0, |i| i + 1); + if length > LAST_SEEN { + return Err(format!( + "Last seen update contained {length} messages, but maximum window size is {LAST_SEEN}" + )); + } + let mut seen = Vec::with_capacity(LAST_SEEN); + for i in 0..LAST_SEEN { + let entry = self.tracked[i]; + if bit(i) { + let Some((s, _)) = entry else { + return Err(format!( + "Last seen update acknowledged unknown or previously ignored message at index {i}" + )); + }; + self.tracked[i] = Some((s, false)); + seen.push(s); + } else { + if let Some((_, false)) = entry { + return Err(format!( + "Last seen update ignored previously acknowledged message at index {i}" + )); + } + self.tracked[i] = None; + } + } + if checksum != 0 && checksum != self::checksum(&seen) { + return Err( + "Checksum mismatch on last seen update: the client and server must have desynced" + .to_owned(), + ); + } + Ok(seen) + } +} + +/// MessageSignatureCache: the 128 signatures a connection's client also +/// holds, so a packed signature can name one by index. +#[derive(Clone, Debug)] +pub struct SignatureCache { + entries: Vec>, +} + +impl Default for SignatureCache { + fn default() -> Self { + Self { + entries: vec![None; 128], + } + } +} + +impl SignatureCache { + /// MessageSignature.pack: the cache index, or the full signature. + pub fn pack(&self, signature: &Signature) -> (i32, Option>) { + match self + .entries + .iter() + .position(|e| e.as_ref() == Some(signature)) + { + Some(i) => (i as i32, None), + None => (-1, Some(signature.to_vec())), + } + } + /// push(body, signature): the message's last seen and its signature go + /// to the front, most recent first; what they displace moves back. + pub fn push(&mut self, last_seen: &[Signature], signature: Option<&Signature>) { + let mut queue: VecDeque = last_seen.iter().chain(signature).copied().collect(); + let new: HashSet = queue.iter().copied().collect(); + for slot in &mut self.entries { + let Some(next) = queue.pop_back() else { break }; + if let Some(old) = slot.replace(next) + && !new.contains(&old) + { + queue.push_front(old); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sig(b: u8) -> Signature { + [b; SIGNATURE_BYTES] + } + + #[test] + fn payload_layout_matches_update_signature() { + let body = Body { + content: "hé", + timestamp: 1_700_000_123_456, + salt: -2, + last_seen: &[sig(7)], + }; + let p = signed_payload(1, 2, 3, &body); + assert_eq!(&p[..4], &[0, 0, 0, 1]); + assert_eq!(&p[4..20], &1u128.to_be_bytes()); + assert_eq!(&p[20..36], &2u128.to_be_bytes()); + assert_eq!(&p[36..40], &3i32.to_be_bytes()); + assert_eq!(&p[40..48], &(-2i64).to_be_bytes()); + assert_eq!(&p[48..56], &1_700_000_123i64.to_be_bytes()); + assert_eq!(&p[56..60], &3i32.to_be_bytes()); + assert_eq!(&p[60..63], "hé".as_bytes()); + assert_eq!(&p[63..67], &1i32.to_be_bytes()); + assert_eq!(p.len(), 67 + 256); + // Instant.getEpochSecond floors. + let before = Body { + timestamp: -1, + ..body + }; + assert_eq!( + &signed_payload(1, 2, 3, &before)[48..56], + &(-1i64).to_be_bytes() + ); + } + + #[test] + fn unsigned_chain_follows_enforcement() { + let mut chain = Chain::default(); + let body = Body { + content: "hi", + timestamp: 5, + salt: 0, + last_seen: &[], + }; + assert_eq!( + chain.unpack(1, None, &body, false, 0), + Ok(Unpacked::Unsigned) + ); + assert_eq!( + chain.unpack(1, Some(&sig(1)), &body, false, 0), + Ok(Unpacked::Unsigned) + ); + assert_eq!( + chain.unpack(1, None, &body, true, 0), + Err(DecodeError::MissingProfileKey) + ); + } + + #[test] + fn checksums_follow_java_hash_codes() { + // Arrays.hashCode(new byte[]{-1}) = 31 + (-1) = 30. + assert_eq!(java_hash(&[0xff]), 30); + assert_eq!(checksum(&[]), 1); + let one = [sig(0)]; + let expected = 31i32.wrapping_add(java_hash(&sig(0))) as i8; + assert_eq!(checksum(&one), if expected == 0 { 1 } else { expected }); + } + + #[test] + fn last_seen_window() { + let mut v = LastSeenValidator::default(); + assert_eq!(v.tracked_count(), 20); + v.add_pending(&sig(1)); + v.add_pending(&sig(1)); + v.add_pending(&sig(2)); + assert_eq!(v.tracked_count(), 22); + assert!(v.apply_offset(3).is_err()); + // Slide by two: the two messages are the window's last entries. + let mut ack = [0u8; 3]; + ack[18 / 8] |= 1 << (18 % 8); + ack[19 / 8] |= 1 << (19 % 8); + let seen = v.apply_update(2, ack, checksum(&[sig(1), sig(2)])).unwrap(); + assert_eq!(seen, vec![sig(1), sig(2)]); + // Once acknowledged, a message can't be ignored. + assert!(v.apply_update(0, [0; 3], 0).is_err()); + let mut v = LastSeenValidator::default(); + v.add_pending(&sig(1)); + assert!(v.apply_update(1, [0, 0, 0x10], 0).is_err(), "bit 20"); + let mut v = LastSeenValidator::default(); + assert!(v.apply_update(0, [1, 0, 0], 0).is_err(), "unknown"); + let mut v = LastSeenValidator::default(); + v.add_pending(&sig(1)); + let mut ack = [0u8; 3]; + ack[2] |= 1 << 3; + assert!(v.apply_update(1, ack, 99).is_err(), "checksum"); + } + + #[test] + fn cache_moves_recent_signatures_first() { + let mut c = SignatureCache::default(); + assert_eq!(c.pack(&sig(1)), (-1, Some(sig(1).to_vec()))); + c.push(&[], Some(&sig(1))); + assert_eq!(c.pack(&sig(1)), (0, None)); + c.push(&[sig(1)], Some(&sig(2))); + assert_eq!(c.pack(&sig(2)), (0, None)); + assert_eq!(c.pack(&sig(1)), (1, None)); + c.push(&[], Some(&sig(3))); + assert_eq!( + [c.pack(&sig(3)).0, c.pack(&sig(2)).0, c.pack(&sig(1)).0], + [0, 1, 2] + ); + } +} diff --git a/crates/horizon-server-files/Cargo.toml b/crates/horizon-server-files/Cargo.toml index 52114718d..2643fc726 100644 --- a/crates/horizon-server-files/Cargo.toml +++ b/crates/horizon-server-files/Cargo.toml @@ -4,13 +4,17 @@ version = "0.1.0" edition.workspace = true license.workspace = true rust-version = "1.90" -description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans" +description = "The dedicated server's vanilla files: server.properties, eula.txt, ops, whitelist and bans, and account lookups" [dependencies] horizon-core = { path = "../horizon-core" } horizon-protocol = { path = "../horizon-protocol" } horizon-world = { path = "../horizon-world" } log = "0.4" +# Online mode: finding accounts by name (the services' profiles endpoint). +# Secure chat: the services' public keys arrive base64-encoded. +base64 = "0.22" +ureq = { version = "2", default-features = false, features = ["tls"] } [lints] workspace = true diff --git a/crates/horizon-server-files/src/json.rs b/crates/horizon-server-files/src/json.rs index 8e1d865b2..47fe6d5d3 100644 --- a/crates/horizon-server-files/src/json.rs +++ b/crates/horizon-server-files/src/json.rs @@ -78,6 +78,43 @@ impl Json { } } + /// `new GsonBuilder().create().toJson(element)`: compact, HTML-safe + /// strings, null members skipped. + pub fn gson(&self) -> String { + let mut out = String::new(); + self.write_gson(&mut out); + out + } + fn write_gson(&self, out: &mut String) { + match self { + Json::String(s) => quote(out, s, true), + Json::Array(items) => { + out.push('['); + for (i, v) in items.iter().enumerate() { + if i > 0 { + out.push(','); + } + v.write_gson(out); + } + out.push(']'); + } + Json::Object(m) => { + out.push('{'); + let members = m.iter().filter(|(_, v)| *v != Json::Null); + for (i, (k, v)) in members.enumerate() { + if i > 0 { + out.push(','); + } + quote(out, k, true); + out.push(':'); + v.write_gson(out); + } + out.push('}'); + } + other => other.write_compact(out), + } + } + /// `new GsonBuilder().setPrettyPrinting().create().toJson(element, writer)`: /// two-space indents, HTML-safe strings, null members skipped. pub fn pretty(&self) -> String { diff --git a/crates/horizon-server-files/src/lib.rs b/crates/horizon-server-files/src/lib.rs index 30c75c869..08c059905 100644 --- a/crates/horizon-server-files/src/lib.rs +++ b/crates/horizon-server-files/src/lib.rs @@ -1,10 +1,13 @@ //! The dedicated server's files and settings, ported from //! net.minecraft.server.dedicated and net.minecraft.server.players: -//! server.properties, eula.txt and the four user lists. The game's dedicated -//! server (`horizon-client --dedicated`) reads them, and `horizon-server` -//! manages them; this crate needs neither a window nor the game. +//! server.properties, eula.txt, the four user lists, usercache.json and +//! looking players up by name. The game's dedicated server +//! (`horizon-client --dedicated`) reads them, and `horizon-server` manages +//! them; this crate needs neither a window nor the game. pub mod eula; pub mod java_properties; pub mod json; +pub mod profiles; pub mod properties; +pub mod user_cache; pub mod user_lists; diff --git a/crates/horizon-server-files/src/profiles.rs b/crates/horizon-server-files/src/profiles.rs new file mode 100644 index 000000000..3e16e2a41 --- /dev/null +++ b/crates/horizon-server-files/src/profiles.rs @@ -0,0 +1,168 @@ +//! Finding a player's account by name, as an online-mode server does for the +//! names given to `op`, `whitelist` and `ban` (CachedUserNameToIdResolver, +//! MinecraftServicesProfileRepository.findProfileByName): the services' +//! `profiles` / `getByName` endpoint, found through the discovery document. +use crate::{ + json::{self, Json}, + user_lists::NameAndId, +}; +use horizon_protocol::rsa::RsaPublicKey; +use std::time::Duration; + +/// Mojang's services discovery document. +pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client"; + +/// The discovery document's URL: `HORIZON_API_DISCOVERY` overrides it like +/// authlib's `-Dminecraft.api.discovery.host`. +pub fn discovery_url() -> String { + std::env::var("HORIZON_API_DISCOVERY") + .ok() + .filter(|u| !u.is_empty()) + .unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned()) +} + +/// StringUtil.isValidPlayerName: at most 16 UTF-16 units, none a control +/// character, a space or above ASCII. +pub fn valid_player_name(name: &str) -> bool { + name.encode_utf16().count() <= 16 && name.encode_utf16().all(|c| c > 32 && c < 127) +} + +/// How a server resolves a name it was given (CachedUserNameToIdResolver.get, +/// without the usercache.json cache): an offline server makes the offline +/// profile; an online one asks the services (for the name in lower case) and +/// knows nobody they don't. +pub fn resolve(name: &str, online: bool) -> Option { + if online && valid_player_name(name) { + find_by_name(&discovery_url(), &name.to_ascii_lowercase()) + } else { + (!online).then(|| NameAndId::offline(name)) + } +} + +/// MinecraftServicesProfileRepository.findProfileByName: the account named +/// `name` (any case), or None when there is none or the services don't +/// answer (vanilla logs both as "Couldn't find profile with name"). +pub fn find_by_name(discovery: &str, name: &str) -> Option { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build(); + let doc = json::parse(&agent.get(discovery).call().ok()?.into_string().ok()?, true).ok()?; + let url = endpoint(&doc, "profiles", "getByName")?.replace("{name}", &name.to_lowercase()); + found(&agent.get(&url).call().ok()?.into_string().ok()?, name) +} + +/// MinecraftServicesKeyInfo.get: the services' public keys from the +/// discovery document's `authentication` / `getPublicKeys` endpoint. The +/// profile-key keys (`playerCertificateKeys`, ServicesKeyType.PROFILE_KEY) +/// sign the players' chat keys; secure chat checks them. The error is the +/// line vanilla logs, after which it has no keys. +pub fn fetch_profile_key_keys(discovery: &str) -> Result, &'static str> { + const FAILED: &str = "Failed to request Minecraft Services public key"; + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(15)) + .user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION"))) + .build(); + let get = |url: &str| agent.get(url).call().ok()?.into_string().ok(); + let doc = get(discovery) + .and_then(|d| json::parse(&d, true).ok()) + .ok_or(FAILED)?; + let url = endpoint(&doc, "authentication", "getPublicKeys").ok_or(FAILED)?; + profile_key_keys(&get(&url).ok_or(FAILED)?) +} + +/// The key set answer: `{"profilePropertyKeys": [...], "playerCertificateKeys": +/// [...]}`, each `{"publicKey": base64 X.509}`. One bad key makes the whole +/// answer malformed (parseList throws). +pub fn profile_key_keys(answer: &str) -> Result, &'static str> { + use base64::Engine; + const MALFORMED: &str = "Received malformed Minecraft Services public key data"; + let doc = json::parse(answer, true).map_err(|_| MALFORMED)?; + let list = |name: &str| -> Result, &'static str> { + let Some(entries) = doc.get(name) else { + return Ok(Vec::new()); + }; + let Json::Array(entries) = entries else { + return Err(MALFORMED); + }; + entries + .iter() + .map(|e| { + let text = e + .get("publicKey") + .and_then(Json::as_string) + .ok_or(MALFORMED)?; + let der = base64::engine::general_purpose::STANDARD + .decode(text) + .map_err(|_| MALFORMED)?; + RsaPublicKey::from_der(&der).map_err(|_| MALFORMED) + }) + .collect() + }; + list("profilePropertyKeys")?; + list("playerCertificateKeys") +} + +/// MinecraftServicesDiscoveryService.getUrl(service, endpoint). +fn endpoint(doc: &Json, service: &str, name: &str) -> Option { + doc.get("discovery")? + .get(service)? + .get("endpoints")? + .get(name)? + .get("uri")? + .as_string() +} + +/// The answer, authlib's NameAndId: `{"id", "name"}`, the id undashed. +pub fn found(answer: &str, name: &str) -> Option { + let profile = json::parse(answer, true).ok()?; + let found = profile.get("name")?.as_string()?; + let id = profile.get("id")?.as_string()?.replace('-', ""); + (found.eq_ignore_ascii_case(name) && id.len() == 32).then_some(())?; + Some(NameAndId { + id: u128::from_str_radix(&id, 16).ok()?, + name: found, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names_and_answers() { + assert!(valid_player_name("Alex_123")); + assert!(!valid_player_name("two words")); + assert!(!valid_player_name("ThisNameIsTooLong")); + assert!(!valid_player_name("caf\u{e9}")); + assert_eq!(resolve("Alex", false), Some(NameAndId::offline("Alex"))); + assert_eq!(resolve("not valid", true), None); + let answer = r#"{"id":"069a79f444e94726a5befca90e38aaf5","name":"Notch"}"#; + assert_eq!( + found(answer, "notch"), + Some(NameAndId { + id: 0x069a79f444e94726a5befca90e38aaf5, + name: "Notch".into() + }) + ); + assert_eq!(found(answer, "Steve"), None); + assert_eq!(found("{}", "Notch"), None); + assert_eq!(found("", "Notch"), None); + } + + #[test] + fn services_key_sets() { + // The 1024-bit test key of horizon-protocol's RSA tests, base64. + let key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCrAmB0+SRQqPcm84lbsRF2yo8GXzEAzUFDusT302dO3P+VtBoFJdI2WlScEG7GaFiBs5IXdCD9Mf9cFE/xG6JDEedRzSxrXRgXtq9mhqQ8ldYSQ2EwBeaUW2CTzZUiPOxeiFaCbanS7hsyM2KsHOvqs2WcvEUxmptUDdqBakeY/wIDAQAB"; + let answer = format!( + r#"{{"profilePropertyKeys":[{{"publicKey":"{key}"}}],"playerCertificateKeys":[{{"publicKey":"{key}"}},{{"publicKey":"{key}"}}]}}"# + ); + let keys = profile_key_keys(&answer).unwrap(); + assert_eq!(keys.len(), 2); + assert_eq!(keys[0].size(), 128); + assert_eq!(profile_key_keys("{}").unwrap().len(), 0); + let bad = r#"{"profilePropertyKeys":[{"publicKey":"AAAA"}],"playerCertificateKeys":[]}"#; + assert!(profile_key_keys(bad).is_err()); + assert!(profile_key_keys("not json").is_err()); + } +} diff --git a/crates/horizon-server-files/src/user_cache.rs b/crates/horizon-server-files/src/user_cache.rs new file mode 100644 index 000000000..c8ccd6cf0 --- /dev/null +++ b/crates/horizon-server-files/src/user_cache.rs @@ -0,0 +1,318 @@ +//! usercache.json (CachedUserNameToIdResolver): the players the server has +//! seen join or has looked up by name, so commands find a player by name +//! without asking the profile service again. Each entry expires a month after +//! it was added; the file keeps the 1000 most recently used. +use crate::{ + java_properties::{civil_from_days, days_from_civil, now_millis}, + json::{self, Json}, + profiles::valid_player_name, + user_lists::{NameAndId, format_date, parse_date}, +}; +use std::{collections::HashMap, path::PathBuf}; + +const MRU_LIMIT: usize = 1000; + +#[derive(Clone, Debug)] +struct Info { + user: NameAndId, + expires: i64, + last_access: u64, +} + +/// `Calendar.add(MONTH, 1)` on a UTC time: the same day and time a month +/// later, the day clamped to the end of a shorter month. +pub fn one_month_later(millis: i64) -> i64 { + let days = millis.div_euclid(86_400_000); + let time = millis.rem_euclid(86_400_000); + let (y, m, d) = civil_from_days(days); + let (y, m) = if m == 12 { (y + 1, 1) } else { (y, m + 1) }; + let last = days_from_civil( + if m == 12 { y + 1 } else { y }, + if m == 12 { 1 } else { m + 1 }, + 1, + ) - days_from_civil(y, m, 1); + let d = d.min(last as u32); + days_from_civil(y, m, d) * 86_400_000 + time +} + +pub struct UserCache { + file: PathBuf, + /// Every entry ever added; the maps point into it, as vanilla's two maps + /// share their GameProfileInfo objects. + infos: Vec, + by_name: HashMap, + by_uuid: HashMap, + operations: u64, + /// Off on an online-mode server: a name the profile service doesn't know + /// is then no player at all, rather than an offline one. + pub resolve_offline_users: bool, +} + +impl UserCache { + /// The cache in `file`, loaded; also returns the warnings vanilla logs. + pub fn load(file: impl Into) -> (Self, Vec) { + let mut cache = Self { + file: file.into(), + infos: Vec::new(), + by_name: HashMap::new(), + by_uuid: HashMap::new(), + operations: 0, + resolve_offline_users: true, + }; + let mut warnings = Vec::new(); + let entries = match std::fs::read_to_string(&cache.file) { + Ok(text) => cache.parse(&text, &mut warnings), + Err(_) => Vec::new(), + }; + for info in entries.into_iter().rev() { + cache.safe_add(info); + } + (cache, warnings) + } + + fn parse(&self, text: &str, warnings: &mut Vec) -> Vec { + let items = match json::parse(text, false) { + Ok(Json::Array(items)) => items, + // An empty file is Gson's null. + Ok(Json::Null) => return Vec::new(), + _ if text.trim().is_empty() => return Vec::new(), + _ => { + warnings.push(format!( + "Failed to load profile cache {}", + self.file.display() + )); + return Vec::new(); + } + }; + let mut out = Vec::new(); + for item in &items { + if !matches!(item, Json::Object(_)) { + continue; + } + let Some(user) = NameAndId::from_json(item) else { + continue; + }; + let Some(date) = item.get("expiresOn").and_then(Json::as_string) else { + continue; + }; + match parse_date(&date) { + Some(expires) => out.push(Info { + user, + expires, + last_access: 0, + }), + None => warnings.push(format!("Failed to parse date {date}")), + } + } + out + } + + fn safe_add(&mut self, mut info: Info) -> usize { + self.operations += 1; + info.last_access = self.operations; + let index = self.infos.len(); + self.by_name.insert(info.user.name.to_lowercase(), index); + self.by_uuid.insert(info.user.id, index); + self.infos.push(info); + index + } + + /// `add`: a player who joined, remembered for a month; saves the file. + pub fn add(&mut self, user: NameAndId) { + self.add_internal(user, now_millis()); + } + + fn add_internal(&mut self, user: NameAndId, now: i64) -> NameAndId { + let index = self.safe_add(Info { + user, + expires: one_month_later(now), + last_access: 0, + }); + self.save(); + self.infos[index].user.clone() + } + + /// `get(String)`: the player with this name (any case). An expired entry is + /// dropped; a name not cached is asked of `lookup` (the profile service, + /// given the lower-case name) and, failing that, made an offline player + /// when offline users resolve. What is found is cached. + pub fn get_by_name( + &mut self, + name: &str, + lookup: impl FnOnce(&str) -> Option, + ) -> Option { + self.get_by_name_at(name, now_millis(), lookup) + } + + fn get_by_name_at( + &mut self, + name: &str, + now: i64, + lookup: impl FnOnce(&str) -> Option, + ) -> Option { + let name = name.to_lowercase(); + let mut found = self.by_name.get(&name).copied(); + let mut needs_save = false; + if let Some(index) = found + && now >= self.infos[index].expires + { + let user = self.infos[index].user.clone(); + self.by_uuid.remove(&user.id); + self.by_name.remove(&user.name.to_lowercase()); + needs_save = true; + found = None; + } + let result = if let Some(index) = found { + self.operations += 1; + self.infos[index].last_access = self.operations; + Some(self.infos[index].user.clone()) + } else { + let profile = if valid_player_name(&name) { + lookup(&name) + } else { + None + }; + let profile = profile.or_else(|| { + self.resolve_offline_users + .then(|| NameAndId::offline(&name)) + }); + match profile { + Some(profile) => { + needs_save = false; + Some(self.add_internal(profile, now)) + } + None => None, + } + }; + if needs_save { + self.save(); + } + result + } + + /// `get(UUID)`: a cached player by id (expired or not). + pub fn get_by_id(&mut self, id: u128) -> Option { + let index = *self.by_uuid.get(&id)?; + self.operations += 1; + self.infos[index].last_access = self.operations; + Some(self.infos[index].user.clone()) + } + + /// The file's text: the 1000 most recently used entries, most recent + /// first, as Gson writes them (compact, HTML-safe). + pub fn to_json(&self) -> String { + let mut entries: Vec<&Info> = self.by_uuid.values().map(|&i| &self.infos[i]).collect(); + entries.sort_by_key(|info| std::cmp::Reverse(info.last_access)); + let items = entries + .into_iter() + .take(MRU_LIMIT) + .map(|info| { + let mut o = Json::Object(Vec::new()); + info.user.append_to(&mut o); + o.add("expiresOn", Json::String(format_date(info.expires))); + o + }) + .collect(); + Json::Array(items).gson() + } + + /// `save`: errors are ignored, as vanilla does. + pub fn save(&self) { + let _ = std::fs::write(&self.file, self.to_json()); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const DAY: i64 = 86_400_000; + + fn cache(text: &str) -> (UserCache, Vec) { + let dir = std::env::temp_dir().join(format!( + "horizon-usercache-{}-{}", + std::process::id(), + text.len() + )); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("usercache.json"); + std::fs::write(&file, text).unwrap(); + UserCache::load(file) + } + + #[test] + fn months() { + let jan31 = days_from_civil(2026, 1, 31) * DAY + 3_723_000; + assert_eq!( + format_date(one_month_later(jan31)), + "2026-02-28 01:02:03 +0000" + ); + let dec15 = days_from_civil(2026, 12, 15) * DAY; + assert_eq!( + format_date(one_month_later(dec15)), + "2027-01-15 00:00:00 +0000" + ); + let jan31_leap = days_from_civil(2028, 1, 31) * DAY; + assert_eq!( + format_date(one_month_later(jan31_leap)), + "2028-02-29 00:00:00 +0000" + ); + } + + #[test] + fn keeps_order_and_skips_bad_entries() { + let (c, warnings) = cache( + r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"}, + 1, {"name":"NoId"}, {"uuid":"853c80ef-3c37-49fd-aa49-938b674adae6","name":"NoDate"}, + {"uuid":"853c80ef-3c37-49fd-aa49-938b674adae6","name":"BadDate","expiresOn":"soon"}, + {"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Alex","expiresOn":"2099-01-01 00:00:00 +0000"}]"#, + ); + assert_eq!(warnings, vec!["Failed to parse date soon".to_owned()]); + assert_eq!( + c.to_json(), + r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"},{"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Alex","expiresOn":"2099-01-01 00:00:00 +0000"}]"# + ); + } + + #[test] + fn names_resolve_through_the_cache() { + let (mut c, _) = cache( + r#"[{"uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","name":"Notch","expiresOn":"2099-01-01 00:00:00 +0000"}, + {"uuid":"61699b2e-d327-4a01-9f1e-0ea8c3f06bc6","name":"Old","expiresOn":"2000-01-01 00:00:00 +0000"}]"#, + ); + let now = days_from_civil(2026, 10, 17) * DAY; + let never = |_: &str| -> Option { panic!("looked up") }; + // A hit in any case, and it becomes the most recent. + let notch = c.get_by_name_at("NOTCH", now, never).unwrap(); + assert_eq!(notch.name, "Notch"); + // Expired: dropped and looked up again, by its lower-case name. + let mut asked = Vec::new(); + let old = c + .get_by_name_at("Old", now, |n| { + asked.push(n.to_owned()); + None + }) + .unwrap(); + assert_eq!(asked, ["old"]); + assert_eq!(old, NameAndId::offline("old")); + // Not a valid name: never looked up. + let odd = c.get_by_name_at("a b", now, never).unwrap(); + assert_eq!(odd, NameAndId::offline("a b")); + c.resolve_offline_users = false; + assert_eq!(c.get_by_name_at("Nobody", now, |_| None), None); + let found = NameAndId { + id: 7, + name: "Steve".into(), + }; + let steve = c.get_by_name_at("steve", now, |_| Some(found.clone())); + assert_eq!(steve, Some(found)); + let json = c.to_json(); + let names: Vec<&str> = json + .split("\"name\":\"") + .skip(1) + .map(|s| s.split('"').next().unwrap()) + .collect(); + assert_eq!(names, ["Steve", "a b", "old", "Notch"]); + assert!(json.contains(r#""name":"Steve","expiresOn":"2026-11-17 00:00:00 +0000"}"#)); + } +} diff --git a/crates/horizon-server-files/src/user_lists.rs b/crates/horizon-server-files/src/user_lists.rs index 3d35aa62f..77de64e31 100644 --- a/crates/horizon-server-files/src/user_lists.rs +++ b/crates/horizon-server-files/src/user_lists.rs @@ -39,7 +39,7 @@ impl NameAndId { name: name.to_owned(), } } - fn from_json(o: &Json) -> Option { + pub(crate) fn from_json(o: &Json) -> Option { let uuid = o.get("uuid")?.as_string()?; let name = o.get("name")?.as_string()?; Some(Self { @@ -47,7 +47,7 @@ impl NameAndId { name, }) } - fn append_to(&self, o: &mut Json) { + pub(crate) fn append_to(&self, o: &mut Json) { o.add("uuid", Json::String(uuid_string(self.id))); o.add("name", Json::String(self.name.clone())); } diff --git a/crates/horizon-server/src/config.rs b/crates/horizon-server/src/config.rs index c62869e27..3c389f858 100644 --- a/crates/horizon-server/src/config.rs +++ b/crates/horizon-server/src/config.rs @@ -23,7 +23,7 @@ motd = "A Minecraft Server" port = 25565 bind = "" # listen on every address, or only on this one (server-ip) max_players = 20 -online_mode = true # not supported by Horizon yet: the server runs offline and says so +online_mode = true # check players' Minecraft accounts (false: anyone joins under any name) whitelist = true # only whitelisted players and operators can join enforce_whitelist = false # kick online players taken off the whitelist view_distance = 10 diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 37e43df80..757b6def8 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -6,7 +6,7 @@ use crate::{config, config::Config, engine}; use horizon_server_files::{ eula, java_properties::now_millis, - user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}, + user_lists::{OpEntry, OpList, WhiteEntry, WhiteList}, }; use std::{ io::{BufRead, IsTerminal, Write}, @@ -23,6 +23,8 @@ pub struct Answers { pub whitelist: Option, pub players: Vec, pub op: Option, + /// online-mode (true unless set): players' Minecraft accounts are checked. + pub online: Option, /// Take the default for every question not answered by a flag. pub yes: bool, } @@ -30,7 +32,7 @@ pub struct Answers { impl Answers { /// The answers in the environment, for containers: `HORIZON_EULA=true`, `HORIZON_WORLD`, /// `HORIZON_SEED`, `HORIZON_PORT`, `HORIZON_WHITELIST=true|false`, `HORIZON_PLAYERS` (names separated by - /// commas) and `HORIZON_OP`. Flags given on the command line win. + /// commas), `HORIZON_OP` and `HORIZON_ONLINE=true|false`. Flags given on the command line win. pub fn from_env() -> Result { let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty()); let flag = |name: &str| var(name).map(|v| v.eq_ignore_ascii_case("true")); @@ -54,6 +56,7 @@ impl Answers { }) .unwrap_or_default(), op: var("HORIZON_OP"), + online: flag("HORIZON_ONLINE"), yes: false, }) } @@ -172,6 +175,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { } // 4. Who may join. + if let Some(online) = answers.online { + cfg.server.online_mode = online; + } cfg.server.whitelist = answers.whitelist.unwrap_or_else(|| { prompt.yes( "Only let in players you list (whitelist)?", @@ -193,7 +199,7 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { .yes(&format!("Make {first} an operator?"), true) .then(|| first.clone()) }); - add_players(dir, &players, op.as_deref())?; + add_players(dir, &players, op.as_deref(), cfg.server.online_mode)?; // 5. The game and its files. match engine::program(&cfg, dir) { @@ -213,24 +219,29 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { toml_path.display(), dir.display() ); - if cfg.server.online_mode { + if !cfg.server.online_mode { println!( - "Note: Horizon's server doesn't check Mojang accounts yet (online mode), so it runs offline: \ - keep the whitelist on, or play on a LAN or a tailnet." + "Note: online mode is off, so anyone can join under any name: keep the whitelist on, or play on a \ + LAN or a tailnet." ); } Ok(()) } -/// Adds players to the whitelist (and one as an operator) in vanilla's files, with offline UUIDs as the -/// server runs offline. -fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), String> { +/// Adds players to the whitelist (and one as an operator) in vanilla's files, with the profiles the server +/// will see: offline ones, or in online mode their accounts. +fn add_players( + dir: &Path, + players: &[String], + op: Option<&str>, + online: bool, +) -> Result<(), String> { if !players.is_empty() { let mut white = WhiteList::new(dir.join("whitelist.json")); let _ = white.load(); for name in players { white.add(WhiteEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, }); } println!("Whitelisted: {}", players.join(", ")); @@ -239,7 +250,7 @@ fn add_players(dir: &Path, players: &[String], op: Option<&str>) -> Result<(), S let mut ops = OpList::new(dir.join("ops.json")); let _ = ops.load(); ops.add(OpEntry { - user: NameAndId::offline(name), + user: crate::lists::account(name, online)?, level: 4, bypasses_player_limit: false, }); @@ -264,6 +275,8 @@ mod tests { whitelist: Some(true), players: vec!["Alex".into(), "Steve".into()], op: Some("Alex".into()), + // Offline: no account lookups in a test. + online: Some(false), yes: true, }; run(&dir, answers).unwrap(); @@ -277,6 +290,7 @@ mod tests { ("survival", "12345", 25599) ); assert!(eula::agreed(&dir.join("eula.txt")).unwrap()); + assert!(!cfg.server.online_mode); let white = std::fs::read_to_string(dir.join("whitelist.json")).unwrap(); assert!( white.contains("\"Alex\"") && white.contains("\"Steve\""), diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs index 398ccfe10..a6c466666 100644 --- a/crates/horizon-server/src/lists.rs +++ b/crates/horizon-server/src/lists.rs @@ -20,7 +20,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { let message = match (command, args.as_slice()) { ("op", [name]) => { let mut ops = load(OpList::new(ops_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if ops.contains(&user) { "Nothing changed. The player already is an operator".to_owned() } else { @@ -34,7 +34,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("deop", [name]) => { let mut ops = load(OpList::new(ops_path))?; - if ops.remove(&NameAndId::offline(name)) { + let user = listed(ops.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| ops.remove(&user)) { format!("Made {name} no longer a server operator") } else { "Nothing changed. The player is not an operator".to_owned() @@ -42,7 +43,7 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["add", name]) => { let mut white = load(WhiteList::new(white_path))?; - let user = NameAndId::offline(name); + let user = account(name, config.server.online_mode)?; if white.contains(&user) { "Player is already whitelisted".to_owned() } else { @@ -52,7 +53,8 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { } ("whitelist", ["remove", name]) => { let mut white = load(WhiteList::new(white_path))?; - if white.remove(&NameAndId::offline(name)) { + let user = listed(white.entries().iter().map(|e| &e.user), name); + if user.is_some_and(|user| white.remove(&user)) { format!("Removed {name} from the whitelist") } else { "Player is not whitelisted".to_owned() @@ -97,6 +99,23 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { Ok(()) } +/// The profile a running server would store for `name`: the offline one, or in online mode the account the +/// services know by that name. +pub fn account(name: &str, online: bool) -> Result { + horizon_server_files::profiles::resolve(name, online).ok_or_else(|| { + if online { + format!("That player does not exist (no Minecraft account is named {name}, or the services didn't answer)") + } else { + "That player does not exist".to_owned() + } + }) +} + +/// The entry already on a list under `name` (any case), so removing needs no lookup. +fn listed<'a>(mut users: impl Iterator, name: &str) -> Option { + users.find(|u| u.name.eq_ignore_ascii_case(name)).cloned() +} + /// A list from its file; a missing file is an empty list, a broken one an error (vanilla would replace it). fn load( mut list: horizon_server_files::user_lists::UserList, diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index af45015de..c37da27a5 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -23,7 +23,7 @@ Usage: horizon-server [--dir DIR] init Set up a server here: the EULA, the world, the port, who may join (asks, or takes flags: --eula --world NAME --seed SEED --port N --whitelist/--no-whitelist --player NAME... --op NAME - --yes) + --offline --yes) run Run the server in the foreground; type console commands, Ctrl-C stops it cleanly. It restarts the game if it crashes. start Run the server in the background (its output goes to logs/supervisor.log) @@ -150,6 +150,7 @@ fn init_answers(args: &[String]) -> Result { "--no-whitelist" => answers.whitelist = Some(false), "--player" => answers.players.push(value(arg)?), "--op" => answers.op = Some(value(arg)?), + "--offline" => answers.online = Some(false), other => return Err(format!("init: unknown option {other}")), } } diff --git a/crates/horizon-world/Cargo.toml b/crates/horizon-world/Cargo.toml index 737edd289..3a8621243 100644 --- a/crates/horizon-world/Cargo.toml +++ b/crates/horizon-world/Cargo.toml @@ -13,7 +13,7 @@ serde = { version = "1", features = ["derive"] } sha2 = "0.10" postcard = { version = "=1.1.3", default-features = false, features = ["alloc"] } horizon-core = { path = "../horizon-core" } -flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] } +flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] } lz4_flex = { version = "0.14", default-features = false, features = ["std", "safe-encode", "safe-decode", "checked-decode"] } xxhash-rust = { version = "0.8.19", features = ["xxh32"] } diff --git a/crates/horizon-world/src/block_properties.rs b/crates/horizon-world/src/block_properties.rs index 2a463b9e3..7c0e17f61 100644 --- a/crates/horizon-world/src/block_properties.rs +++ b/crates/horizon-world/src/block_properties.rs @@ -2,11 +2,10 @@ //! collision shapes. Replacement with an item/fluid context is separate behavior. use crate::{ DATA_VERSION, - chunk::BlockState, collision::CachedCollisionRegistry, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::geometry::{Direction, ShapeError, ShapeOp, VoxelShape}; use std::{ @@ -112,21 +111,25 @@ pub struct BlockPropertiesRegistry<'r> { } impl<'r> BlockPropertiesRegistry<'r> { pub fn from_nbt(tag: &Tag, collisions: &CachedCollisionRegistry<'r>) -> io::Result { + Self::from_table( + BlockTable::check(tag, collisions.registry(), "block property")?, + collisions, + ) + } + pub fn from_table( + table: BlockTable<'_, '_>, + collisions: &CachedCollisionRegistry<'r>, + ) -> io::Result { let registry = collisions.registry(); + if !std::ptr::eq(table.registry(), registry) { + return Err(invalid( + "block properties and collisions use other registries", + )); + } + let tag = table.tag(); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("block properties DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing block property state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("block property registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("block property state identities differ")); - } - } let Some(Tag::Compound(blocks)) = tag.get("blocks") else { return Err(invalid("missing block definition properties")); }; @@ -150,10 +153,8 @@ impl<'r> BlockPropertiesRegistry<'r> { }, ); } - let occlusion = CachedCollisionRegistry::from_nbt( - tag.get("occlusion") - .ok_or_else(|| invalid("missing block occlusion shapes"))?, - registry, + let occlusion = CachedCollisionRegistry::from_table( + table.nested("occlusion", "block occlusion shapes")?, )?; let mut result = Vec::with_capacity(registry.len()); let mut faces = Vec::with_capacity(registry.len()); diff --git a/crates/horizon-world/src/block_support.rs b/crates/horizon-world/src/block_support.rs index 2c7a9aecc..295999d18 100644 --- a/crates/horizon-world/src/block_support.rs +++ b/crates/horizon-world/src/block_support.rs @@ -61,7 +61,7 @@ use crate::{ collision::CachedCollisionRegistry, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use std::{collections::HashMap, io}; /// Cached branch of BlockState.isFaceSturdy. Dynamic support-shape selection @@ -72,10 +72,14 @@ pub struct CachedBlockSupportRegistry<'r> { } impl<'r> CachedBlockSupportRegistry<'r> { pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { - if tag.get("Kind") != Some(&Tag::String("block_support".into())) { + Self::from_table(BlockTable::check(tag, registry, "support")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result { + if table.get("Kind") != Some(&Tag::String("block_support".into())) { return Err(invalid("wrong cached support data kind")); } - let shapes = CachedCollisionRegistry::from_nbt(tag, registry)?; + let registry = table.registry(); + let shapes = CachedCollisionRegistry::from_table(table)?; let mut cache = HashMap::new(); let mut states = Vec::with_capacity(registry.len()); for id in 0..registry.len() { @@ -163,7 +167,11 @@ impl std::fmt::Display for SupportQueryError { impl std::error::Error for SupportQueryError {} impl<'r> BlockSupportRegistry<'r> { pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { - let cached = CachedBlockSupportRegistry::from_nbt(tag, registry)?; + Self::from_table(BlockTable::check(tag, registry, "support")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result { + let registry = table.registry(); + let cached = CachedBlockSupportRegistry::from_table(table)?; let mut dynamic = HashMap::new(); for id in 0..registry.len() { let id = BlockStateId(id as u32); diff --git a/crates/horizon-world/src/chunk.rs b/crates/horizon-world/src/chunk.rs index f4341c92f..fdbefe259 100644 --- a/crates/horizon-world/src/chunk.rs +++ b/crates/horizon-world/src/chunk.rs @@ -442,54 +442,58 @@ impl<'r> BlockSection<'r> { if index >= 4096 { return Err(invalid("section index out of bounds")); } - let id = self.storage.as_ref().map_or(0, |s| s.get(index).unwrap()); + let id = self.storage.as_ref().map_or(0, |s| s.read(index)); Ok(self.palette[id as usize]) } pub fn set(&mut self, index: usize, state: BlockStateId) -> io::Result { - let old = self.get(index)?; + if index >= 4096 { + return Err(invalid("section index out of bounds")); + } if state.0 as usize >= self.registry.len() { return Err(invalid("state ID outside registry")); } + // The slot at `index` is the old state's id, so no palette lookup is + // needed for it; only the new state has to be resolved. + let old_id = self.storage.as_ref().map_or(0, |s| s.read(index)); + let old = self.palette[old_id as usize]; if old == state { return Ok(old); } - let old_id = self.local_ids[&old]; - if self.counts[old_id as usize] == 1 && !self.local_ids.contains_key(&state) { - // Replacing the last occurrence can reuse its slot without repacking. - self.palette[old_id as usize] = state; - self.local_ids.remove(&old); - self.local_ids.insert(state, old_id); - return Ok(old); - } - let id = if let Some(id) = self.local_ids.get(&state) { - *id - } else if let Some(id) = self.free.pop() { - self.palette[id as usize] = state; - self.local_ids.insert(state, id); - id - } else { - let id = self.palette.len() as u32; - let next_bits = bits_for_palette(self.palette.len() + 1, 4); - if next_bits != self.bits() { - let mut storage = - PackedStorage::new(next_bits, 4096).map_err(|e| invalid(e.to_string()))?; - if let Some(old) = &self.storage { - for i in 0..4096 { - storage.set(i, old.get(i).unwrap()).unwrap(); - } - } - self.storage = Some(storage); + let id = match self.local_ids.get(&state) { + Some(&id) => id, + None if self.counts[old_id as usize] == 1 => { + // Replacing the last occurrence can reuse its slot without repacking. + self.palette[old_id as usize] = state; + self.local_ids.remove(&old); + self.local_ids.insert(state, old_id); + return Ok(old); + } + None => { + if let Some(id) = self.free.pop() { + self.palette[id as usize] = state; + self.local_ids.insert(state, id); + id + } else { + let id = self.palette.len() as u32; + let next_bits = bits_for_palette(self.palette.len() + 1, 4); + if next_bits != self.bits() { + let mut storage = PackedStorage::new(next_bits, 4096) + .map_err(|e| invalid(e.to_string()))?; + if let Some(old) = &self.storage { + for i in 0..4096 { + storage.write(i, old.read(i)); + } + } + self.storage = Some(storage); + } + self.palette.push(state); + self.counts.push(0); + self.local_ids.insert(state, id); + id + } } - self.palette.push(state); - self.counts.push(0); - self.local_ids.insert(state, id); - id }; - self.storage - .as_mut() - .unwrap() - .set(index, id) - .map_err(|e| invalid(e.to_string()))?; + self.storage.as_mut().unwrap().write(index, id); self.counts[old_id as usize] -= 1; self.counts[id as usize] += 1; if self.counts[old_id as usize] == 0 { @@ -585,4 +589,271 @@ mod tests { map.insert(key("data"), Tag::LongArray(vec![-1; 256])); assert!(PalettedContainer::from_nbt(&tag, 4096, 4).is_err()); } + + /// The pre-optimization `get`, kept to compare against in the benchmark. + fn baseline_get(section: &BlockSection<'_>, index: usize) -> io::Result { + if index >= 4096 { + return Err(invalid("section index out of bounds")); + } + let id = section + .storage + .as_ref() + .map_or(0, |s| s.get(index).unwrap()); + Ok(section.palette[id as usize]) + } + /// The pre-optimization `set`, kept to compare against in the benchmark. + fn baseline_set( + section: &mut BlockSection<'_>, + index: usize, + state: BlockStateId, + ) -> io::Result { + let old = baseline_get(section, index)?; + if state.0 as usize >= section.registry.len() { + return Err(invalid("state ID outside registry")); + } + if old == state { + return Ok(old); + } + let old_id = section.local_ids[&old]; + if section.counts[old_id as usize] == 1 && !section.local_ids.contains_key(&state) { + section.palette[old_id as usize] = state; + section.local_ids.remove(&old); + section.local_ids.insert(state, old_id); + return Ok(old); + } + let id = if let Some(id) = section.local_ids.get(&state) { + *id + } else if let Some(id) = section.free.pop() { + section.palette[id as usize] = state; + section.local_ids.insert(state, id); + id + } else { + let id = section.palette.len() as u32; + let next_bits = bits_for_palette(section.palette.len() + 1, 4); + if next_bits != section.bits() { + let mut storage = + PackedStorage::new(next_bits, 4096).map_err(|e| invalid(e.to_string()))?; + if let Some(old) = §ion.storage { + for i in 0..4096 { + storage.set(i, old.get(i).unwrap()).unwrap(); + } + } + section.storage = Some(storage); + } + section.palette.push(state); + section.counts.push(0); + section.local_ids.insert(state, id); + id + }; + section + .storage + .as_mut() + .unwrap() + .set(index, id) + .map_err(|e| invalid(e.to_string()))?; + section.counts[old_id as usize] -= 1; + section.counts[id as usize] += 1; + if section.counts[old_id as usize] == 0 { + section.local_ids.remove(&old); + section.free.push(old_id); + } + if section.counts[id as usize] == 4096 { + section.palette = vec![state]; + section.local_ids = local_ids(state); + section.counts = vec![4096]; + section.free.clear(); + section.storage = None; + } + Ok(old) + } + + fn benchmark_registry(states: usize) -> BlockRegistry { + let list: Vec = (0..states) + .map(|i| { + Tag::compound([("id", Tag::String(format!("minecraft:b{i}").as_str().into()))]) + }) + .collect(); + let defaults: BTreeMap<_, _> = (0..states) + .map(|i| { + ( + JavaString::from(format!("minecraft:b{i}").as_str()), + Tag::Int(i as i32), + ) + }) + .collect(); + let tag = Tag::compound([ + ("DataVersion", Tag::Int(crate::DATA_VERSION)), + ("states", Tag::List(list)), + ("defaults", Tag::Compound(defaults)), + ]); + BlockRegistry::from_nbt(&tag).unwrap() + } + + /// The optimized `set`/`get` must agree with the pre-optimization ones on + /// every field, across growth, collapse and reclaimed palette slots. + #[test] + fn set_matches_baseline_under_random_edits() { + let registry = benchmark_registry(64); + for &(distinct, seed) in &[(1u64, 1u64), (2, 2), (16, 3), (17, 4), (24, 5), (64, 6)] { + let mut base = BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + let mut fast = BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + let mut rng = seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + for step in 0..50_000u32 { + if step % 5_000 == 4_999 { + let value = (next() % distinct) as u32; + for index in 0..4096 { + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + } else { + let index = (next() % 4096) as usize; + let value = (next() % distinct) as u32; + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + assert_eq!(base.bits(), fast.bits()); + } + assert_eq!(base.palette, fast.palette); + assert_eq!(base.counts, fast.counts); + assert_eq!(base.free, fast.free); + assert_eq!(base.local_ids, fast.local_ids); + for index in 0..4096 { + assert_eq!( + baseline_get(&base, index).unwrap(), + fast.get(index).unwrap(), + "distinct {distinct} index {index}" + ); + } + assert_eq!(base.to_nbt().unwrap(), fast.to_nbt().unwrap()); + } + } + + /// `set` and `get` against the pre-optimization implementations, on the same + /// edit stream. The result is checked before timing; 51 measured rounds + /// alternate order and report the median and best nanosecond-per-operation. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_section_get_set() { + use std::{hint::black_box, time::Instant}; + const OPS: usize = 50_000; + const ROUNDS: u32 = 51; + let registry = benchmark_registry(32); + let mut rng = 0x1234_5678_9abc_def1u64; + let mut next = || { + rng ^= rng << 13; + rng ^= rng >> 7; + rng ^= rng << 17; + rng + }; + let ops: Vec<(usize, u32)> = (0..OPS) + .map(|_| ((next() % 4096) as usize, (next() % 24) as u32)) + .collect(); + let make = || BlockSection::uniform(BlockStateId(0), ®istry).unwrap(); + + let mut base = make(); + let mut fast = make(); + for &(index, value) in &ops { + assert_eq!( + baseline_set(&mut base, index, BlockStateId(value)).unwrap(), + fast.set(index, BlockStateId(value)).unwrap() + ); + } + assert_eq!(base.bits(), fast.bits()); + assert_eq!(base.palette, fast.palette); + assert_eq!(base.counts, fast.counts); + assert_eq!(base.free, fast.free); + assert_eq!(base.to_nbt().unwrap(), fast.to_nbt().unwrap()); + for i in 0..4096 { + assert_eq!(baseline_get(&base, i).unwrap(), fast.get(i).unwrap()); + } + + let mut times = [Vec::new(), Vec::new()]; + for round in 0..ROUNDS { + for optimized in [round % 2 == 0, round % 2 != 0] { + let mut section = make(); + let started = Instant::now(); + for &(index, value) in &ops { + if optimized { + section + .set(black_box(index), black_box(BlockStateId(value))) + .unwrap(); + } else { + baseline_set( + &mut section, + black_box(index), + black_box(BlockStateId(value)), + ) + .unwrap(); + } + } + black_box(§ion); + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e9 / OPS as f64); + } + } + } + for values in &mut times { + values.sort_by(f64::total_cmp); + } + let median = |v: &[f64]| v[v.len() / 2]; + println!( + "section set median: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + median(×[0]), + median(×[1]), + median(×[0]) / median(×[1]) + ); + println!( + "section set best: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + times[0][0], + times[1][0], + times[0][0] / times[1][0] + ); + + let mut get_times = [Vec::new(), Vec::new()]; + for round in 0..ROUNDS { + for optimized in [round % 2 == 0, round % 2 != 0] { + let started = Instant::now(); + let mut acc = 0u32; + for &(index, _) in &ops { + let state = if optimized { + fast.get(black_box(index)).unwrap() + } else { + baseline_get(&base, black_box(index)).unwrap() + }; + acc ^= state.0; + } + black_box(acc); + if round > 0 { + get_times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e9 / OPS as f64); + } + } + } + for values in &mut get_times { + values.sort_by(f64::total_cmp); + } + println!( + "section get median: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + median(&get_times[0]), + median(&get_times[1]), + median(&get_times[0]) / median(&get_times[1]) + ); + println!( + "section get best: baseline {:.3} ns/op optimized {:.3} ns/op speedup {:.3}x", + get_times[0][0], + get_times[1][0], + get_times[0][0] / get_times[1][0] + ); + } } diff --git a/crates/horizon-world/src/collision.rs b/crates/horizon-world/src/collision.rs index 694264a5e..3d3311646 100644 --- a/crates/horizon-world/src/collision.rs +++ b/crates/horizon-world/src/collision.rs @@ -5,10 +5,10 @@ //! This module covers the cached branch only; uncached states remain explicit. use crate::{ DATA_VERSION, - chunk::{BlockSection, BlockState}, + chunk::BlockSection, compression::invalid, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::geometry::{Axis, VoxelShape}; use std::{collections::HashMap, io}; @@ -35,20 +35,13 @@ impl<'r> CachedCollisionRegistry<'r> { self.registry } pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + Self::from_table(BlockTable::check(tag, registry, "collision")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result { + let (tag, registry) = (table.tag(), table.registry()); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("collision DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing collision state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("collision registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("collision state identities differ")); - } - } let Some(Tag::List(entries)) = tag.get("shapes") else { return Err(invalid("missing collision shapes")); }; diff --git a/crates/horizon-world/src/level/data.rs b/crates/horizon-world/src/level/data.rs index 33d63411a..e0ef0dca1 100644 --- a/crates/horizon-world/src/level/data.rs +++ b/crates/horizon-world/src/level/data.rs @@ -8,8 +8,7 @@ use crate::{ collision::CachedCollisionRegistry, compression::invalid, fluid::{FluidBlockBindings, FluidKind, FluidState}, - nbt::{self, Limits}, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTableFile}, worldgen::tags::TagDefinitions, }; use horizon_core::geometry::{Aabb, Direction, ShapeOp, Vec3, VoxelShape}; @@ -614,45 +613,9 @@ fn set_type(value: &Value, cache: &mut HashMap>) -> Option io::Result { - use crate::{DATA_VERSION, nbt::Tag}; - fn tag(value: &Value) -> io::Result { - Ok(match value { - Value::String(value) => Tag::String(value.as_str().into()), - Value::Number(value) => Tag::Int( - value - .as_i64() - .and_then(|v| i32::try_from(v).ok()) - .ok_or_else(|| fail("invalid registry number"))?, - ), - Value::Array(values) => Tag::List(values.iter().map(tag).collect::>()?), - Value::Object(values) => Tag::Compound( - values - .iter() - .map(|(name, value)| Ok((name.as_str().into(), tag(value)?))) - .collect::>()?, - ), - _ => return Err(fail("unsupported registry value")), - }) - } - let facts = read_json(&root.join("facts.json"))?; - let states = facts["states"] - .as_array() - .ok_or_else(|| fail("missing registry state facts"))?; - BlockRegistry::from_nbt(&Tag::compound([ - ("DataVersion", Tag::Int(DATA_VERSION)), - ( - "states", - Tag::List( - states - .iter() - .map(|state| tag(&state[4])) - .collect::>()?, - ), - ), - ("defaults", tag(&facts["defaults"])?), - ])) + BlockRegistry::from_facts_json(File::open(root.join("facts.json"))?) } pub(super) fn load(registry: &BlockRegistry, root: &Path) -> io::Result { @@ -787,14 +750,8 @@ fn build_with_gameplay( }; // Collision shapes. - let collision_tag = nbt::read_named( - &fs::read(root.join("cached-collision.nbt"))?, - Limits::default(), - ) - .map_err(|e| invalid(e.to_string()))? - .0 - .tag; - let cached = CachedCollisionRegistry::from_nbt(&collision_tag, registry)?; + let collision_file = BlockTableFile::open(&root.join("cached-collision.nbt"), registry)?; + let cached = CachedCollisionRegistry::from_table(collision_file.table("collision")?)?; let mut shapes: Vec = Vec::new(); let mut shape_ids = Vec::with_capacity(table.state_count()); for id in 0..table.state_count() { diff --git a/crates/horizon-world/src/movement_properties.rs b/crates/horizon-world/src/movement_properties.rs index 84cafae1e..9e1dc6236 100644 --- a/crates/horizon-world/src/movement_properties.rs +++ b/crates/horizon-world/src/movement_properties.rs @@ -1,11 +1,10 @@ //! Registry-bound block movement coefficients, identities and reloadable tags. use crate::{ DATA_VERSION, - chunk::BlockState, compression::invalid, movement_support::MovementBlockWorld, nbt::Tag, - registry::{BlockRegistry, BlockStateId}, + registry::{BlockRegistry, BlockStateId, BlockTable}, }; use horizon_core::position::BlockPos; use std::{ @@ -55,20 +54,13 @@ impl<'r> MovementProperties<'r> { } pub fn from_nbt(tag: &Tag, registry: &'r BlockRegistry) -> io::Result { + Self::from_table(BlockTable::check(tag, registry, "movement")?) + } + pub fn from_table(table: BlockTable<'_, 'r>) -> io::Result { + let (tag, registry) = (table.tag(), table.registry()); if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { return Err(invalid("movement properties DataVersion mismatch")); } - let Some(Tag::List(states)) = tag.get("states") else { - return Err(invalid("missing movement state identities")); - }; - if states.len() != registry.len() { - return Err(invalid("movement registry size mismatch")); - } - for (id, state) in states.iter().enumerate() { - if registry.state(BlockStateId(id as u32)) != Some(&BlockState::from_nbt(state)?) { - return Err(invalid("movement state identities differ")); - } - } let Some(Tag::Compound(blocks)) = tag.get("blocks") else { return Err(invalid("missing movement definitions")); }; diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 7e4d76a41..2a8b11591 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -100,11 +100,13 @@ impl Default for Limits { impl Limits { /// The prepared per-state block tables (`cached-collision.nbt`, /// `block-properties.nbt`, ...): trusted files with a row per block - /// state, which content mods' states grow past the default caps. + /// state, which content mods' states grow past the default caps + /// (vanilla's 35,723 states fill about a tenth of these; ATM10's ported + /// mods, 193,762 states, about half). pub fn tables() -> Self { Self { - max_bytes: 1 << 28, - max_nodes: 16_000_000, + max_bytes: 1 << 30, + max_nodes: 128_000_000, max_depth: 512, } } @@ -122,13 +124,20 @@ impl std::fmt::Display for Error { } impl std::error::Error for Error {} -struct Reader<'a> { +/// Hands a streamed list's elements to the caller one at a time (see +/// [`read_named_streaming`]). +type Visit<'s> = &'s mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>; + +struct Reader<'a, 's> { bytes: &'a [u8], offset: usize, limits: Limits, nodes: usize, + /// Lists with this key in the root compound or in a compound directly + /// under it are streamed to the visitor instead of kept. + stream: Option<(&'s str, Visit<'s>)>, } -impl<'a> Reader<'a> { +impl<'a> Reader<'a, '_> { fn error(&self, reason: &'static str) -> Error { Error { offset: self.offset, @@ -264,7 +273,11 @@ impl<'a> Reader<'a> { break; } let name = self.string()?; - let value = self.payload(id, depth + 1)?; + let value = if id == 9 && depth <= 1 && self.streams(&name) { + self.stream_list(depth + 1)? + } else { + self.payload(id, depth + 1)? + }; map.insert(name, value); // Java maps retain the last duplicate key. } Tag::Compound(map) @@ -288,6 +301,82 @@ impl<'a> Reader<'a> { _ => return Err(self.error("unknown tag type")), }) } + fn streams(&self, name: &JavaString) -> bool { + self.stream + .as_ref() + .is_some_and(|(key, _)| name.0.iter().copied().eq(key.encode_utf16())) + } + /// A list's payload handed to the visitor element by element; the tree + /// keeps it empty. Elements the visitor leaves are read and dropped. + fn stream_list(&mut self, depth: usize) -> Result { + if self.nodes >= self.limits.max_nodes { + return Err(self.error("node limit exceeded")); + } + self.nodes += 1; + if depth >= self.limits.max_depth { + return Err(self.error("depth limit exceeded")); + } + let element_id = self.byte()?; + let len = self.count(0)?; + if len > 0 && (element_id == 0 || element_id > 12) { + return Err(self.error("invalid list element type")); + } + if len > self.bytes.len().saturating_sub(self.offset) { + return Err(self.error("truncated list")); + } + let (key, visit) = self.stream.take().expect("streams() checked the visitor"); + let mut elements = ListElements { + reader: self, + element_id, + depth: depth + 1, + len, + left: len, + }; + let rest = visit(&mut elements).and_then(|()| { + while elements.next_element()?.is_some() {} + Ok(()) + }); + self.stream = Some((key, visit)); + rest.map(|()| Tag::List(Vec::new())) + } +} + +/// The elements of a list [`read_named_streaming`] streams, read one at a +/// time. +pub struct ListElements<'r, 'a, 's> { + reader: &'r mut Reader<'a, 's>, + element_id: u8, + depth: usize, + len: usize, + left: usize, +} +impl ListElements<'_, '_, '_> { + /// The list's length, as its header gives it. + pub fn len(&self) -> usize { + self.len + } + pub fn is_empty(&self) -> bool { + self.len == 0 + } + /// The next element, unwrapped as [`read_named`] unwraps mixed-list + /// elements; `None` past the last. + pub fn next_element(&mut self) -> Result, Error> { + if self.left == 0 { + return Ok(None); + } + self.left -= 1; + let mut value = self.reader.payload(self.element_id, self.depth)?; + if let Tag::Compound(map) = &mut value { + if map.len() == 1 && map.contains_key(&JavaString::default()) { + value = map.remove(&JavaString::default()).unwrap(); + } + } + Ok(Some(value)) + } + /// An error at the current position in the input. + pub fn error(&self, reason: &'static str) -> Error { + self.reader.error(reason) + } } /// Read a file root (type, modified-UTF name, payload), returning bytes consumed. @@ -297,6 +386,35 @@ pub fn read_named(bytes: &[u8], limits: Limits) -> Result<(NamedTag, usize), Err offset: 0, limits, nodes: 0, + stream: None, + }; + let id = reader.byte()?; + let name = if id == 0 { + JavaString::default() + } else { + reader.string()? + }; + let tag = reader.payload(id, 0)?; + Ok((NamedTag { name, tag }, reader.offset)) +} + +/// [`read_named`], except that lists keyed `key` in the root compound or in +/// a compound directly under it are not kept: `visit` reads each one's +/// elements as they come, and the tree holds it as an empty list. Per-state +/// tables check hundreds of thousands of state identities this way without +/// holding them as a tree (crate::registry::BlockTableFile). +pub fn read_named_streaming( + bytes: &[u8], + limits: Limits, + key: &str, + visit: &mut dyn FnMut(&mut ListElements<'_, '_, '_>) -> Result<(), Error>, +) -> Result<(NamedTag, usize), Error> { + let mut reader = Reader { + bytes, + offset: 0, + limits, + nodes: 0, + stream: Some((key, visit)), }; let id = reader.byte()?; let name = if id == 0 { @@ -315,6 +433,7 @@ pub fn read_network(bytes: &[u8], limits: Limits) -> Result<(Tag, usize), Error> offset: 0, limits, nodes: 0, + stream: None, }; let id = reader.byte()?; let tag = reader.payload(id, 0)?; @@ -657,6 +776,50 @@ impl Snbt<'_> { mod tests { use super::*; #[test] + fn streamed_lists_reach_the_visitor_and_stay_empty_in_the_tree() { + let list = |n: i32| Tag::List((0..n).map(Tag::Int).collect()); + let root = NamedTag { + name: "".into(), + tag: Tag::compound([ + ("states", list(3)), + ("inner", Tag::compound([("states", list(2))])), + ( + "deep", + Tag::compound([("inner", Tag::compound([("states", list(1))]))]), + ), + ("other", list(4)), + ]), + }; + let bytes = write_named(&root, Limits::default()).unwrap(); + let mut seen = Vec::new(); + let (read, used) = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| { + let mut values = vec![l.len() as i32]; + // Elements left unread are skipped. + if let Some(Tag::Int(v)) = l.next_element()? { + values.push(v); + } + seen.push(values); + Ok(()) + }) + .unwrap(); + assert_eq!(used, bytes.len()); + // Compounds are written in key order: `inner` before `states`. + assert_eq!(seen, [vec![2, 0], vec![3, 0]]); + assert_eq!(read.tag.get("states"), Some(&Tag::List(Vec::new()))); + assert_eq!( + read.tag.get("inner").unwrap().get("states"), + Some(&Tag::List(Vec::new())) + ); + // Only the root and its direct children stream. + assert_eq!(read.tag.get("deep"), root.tag.get("deep")); + assert_eq!(read.tag.get("other"), root.tag.get("other")); + // A visitor's error stops the read. + let failed = read_named_streaming(&bytes, Limits::default(), "states", &mut |l| { + Err(l.error("refused")) + }); + assert_eq!(failed.unwrap_err().reason, "refused"); + } + #[test] fn wire_node_budget_includes_mixed_list_wrappers() { let tag = Tag::List(vec![Tag::Int(1), Tag::Byte(2)]); let limits = Limits { diff --git a/crates/horizon-world/src/registry.rs b/crates/horizon-world/src/registry.rs index 30367e251..9ce9a6814 100644 --- a/crates/horizon-world/src/registry.rs +++ b/crates/horizon-world/src/registry.rs @@ -1,11 +1,13 @@ //! Runtime block-state IDs imported from a version-pinned registry data export. //! This supplies identities and default properties, not block behavior. +mod facts; mod json; use crate::{DATA_VERSION, chunk::BlockState, compression::invalid, nbt::Tag}; pub use json::BlockStateJsonCodec; pub(crate) use json::java_integer; use std::{ - collections::{BTreeMap, BTreeSet}, + collections::{BTreeMap, BTreeSet, HashMap}, + hash::{DefaultHasher, Hash, Hasher}, io, }; @@ -14,9 +16,25 @@ pub struct BlockStateId(pub u32); pub struct BlockRegistry { states: Vec, - ids: BTreeMap, + /// Ids by a hash of their state, checked against `states`: 12 bytes per + /// state instead of a second copy of every name and property map (about + /// 125 MB for a registry of 190,000 states). + ids: HashMap, + /// States whose hash an earlier state already took (none in vanilla). + collided: BTreeMap, defaults: BTreeMap, } +/// The hash [`BlockRegistry`] indexes states by (fixed keys: the same in +/// every process). +fn state_key(state: &BlockState) -> u64 { + let mut hasher = DefaultHasher::new(); + state.name.hash(&mut hasher); + for (key, value) in &state.properties { + key.hash(&mut hasher); + value.hash(&mut hasher); + } + hasher.finish() +} impl BlockRegistry { pub fn from_nbt(tag: &Tag) -> io::Result { if tag.get("DataVersion") != Some(&Tag::Int(DATA_VERSION)) { @@ -28,39 +46,79 @@ impl BlockRegistry { let Some(Tag::Compound(defaults)) = tag.get("defaults") else { return Err(invalid("missing registry defaults")); }; - if entries.is_empty() || entries.len() > i32::MAX as usize { + let states = entries + .iter() + .map(BlockState::from_nbt) + .collect::>()?; + let defaults = defaults + .iter() + .map(|(name, id)| { + let name = name.to_string().map_err(|e| invalid(e.to_string()))?; + let Tag::Int(id) = id else { + return Err(invalid("default state ID is not an int")); + }; + Ok((name, i64::from(*id))) + }) + .collect::>()?; + Self::from_states(states, defaults) + } + + /// The registry of a resources `facts.json` (`{"states": [[..., ..., ..., + /// ..., state], ...], "defaults": {name: id}}`), read as it streams: no + /// JSON or NBT tree of the whole file is built. For a pack of 190,000 + /// states the two trees were several hundred megabytes at startup. + pub fn from_facts_json(reader: impl io::Read) -> io::Result { + Ok(Self::from_facts_json_with_flags(reader)?.0) + } + + /// [`Self::from_facts_json`], with each state's `(air, fluid)` columns. + pub fn from_facts_json_with_flags( + reader: impl io::Read, + ) -> io::Result<(Self, Vec<(bool, bool)>)> { + let facts: facts::Facts = serde_json::from_reader(io::BufReader::new(reader)) + .map_err(|e| invalid(e.to_string()))?; + let flags = facts.states.iter().map(|r| (r.air, r.fluid)).collect(); + let states = facts.states.into_iter().map(|r| r.state).collect(); + Ok((Self::from_states(states, facts.defaults)?, flags)) + } + + fn from_states(states: Vec, defaults: BTreeMap) -> io::Result { + if states.is_empty() || states.len() > i32::MAX as usize { return Err(invalid("invalid registry size")); } let mut result = Self { - states: Vec::with_capacity(entries.len()), - ids: BTreeMap::new(), + states: Vec::with_capacity(states.len()), + ids: HashMap::with_capacity(states.len()), + collided: BTreeMap::new(), defaults: BTreeMap::new(), }; - for (i, entry) in entries.iter().enumerate() { - let state = BlockState::from_nbt(entry)?; - if result - .ids - .insert(state.clone(), BlockStateId(i as u32)) - .is_some() - { + for (i, state) in states.into_iter().enumerate() { + if result.id(&state).is_some() { return Err(invalid("duplicate block registry state")); } + match result.ids.entry(state_key(&state)) { + std::collections::hash_map::Entry::Vacant(slot) => { + slot.insert(i as u32); + } + std::collections::hash_map::Entry::Occupied(_) => { + result + .collided + .insert(state.clone(), BlockStateId(i as u32)); + } + } result.states.push(state); } for (name, id) in defaults { - let name = name.to_string().map_err(|e| invalid(e.to_string()))?; - let Tag::Int(id) = id else { - return Err(invalid("default state ID is not an int")); - }; - if *id < 0 + if id < 0 + || id > i64::from(i32::MAX) || result .states - .get(*id as usize) + .get(id as usize) .is_none_or(|s| s.name != name) { return Err(invalid("invalid default block state ID")); } - result.defaults.insert(name, BlockStateId(*id as u32)); + result.defaults.insert(name, BlockStateId(id as u32)); } let names: BTreeSet<_> = result.states.iter().map(|s| &s.name).collect(); if names.len() != result.defaults.len() @@ -82,7 +140,10 @@ impl BlockRegistry { self.states.get(id.0 as usize) } pub fn id(&self, state: &BlockState) -> Option { - self.ids.get(state).copied() + match self.ids.get(&state_key(state)) { + Some(&id) if self.states[id as usize] == *state => Some(BlockStateId(id)), + _ => self.collided.get(state).copied(), + } } pub fn default_state(&self, name: &str) -> Option { self.defaults.get(name).copied() @@ -105,3 +166,120 @@ impl BlockRegistry { .ok_or_else(|| invalid("invalid block property value")) } } + +/// A per-state table (`occlusion.nbt`, `cached-collision.nbt`, ...) whose +/// `states` list, the identity of every state it describes in id order, has +/// been checked against `registry`. +#[derive(Clone, Copy)] +pub struct BlockTable<'t, 'r> { + tag: &'t Tag, + registry: &'r BlockRegistry, + /// How many levels, from this one down, [`BlockTableFile::read`] checked + /// while reading: their `states` lists are kept empty in the tree. + read_checked: u8, +} +impl<'t, 'r> BlockTable<'t, 'r> { + /// Checks that `tag`'s `states` names the registry's states in id order. + pub fn check(tag: &'t Tag, registry: &'r BlockRegistry, what: &str) -> io::Result { + Self { + tag, + registry, + read_checked: 0, + } + .checked(what) + } + fn checked(self, what: &str) -> io::Result { + let Some(Tag::List(states)) = self.tag.get("states") else { + return Err(invalid(format!("missing {what} state identities"))); + }; + if self.read_checked == 0 { + if states.len() != self.registry.len() { + return Err(invalid(format!("{what} registry size mismatch"))); + } + for (id, state) in states.iter().enumerate() { + if self.registry.state(BlockStateId(id as u32)) + != Some(&BlockState::from_nbt(state)?) + { + return Err(invalid(format!("{what} state identities differ"))); + } + } + } + Ok(self) + } + /// The table nested under `key` (`block-properties.nbt`'s `occlusion`), + /// with its own `states`, checked the same way. + pub fn nested(&self, key: &str, what: &str) -> io::Result { + Self { + tag: self + .tag + .get(key) + .ok_or_else(|| invalid(format!("missing {what}")))?, + registry: self.registry, + read_checked: self.read_checked.saturating_sub(1), + } + .checked(what) + } + pub fn tag(&self) -> &'t Tag { + self.tag + } + pub fn get(&self, key: &str) -> Option<&'t Tag> { + self.tag.get(key) + } + pub fn registry(&self) -> &'r BlockRegistry { + self.registry + } +} + +/// A per-state table read from its file with its state identities checked +/// while reading, so they never exist as a tree: for 190,000 states (a big +/// modpack) that tree took 300-600 MB per table. +pub struct BlockTableFile<'r> { + tag: Tag, + registry: &'r BlockRegistry, +} +impl<'r> BlockTableFile<'r> { + /// [`Self::read`] of the file at `path`. + pub fn open(path: &std::path::Path, registry: &'r BlockRegistry) -> io::Result { + let bytes = std::fs::read(path)?; + Self::read(&bytes, registry).map_err(|e| invalid(format!("{}: {e}", path.display()))) + } + /// Reads `bytes`, checking every `states` list of the root compound and + /// of the compounds directly under it against `registry`. + pub fn read(bytes: &[u8], registry: &'r BlockRegistry) -> io::Result { + let mut visit = |states: &mut crate::nbt::ListElements<'_, '_, '_>| { + if states.len() != registry.len() { + return Err(states.error("table registry size mismatch")); + } + let mut id = 0u32; + while let Some(tag) = states.next_element()? { + let state = + BlockState::from_nbt(&tag).map_err(|_| states.error("invalid table state"))?; + if registry.state(BlockStateId(id)) != Some(&state) { + return Err(states.error("table state identities differ")); + } + id += 1; + } + Ok(()) + }; + let (named, _) = crate::nbt::read_named_streaming( + bytes, + crate::nbt::Limits::tables(), + "states", + &mut visit, + ) + .map_err(|e| invalid(e.to_string()))?; + Ok(Self { + tag: named.tag, + registry, + }) + } + /// The table, checked (`what` names it in errors). + pub fn table(&self, what: &str) -> io::Result> { + BlockTable { + tag: &self.tag, + registry: self.registry, + read_checked: 2, + } + .checked(what) + } +} diff --git a/crates/horizon-world/src/registry/facts.rs b/crates/horizon-world/src/registry/facts.rs new file mode 100644 index 000000000..3371a8283 --- /dev/null +++ b/crates/horizon-world/src/registry/facts.rs @@ -0,0 +1,164 @@ +//! The part of `facts.json` the block registry reads, deserialized as it +//! streams: each row's state (its fifth column) and the defaults. +use crate::chunk::BlockState; +use serde::{ + Deserialize, Deserializer, + de::{self, IgnoredAny, SeqAccess, Visitor}, +}; +use std::{collections::BTreeMap, fmt}; + +#[derive(Deserialize)] +pub(super) struct Facts { + pub states: Vec, + pub defaults: BTreeMap, +} + +/// One `states` row: `[name, air, fluid, description, state, ...]`, keeping +/// the two flags and the state. +pub(super) struct Row { + pub air: bool, + pub fluid: bool, + pub state: BlockState, +} + +impl<'de> Deserialize<'de> for Row { + fn deserialize>(deserializer: D) -> Result { + struct RowVisitor; + impl<'de> Visitor<'de> for RowVisitor { + type Value = Row; + fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str("a registry state row") + } + fn visit_seq>(self, mut seq: A) -> Result { + let length = |i| de::Error::invalid_length(i, &self); + seq.next_element::()?.ok_or_else(|| length(0))?; + let air = seq.next_element::()?.ok_or_else(|| length(1))?; + let fluid = seq.next_element::()?.ok_or_else(|| length(2))?; + seq.next_element::()?.ok_or_else(|| length(3))?; + let state = seq.next_element::()?.ok_or_else(|| length(4))?; + while seq.next_element::()?.is_some() {} + Ok(Row { + air, + fluid, + state: state.0, + }) + } + } + deserializer.deserialize_seq(RowVisitor) + } +} + +/// A state as BlockState::from_nbt reads it: a name, or `{"id", "properties"}`. +struct State(BlockState); + +impl<'de> Deserialize<'de> for State { + fn deserialize>(deserializer: D) -> Result { + #[derive(Deserialize)] + #[serde(untagged)] + enum Shape { + Name(String), + Full { + id: String, + #[serde(default)] + properties: BTreeMap, + }, + } + Ok(State(match Shape::deserialize(deserializer)? { + Shape::Name(name) => BlockState { + name, + properties: BTreeMap::new(), + }, + Shape::Full { id, properties } => BlockState { + name: id, + properties, + }, + })) + } +} + +#[cfg(test)] +mod tests { + use crate::{ + DATA_VERSION, + chunk::BlockState, + nbt::Tag, + registry::{BlockRegistry, BlockStateId}, + }; + use serde_json::Value; + use std::path::Path; + + #[test] + fn reads_states_and_defaults() { + let json = br#"{"defaults": {"minecraft:air": 0, "minecraft:oak_slab": 2}, + "states": [ + ["minecraft:air", true, false, "Block{minecraft:air}", "minecraft:air"], + ["minecraft:oak_slab", false, false, "x", {"id": "minecraft:oak_slab", "properties": {"type": "top"}}, "extra"], + ["minecraft:oak_slab", false, true, "x", {"id": "minecraft:oak_slab", "properties": {"type": "bottom"}}] + ], "other": [1, 2]}"#; + let (registry, flags) = BlockRegistry::from_facts_json_with_flags(&json[..]).unwrap(); + assert_eq!(registry.len(), 3); + assert_eq!(flags, [(true, false), (false, false), (false, true)]); + assert_eq!( + registry.default_state("minecraft:oak_slab"), + Some(BlockStateId(2)) + ); + let top = BlockState { + name: "minecraft:oak_slab".into(), + properties: [("type".into(), "top".into())].into(), + }; + assert_eq!(registry.id(&top), Some(BlockStateId(1))); + // A default naming another block, a short row, a missing default. + for bad in [ + &br#"{"defaults": {"minecraft:air": 1}, "states": [["minecraft:air", true, false, "", "minecraft:air"], ["minecraft:stone", false, false, "", "minecraft:stone"]]}"#[..], + br#"{"defaults": {"minecraft:air": 0}, "states": [["minecraft:air", true, false, ""]]}"#, + br#"{"defaults": {}, "states": [["minecraft:air", true, false, "", "minecraft:air"]]}"#, + ] { + assert!(BlockRegistry::from_facts_json(bad).is_err()); + } + } + + /// The streamed registry is the one the JSON and NBT trees built. + #[test] + fn matches_the_tree_built_registry() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../.local/horizon-client/26.3/facts.json"); + let Ok(bytes) = std::fs::read(&path) else { + eprintln!("skipped: no prepared facts.json"); + return; + }; + fn tag(v: &Value) -> Tag { + match v { + Value::String(s) => Tag::String(s.as_str().into()), + Value::Number(n) => Tag::Int(n.as_i64().unwrap() as i32), + Value::Object(o) => { + Tag::Compound(o.iter().map(|(k, v)| (k.as_str().into(), tag(v))).collect()) + } + _ => unreachable!(), + } + } + let facts: Value = serde_json::from_slice(&bytes).unwrap(); + let rows = facts["states"].as_array().unwrap(); + let tree = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ( + "states", + Tag::List(rows.iter().map(|r| tag(&r[4])).collect()), + ), + ("defaults", tag(&facts["defaults"])), + ])) + .unwrap(); + let (streamed, flags) = BlockRegistry::from_facts_json_with_flags(&bytes[..]).unwrap(); + assert_eq!(streamed.len(), tree.len()); + for (i, row) in rows.iter().enumerate() { + let id = BlockStateId(i as u32); + assert_eq!(streamed.state(id), tree.state(id)); + assert_eq!( + flags[i], + (row[1].as_bool().unwrap(), row[2].as_bool().unwrap()) + ); + } + for name in facts["defaults"].as_object().unwrap().keys() { + assert_eq!(streamed.default_state(name), tree.default_state(name)); + } + } +} diff --git a/crates/horizon-world/src/worldgen/feature_catalog.rs b/crates/horizon-world/src/worldgen/feature_catalog.rs index 0b8d56cc4..4db251114 100644 --- a/crates/horizon-world/src/worldgen/feature_catalog.rs +++ b/crates/horizon-world/src/worldgen/feature_catalog.rs @@ -192,7 +192,7 @@ impl FeatureCatalog { if names.is_empty() { return Ok(serde_json::to_string(&format!("#{tag}"))?); } - if names.len() > 8192 { + if names.len() > super::state_provider::MAX_TAG_BLOCKS { return Err(DecodeError::Field("placed-feature tag size")); } names diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 12dfc10d9..7b73d35a8 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1764,6 +1764,18 @@ impl OverworldGenerator { ) -> Result { Self::build(data, seed, preset, dimension, true) } + /// A dimension of a world preset, with or without structures (the + /// world's `generate_structures`: without, no starts, terrain adaptation, + /// structure pieces or structure locating). + pub fn for_world( + data: Arc, + seed: i64, + preset: &str, + dimension: &str, + structures: bool, + ) -> Result { + Self::build(data, seed, preset, dimension, structures) + } fn build( data: Arc, seed: i64, diff --git a/crates/horizon-world/src/worldgen/generator_blocks.rs b/crates/horizon-world/src/worldgen/generator_blocks.rs index dc7db7d20..ed1182f36 100644 --- a/crates/horizon-world/src/worldgen/generator_blocks.rs +++ b/crates/horizon-world/src/worldgen/generator_blocks.rs @@ -8,8 +8,7 @@ use crate::{ block_support::BlockSupportRegistry, block_survival::{BlockSurvivalRegistry, SurvivalDefinitions, SurvivalRule}, collision::CachedCollisionRegistry, - nbt::{self, Limits, Tag}, - registry::BlockRegistry, + registry::{BlockRegistry, BlockTableFile}, }; use serde_json::Value; use std::{ @@ -102,24 +101,21 @@ impl BlockBehavior { if !dir.join("block-properties.nbt").exists() { return Ok(None); } - let read = |name: &str| -> Result { - Ok( - nbt::read_named(&fs::read(dir.join(name))?, Limits::tables()) - .map_err(|e| resource(format!("{name}: {e:?}")))? - .0 - .tag, - ) + let read = |name: &str| -> Result, GeneratorError> { + BlockTableFile::open(&dir.join(name), registry) + .map_err(|e| resource(format!("{name}: {e}"))) }; let json = |name: &str| -> Result { Ok(serde_json::from_str(&fs::read_to_string(dir.join(name))?)?) }; let collisions = - CachedCollisionRegistry::from_nbt(&read("cached-collision.nbt")?, registry)?; - let properties = - BlockPropertiesRegistry::from_nbt(&read("block-properties.nbt")?, &collisions)?; - let support = Arc::new(BlockSupportRegistry::from_nbt( - &read("cached-support.nbt")?, - registry, + CachedCollisionRegistry::from_table(read("cached-collision.nbt")?.table("collision")?)?; + let properties = BlockPropertiesRegistry::from_table( + read("block-properties.nbt")?.table("block property")?, + &collisions, + )?; + let support = Arc::new(BlockSupportRegistry::from_table( + read("cached-support.nbt")?.table("support")?, )?); let collision = Arc::new(BlockCollisionRegistry::new(Arc::new(collisions))?); let rules = json("survival-rules.json")? diff --git a/crates/horizon-world/src/worldgen/material_condition.rs b/crates/horizon-world/src/worldgen/material_condition.rs index 30eb26ec8..6433b09a4 100644 --- a/crates/horizon-world/src/worldgen/material_condition.rs +++ b/crates/horizon-world/src/worldgen/material_condition.rs @@ -300,6 +300,14 @@ enum Kind { Not(Box>), } impl Compiled { + fn constant_result(&self) -> Option { + match &self.kind { + Kind::Constant(value) => Some(*value), + Kind::Not(child) => child.constant_result().map(|value| !value), + _ => None, + } + } + fn compile( condition: MaterialCondition, root: &R::Positional, diff --git a/crates/horizon-world/src/worldgen/material_condition/density.rs b/crates/horizon-world/src/worldgen/material_condition/density.rs index 5c98c75e0..b10ea815a 100644 --- a/crates/horizon-world/src/worldgen/material_condition/density.rs +++ b/crates/horizon-world/src/worldgen/material_condition/density.rs @@ -15,6 +15,8 @@ pub struct MaterialDensitySources { surface: S, expected: DensityVolume, densities: Vec, + /// Eagerly sampled volumes, shared by bindings of the same density root. + buffers: Vec>, retained_samples: usize, plane: DensityVolume, sampler: Arc, @@ -23,7 +25,7 @@ pub struct MaterialDensitySources { } struct BoundDensity { sampler: Arc, - buffer: Option>, + buffer: Option, } impl MaterialDensitySources { pub fn sampler_context_mut(&mut self) -> &mut SamplerContext { @@ -50,6 +52,7 @@ impl MaterialDensitySources { surface, expected, densities: Vec::new(), + buffers: Vec::new(), retained_samples: 0, plane, sampler, @@ -71,13 +74,23 @@ impl MaterialSurfaceQueries for MaterialDensitySource { return Err(DecodeError::Field("material density storage bound")); } - let buffer = if eager { - let mut buffer = vec![0.0; self.expected.size()]; - sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; - self.retained_samples += buffer.len(); - Some(buffer) - } else { - None + let shared = self + .densities + .iter() + .find(|bound| bound.buffer.is_some() && Arc::ptr_eq(&bound.sampler, &sampler)) + .and_then(|bound| bound.buffer); + let buffer = match (eager, shared) { + (false, _) => None, + // Sampling a root over the same volume and context is deterministic, + // so a second binding (iron and copper veins' richness) reuses it. + (true, Some(buffer)) => Some(buffer), + (true, None) => { + let mut buffer = vec![0.0; self.expected.size()]; + sampler.sample_volume(&mut self.context, &mut buffer, self.expected)?; + self.retained_samples += buffer.len(); + self.buffers.push(buffer); + Some(self.buffers.len() - 1) + } }; let index = self.densities.len(); self.densities.push(BoundDensity { sampler, buffer }); @@ -89,9 +102,9 @@ impl MaterialSurfaceQueries for MaterialDensitySource .get(index) .ok_or(MaterialRuleError::MissingDensityProvider)?; let position = [position.x, position.y, position.z]; - if let Some(buffer) = &source.buffer { - if let Some(index) = self.expected.index_of_block(position) { - return Ok(buffer[index]); + if let Some(buffer) = source.buffer { + if let Some(index) = block_index(self.expected, position) { + return Ok(self.buffers[buffer][index]); } } Ok(source.sampler.sample_value(&mut self.context, position)?) @@ -145,3 +158,121 @@ impl MaterialSurfaceQueries for MaterialDensitySource self.surface.band(position) } } + +/// `DensityVolume::index_of_block` without its per-axis divisions for the +/// unit-step volumes the material stage samples (one or two lookups per block). +#[inline] +fn block_index(volume: DensityVolume, position: [i32; 3]) -> Option { + if volume.steps() != [1; 3] { + return volume.index_of_block(position); + } + let [mx, my, mz] = volume.minimum(); + let [sx, sy, sz] = volume.sizes(); + let x = position[0].wrapping_sub(mx) as u32 as usize; + let y = position[1].wrapping_sub(my) as u32 as usize; + let z = position[2].wrapping_sub(mz) as u32 as usize; + (x < sx && y < sy && z < sz).then(|| y + (x + z * sx) * sy) +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::density::SampleError; + use std::sync::atomic::{AtomicUsize, Ordering}; + + struct Surface; + impl MaterialSurfaceQueries for Surface { + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 0 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0.0 + } + } + /// Position-dependent values; counts bulk samples. + #[derive(Debug, Default)] + struct Counted(AtomicUsize); + impl DensitySampler for Counted { + fn sample_value(&self, _: &mut SamplerContext, p: [i32; 3]) -> Result { + Ok((p[0] * 10_000 + p[1] * 100 + p[2]) as f32) + } + fn sample_volume( + &self, + context: &mut SamplerContext, + buffer: &mut [f32], + volume: DensityVolume, + ) -> Result<(), SampleError> { + self.0.fetch_add(1, Ordering::Relaxed); + for z in 0..volume.sizes()[2] { + for x in 0..volume.sizes()[0] { + for y in 0..volume.sizes()[1] { + let [mx, my, mz] = volume.minimum(); + let p = [mx + x as i32, my + y as i32, mz + z as i32]; + buffer[volume.index([x, y, z]).unwrap()] = self.sample_value(context, p)?; + } + } + } + Ok(()) + } + } + fn sources() -> MaterialDensitySources { + let volume = DensityVolume::new([16, 24, 16], [32, -64, -16], [1; 3]).unwrap(); + MaterialDensitySources::new( + Surface, + volume, + Arc::new(Counted::default()), + SamplerContext::default(), + ) + .unwrap() + } + + #[test] + fn eager_bindings_of_one_root_share_a_single_sample() { + let mut sources = sources(); + let shared = Arc::new(Counted::default()); + let other = Arc::new(Counted::default()); + let a = sources.bind_density(shared.clone(), true).unwrap(); + let lazy = sources.bind_density(shared.clone(), false).unwrap(); + let b = sources.bind_density(shared.clone(), true).unwrap(); + let c = sources.bind_density(other.clone(), true).unwrap(); + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + assert_eq!(other.0.load(Ordering::Relaxed), 1); + assert_eq!([a, lazy, b, c], [0, 1, 2, 3]); + for p in [[32, -64, -16], [47, -41, -1], [40, -50, -9], [48, 0, 0]] { + let position = BlockPos::new(p[0], p[1], p[2]); + let expected = (p[0] * 10_000 + p[1] * 100 + p[2]) as f32; + for index in [a, lazy, b, c] { + assert_eq!(sources.density(index, position).unwrap(), expected); + } + } + assert_eq!(shared.0.load(Ordering::Relaxed), 1); + } + + #[test] + fn block_index_matches_index_of_block() { + let unit = DensityVolume::new([16, 24, 16], [i32::MAX - 7, -64, -16], [1; 3]).unwrap(); + let strided = DensityVolume::new([5, 3, 5], [-8, -64, 0], [4, 8, 4]).unwrap(); + for volume in [unit, strided] { + let [mx, my, mz] = volume.minimum(); + for dx in [-1, 0, 1, 4, 7, 8, 15, 16, 17, 20] { + for dy in [-9, -1, 0, 8, 16, 23, 24] { + for dz in [-1, 0, 3, 15, 16, 20] { + let p = [ + mx.wrapping_add(dx), + my.wrapping_add(dy), + mz.wrapping_add(dz), + ]; + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } + for p in [ + [i32::MIN, 0, 0], + [i32::MAX, i32::MAX, i32::MAX], + [0, i32::MIN, 0], + ] { + assert_eq!(block_index(volume, p), volume.index_of_block(p), "{p:?}"); + } + } + } +} diff --git a/crates/horizon-world/src/worldgen/material_condition/rule.rs b/crates/horizon-world/src/worldgen/material_condition/rule.rs index 9dfc2ff1e..cf4fc8547 100644 --- a/crates/horizon-world/src/worldgen/material_condition/rule.rs +++ b/crates/horizon-world/src/worldgen/material_condition/rule.rs @@ -70,6 +70,7 @@ impl From for MaterialRuleError { } pub(super) enum CompiledRule { + Empty, Block(BlockStateId), OreVein { blocks: [BlockStateId; 3], @@ -127,7 +128,12 @@ impl CompiledRule { // whether the predicate will match any subsequent position. let condition = Compiled::compile(if_true, root, context, depth + 1)?; let rule = Box::new(Self::compile(*then_run, root, context, depth + 1, nodes)?); - Self::Condition { condition, rule } + // Compile both sides first: binding and errors must retain their order. + match condition.constant_result() { + Some(false) => Self::Empty, + Some(true) => *rule, + None => Self::Condition { condition, rule }, + } } MaterialRule::Sequence(mut children) => { if children.len() == 1 { @@ -135,9 +141,16 @@ impl CompiledRule { } let mut result = Vec::with_capacity(children.len()); for child in children { - result.push(Self::compile(child, root, context, depth + 1, nodes)?); + let child = Self::compile(child, root, context, depth + 1, nodes)?; + if !matches!(child, Self::Empty) { + result.push(child); + } + } + match result.len() { + 0 => Self::Empty, + 1 => result.pop().unwrap(), + _ => Self::Sequence(result), } - Self::Sequence(result) } }) } @@ -147,6 +160,7 @@ impl CompiledRule { context: &mut Context, ) -> Result, MaterialRuleError> { match self { + Self::Empty => Ok(None), Self::Block(block) => Ok(Some(*block)), Self::OreVein { blocks, diff --git a/crates/horizon-world/src/worldgen/state_provider.rs b/crates/horizon-world/src/worldgen/state_provider.rs index 37e9c866b..098decdf1 100644 --- a/crates/horizon-world/src/worldgen/state_provider.rs +++ b/crates/horizon-world/src/worldgen/state_provider.rs @@ -93,7 +93,7 @@ impl<'r> StateProviderBindings<'r> { } let mut bound_tags = BTreeMap::new(); for (name, entries) in tags { - if entries.len() > 8192 { + if entries.len() > MAX_TAG_BLOCKS { return Err(DecodeError::Field("provider tag size")); } let values = entries @@ -558,6 +558,11 @@ impl BlockStateProvider { } } +/// Blocks a bound block tag may list (8,192 before content mods, vanilla's +/// tags fit well within it): content mods' blocks join the shared tags +/// (`mineable/pickaxe` takes every stone block of a pack). +pub(crate) const MAX_TAG_BLOCKS: usize = 1 << 20; + /// Bind the pinned registry's full-axis/full-facing/horizontal-facing property /// families. A five-way facing or two-axis property is a different property and /// is intentionally left unchanged. Unrelated properties retain their values. diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index f15c37dc2..361b2c1d0 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -14,6 +14,7 @@ pub mod processor; pub mod ruined_portal; pub mod simple; pub mod start; +pub mod start_checks; pub mod stronghold; pub mod template; pub mod temple; diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index 1b443eba5..a66f27509 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -55,6 +55,8 @@ pub struct JigsawDef { aliases: Vec, padding: [i32; 2], waterlogging: bool, + /// A carried mod's start rules (`"horizon:start_checks"`). + checks: super::start_checks::StartChecks, } #[derive(Debug)] pub enum StructureKind { @@ -129,6 +131,12 @@ pub struct StructureSet { frequency: f32, reduction: Reduction, exclusion: Option<(String, i32)>, + /// A carried mod's placement rules: no start nearer the world origin + /// than this many blocks (`"horizon:min_distance_from_world_origin"`), + /// and none within `chunk_count` chunks of any of several sets + /// (`"horizon:exclusion_zone"`: `other_sets`, `chunk_count`). + min_distance: Option, + avoid: Option<(Vec, i32)>, } fn heightmap(name: &str) -> Option { @@ -193,6 +201,7 @@ impl StructureRegistry { aliases: v["pool_aliases"].as_array().cloned().unwrap_or_default(), padding: pair(v.get("dimension_padding"), "bottom", "top", 0), waterlogging: v["liquid_settings"].as_str() != Some("ignore_waterlogging"), + checks: super::start_checks::StartChecks::decode(v.get("horizon:start_checks")), }), "minecraft:buried_treasure" => StructureKind::BuriedTreasure, "minecraft:igloo" => StructureKind::Igloo, @@ -291,6 +300,20 @@ impl StructureRegistry { z["chunk_count"].as_i64().unwrap_or(0) as i32, ) }), + min_distance: p + .get("horizon:min_distance_from_world_origin") + .and_then(Value::as_i64), + avoid: p.get("horizon:exclusion_zone").map(|z| { + ( + z["other_sets"] + .as_array() + .into_iter() + .flatten() + .filter_map(|s| Some(s.as_str()?.to_owned())) + .collect(), + z["chunk_count"].as_i64().unwrap_or(0) as i32, + ) + }), }); } Ok(Self { @@ -397,26 +420,47 @@ impl StructureRegistry { if !placed { return false; } + // AdvancedRandomSpread.isPlacementChunk, in blocks from the chunk's corner. + if let Some(d) = set.min_distance { + let (bx, bz) = (i64::from(x) * 16, i64::from(z) * 16); + if bx * bx + bz * bz < d * d { + return false; + } + } + if let Some((others, range)) = &set.avoid { + if others + .iter() + .any(|other| self.has_start_in_range(other, seed, x, z, *range, rings)) + { + return false; + } + } if set.frequency < 1. && !reduce(set.reduction, seed, set.salt, x, z, set.frequency) { return false; } match &set.exclusion { - Some((other, range)) => { - let Some(other) = self.sets.iter().find(|s| s.name == *other) else { - return true; - }; - for tx in x - range..=x + range { - for tz in z - range..=z + range { - if self.is_structure_chunk(other, seed, tx, tz, rings) { - return false; - } - } - } - true - } + Some((other, range)) => !self.has_start_in_range(other, seed, x, z, *range, rings), None => true, } } + /// ChunkGeneratorStructureState.hasStructureChunkInRange: whether set + /// `other` places a structure within `range` chunks of (`x`, `z`). + fn has_start_in_range( + &self, + other: &str, + seed: i64, + x: i32, + z: i32, + range: i32, + rings: &Rings, + ) -> bool { + let Some(other) = self.sets.iter().find(|s| s.name == other) else { + return false; + }; + (x - range..=x + range).any(|tx| { + (z - range..=z + range).any(|tz| self.is_structure_chunk(other, seed, tx, tz, rings)) + }) + } } impl StructureSet { /// The random spread's spacing in chunks (`None` for rings). @@ -606,6 +650,12 @@ fn try_generate( .start_height .sample(&mut random, context.generation()) .ok()?; + if !jigsaw + .checks + .pass(context, &def.biomes, chunk, height, jigsaw.project_to) + { + return None; + } let start = [chunk.x * 16, height, chunk.z * 16]; let aliases = resolve_aliases(&jigsaw.aliases, start, seed); let config = JigsawConfig { diff --git a/crates/horizon-world/src/worldgen/structure/start_checks.rs b/crates/horizon-world/src/worldgen/structure/start_checks.rs new file mode 100644 index 000000000..45b991531 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/start_checks.rs @@ -0,0 +1,277 @@ +//! Start rules a carried structure mod adds on top of vanilla's jigsaw. +//! +//! Repurposed Structures and Moog's Structure Lib give their jigsaw +//! structures checks that run before the pieces are laid out: every biome +//! in a radius must be one the structure allows, the start column may not +//! end in liquid, and the terrain in a radius must lie within a height range. +//! Carry (`horizon-port-pack`) maps those structures to `minecraft:jigsaw` +//! and writes the checks under `"horizon:start_checks"`; vanilla data never +//! has the key, so vanilla structures are unchanged. +//! +//! ```json +//! "horizon:start_checks": { +//! "biome_radius": 2, // chunks; every noise biome must be allowed +//! "liquid": "top", // "top": the column's highest block; "lowest": the block above min_y +//! "terrain_radius": 1, // chunks, with terrain_range and/or min_y, max_y +//! "terrain_range": 15, +//! "min_y": 60, +//! "max_y": 200 +//! } +//! ``` +use crate::{heightmap::HeightmapType, worldgen::biome::BiomeId}; +use horizon_core::position::ChunkPos; +use serde_json::Value; +use std::collections::BTreeSet; + +/// Which block of the start column must not be a liquid. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LiquidCheck { + /// The highest non-air block of the noise column (Moog's). + Top, + /// The block above the column's bottom (Repurposed Structures: its loop + /// keeps the last block it reads, not the first solid one). + Lowest, +} + +/// The checks of one structure; all empty for vanilla's. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct StartChecks { + biome_radius: Option, + liquid: Option, + terrain_radius: Option, + terrain_range: Option, + min_y: Option, + max_y: Option, +} + +/// The column and biome queries the checks need. +pub trait CheckQueries { + /// ChunkGenerator.getFirstFreeHeight. + fn first_free_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32; + /// The noise column at (`x`, `z`) as (not air, blocks motion) per block + /// from the noise's bottom up: in a noise column a block that is not air + /// and does not block motion is a liquid. + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec, Vec); + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId; +} + +impl CheckQueries for T { + fn first_free_height(&mut self, x: i32, z: i32, kind: HeightmapType) -> i32 { + self.base_height(x, z, kind) + } + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec, Vec) { + let mut columns = self.base_columns( + x, + z, + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg], + ); + let solid = columns.pop().unwrap_or_default(); + (columns.pop().unwrap_or_default(), solid) + } + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + super::start::StartContext::noise_biome(self, quart) + } +} + +impl StartChecks { + /// `"horizon:start_checks"` of a structure, or none. + pub fn decode(value: Option<&Value>) -> Self { + let Some(v) = value else { + return Self::default(); + }; + let int = |k: &str| v.get(k).and_then(Value::as_i64).map(|n| n as i32); + Self { + biome_radius: int("biome_radius"), + liquid: match v.get("liquid").and_then(Value::as_str) { + Some("top") => Some(LiquidCheck::Top), + Some("lowest") => Some(LiquidCheck::Lowest), + _ => None, + }, + terrain_radius: int("terrain_radius"), + terrain_range: int("terrain_range"), + min_y: int("min_y"), + max_y: int("max_y"), + } + } + + /// GenericJigsawStructure.extraSpawningChecks: whether the structure may + /// start in `chunk` at `y` (the sampled start height). + pub fn pass( + &self, + queries: &mut impl CheckQueries, + biomes: &BTreeSet, + chunk: ChunkPos, + y: i32, + project_to: Option, + ) -> bool { + let (x0, z0) = (chunk.x * 16, chunk.z * 16); + if let Some(radius) = self.biome_radius { + let mut section_y = y; + if let Some(kind) = project_to { + section_y += queries.first_free_height(x0 + 7, z0 + 7, kind) - 1; + } + for cx in chunk.x - radius..=chunk.x + radius { + for cz in chunk.z - radius..=chunk.z + radius { + if !biomes.contains(&queries.noise_biome([cx << 2, section_y >> 2, cz << 2])) { + return false; + } + } + } + } + if let Some(check) = self.liquid { + let (filled, solid) = queries.liquid_column(x0 + 7, z0 + 7); + // From the top down to the block above the bottom, as the mods loop. + let index = match check { + LiquidCheck::Top => (1..filled.len()).rev().find(|&i| filled[i]), + LiquidCheck::Lowest => Some(1).filter(|&i| i < filled.len()), + }; + if index.is_some_and(|i| filled[i] && !solid[i]) { + return false; + } + } + if let Some(radius) = self + .terrain_radius + .filter(|_| self.terrain_range.is_some() || self.min_y.is_some()) + { + let kind = project_to.unwrap_or(HeightmapType::WorldSurfaceWg); + let (mut highest, mut lowest) = (i32::MIN, i32::MAX); + for cx in chunk.x - radius..=chunk.x + radius { + for cz in chunk.z - radius..=chunk.z + radius { + let height = queries.first_free_height((cx << 4) + 7, (cz << 4) + 7, kind); + highest = highest.max(height); + lowest = lowest.min(height); + // Both bounds test the lowest height so far, as the mods do. + if self.min_y.is_some_and(|m| lowest < m) + || self.max_y.is_some_and(|m| lowest > m) + { + return false; + } + } + } + if self + .terrain_range + .is_some_and(|range| highest - lowest > range) + { + return false; + } + } + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + use std::collections::BTreeMap; + + /// Heights per (x, z), a liquid column, one biome per quart column. + #[derive(Default)] + struct Fake { + heights: BTreeMap<(i32, i32), i32>, + column: Vec, + biomes: BTreeMap<(i32, i32), u32>, + asked: Vec<[i32; 3]>, + } + impl CheckQueries for Fake { + fn first_free_height(&mut self, x: i32, z: i32, _: HeightmapType) -> i32 { + self.heights.get(&(x, z)).copied().unwrap_or(64) + } + fn liquid_column(&mut self, _: i32, _: i32) -> (Vec, Vec) { + // '.' air, '#' stone, '~' water, from the bottom up. + ( + self.column.iter().map(|&c| c != '.').collect(), + self.column.iter().map(|&c| c == '#').collect(), + ) + } + fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + self.asked.push(quart); + BiomeId(self.biomes.get(&(quart[0], quart[2])).copied().unwrap_or(1)) + } + } + fn checks(v: Value) -> StartChecks { + StartChecks::decode(Some(&v)) + } + const CHUNK: ChunkPos = ChunkPos { x: 2, z: -1 }; + + #[test] + fn vanilla_structures_pass_everything() { + let mut fake = Fake { + column: "#~~.".chars().collect(), + ..Fake::default() + }; + let none = StartChecks::decode(None); + assert_eq!(none, StartChecks::default()); + assert!(none.pass(&mut fake, &BTreeSet::new(), CHUNK, 0, None)); + assert!(fake.asked.is_empty()); + } + + #[test] + fn every_biome_in_the_radius_must_be_allowed() { + let allowed = BTreeSet::from([BiomeId(1)]); + let mut fake = Fake::default(); + fake.heights.insert((39, -9), 70); + let c = checks(json!({"biome_radius": 1})); + assert!(c.pass( + &mut fake, + &allowed, + CHUNK, + 10, + Some(HeightmapType::WorldSurfaceWg) + )); + // Section y: start height plus the projected height minus one, in quarts. + assert_eq!(fake.asked.len(), 9); + assert!(fake.asked.iter().all(|q| q[1] == (10 + 70 - 1) >> 2)); + assert_eq!(fake.asked[0], [4, 19, -8]); + fake.biomes.insert((12, 0), 2); // chunk (3, 0), the radius' corner + assert!(!c.pass(&mut fake, &allowed, CHUNK, 10, None)); + } + + #[test] + fn liquid_checks_read_the_mods_block() { + let top = checks(json!({"liquid": "top"})); + let lowest = checks(json!({"liquid": "lowest"})); + let none = BTreeSet::new(); + let mut ocean = Fake { + column: "##~~~..".chars().collect(), + ..Fake::default() + }; + assert!(!top.pass(&mut ocean, &none, CHUNK, 0, None)); + assert!(lowest.pass(&mut ocean, &none, CHUNK, 0, None)); + let mut land = Fake { + column: "#~###..".chars().collect(), + ..Fake::default() + }; + assert!(top.pass(&mut land, &none, CHUNK, 0, None)); + assert!(!lowest.pass(&mut land, &none, CHUNK, 0, None)); + // The bottom block itself is never read; an empty column passes. + let mut empty = Fake { + column: "~....".chars().collect(), + ..Fake::default() + }; + assert!(top.pass(&mut empty, &none, CHUNK, 0, None)); + } + + #[test] + fn terrain_must_lie_within_its_range() { + let none = BTreeSet::new(); + let mut fake = Fake::default(); + // Chunk centres around (2, -1): x 23, 39, 55; z -25, -9, 7. + fake.heights.insert((23, -25), 60); + fake.heights.insert((55, 7), 75); + let range = |r: i32| checks(json!({"terrain_radius": 1, "terrain_range": r})); + assert!(range(15).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!range(14).pass(&mut fake, &none, CHUNK, 0, None)); + // The radius alone, or with only max_y, checks nothing. + assert!( + checks(json!({"terrain_radius": 1, "max_y": 0})).pass(&mut fake, &none, CHUNK, 0, None) + ); + let bounds = + |min: i32, max: i32| checks(json!({"terrain_radius": 1, "min_y": min, "max_y": max})); + assert!(bounds(60, 64).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!bounds(61, 100).pass(&mut fake, &none, CHUNK, 0, None)); + // max_y is compared with the lowest height so far: 75 never fails it. + assert!(bounds(0, 64).pass(&mut fake, &none, CHUNK, 0, None)); + assert!(!bounds(0, 59).pass(&mut fake, &none, CHUNK, 0, None)); + } +} diff --git a/crates/horizon-world/tests/collision_data.rs b/crates/horizon-world/tests/collision_data.rs index 3738edf1a..85b41d98e 100644 --- a/crates/horizon-world/tests/collision_data.rs +++ b/crates/horizon-world/tests/collision_data.rs @@ -267,3 +267,75 @@ fn registry_scan_binding_requires_complete_canonical_metadata() { ); } } + +/// A table read from its bytes checks its state identities while reading and +/// keeps none of them, yet loads the same shapes as the tree; a nested table +/// (`block-properties.nbt`'s `occlusion`) is checked the same way. +#[test] +fn streamed_tables_check_states_while_reading() { + use horizon_world::{ + nbt::{self, Limits, NamedTag}, + registry::{BlockTable, BlockTableFile}, + }; + let (registry_tag, collision_tag) = fixture(); + let registry = BlockRegistry::from_nbt(®istry_tag).unwrap(); + let bytes = |tag: &Tag| { + let root = NamedTag { + name: "".into(), + tag: tag.clone(), + }; + nbt::write_named(&root, Limits::tables()).unwrap() + }; + let file = BlockTableFile::read(&bytes(&collision_tag), ®istry).unwrap(); + let table = file.table("collision").unwrap(); + assert_eq!(table.get("states"), Some(&Tag::List(Vec::new()))); + let streamed = CachedCollisionRegistry::from_table(table).unwrap(); + let tree = CachedCollisionRegistry::from_nbt(&collision_tag, ®istry).unwrap(); + for id in 0..3 { + let id = BlockStateId(id); + assert_eq!( + streamed.cached_shape(id).unwrap().map(|s| s.boxes()), + tree.cached_shape(id).unwrap().map(|s| s.boxes()) + ); + } + + let mut outer = Tag::compound([("occlusion", collision_tag.clone())]); + let Tag::Compound(map) = &mut outer else { + unreachable!() + }; + map.insert( + "states".into(), + collision_tag.get("states").unwrap().clone(), + ); + let file = BlockTableFile::read(&bytes(&outer), ®istry).unwrap(); + let nested = file + .table("outer") + .unwrap() + .nested("occlusion", "occlusion") + .unwrap(); + assert_eq!(nested.get("states"), Some(&Tag::List(Vec::new()))); + CachedCollisionRegistry::from_table(nested).unwrap(); + // Checked only as a tree, an emptied list is refused. + assert!(BlockTable::check(nested.tag(), ®istry, "occlusion").is_err()); + + // Other states, a different count or no states at all are refused. + let with_states = |edit: &dyn Fn(&mut Vec)| { + let mut tag = collision_tag.clone(); + let Some(Tag::List(states)) = tag.get_mut("states") else { + unreachable!() + }; + edit(states); + tag + }; + let swapped = with_states(&|s| s.swap(1, 2)); + assert!(BlockTableFile::read(&bytes(&swapped), ®istry).is_err()); + let short = with_states(&|s| drop(s.pop())); + assert!(BlockTableFile::read(&bytes(&short), ®istry).is_err()); + let mut swapped = swapped; + let Tag::Compound(map) = &mut swapped else { + unreachable!() + }; + map.remove(&"states".into()); + let file = BlockTableFile::read(&bytes(&swapped), ®istry).unwrap(); + assert!(file.table("collision").is_err()); +} diff --git a/crates/horizon-world/tests/material_rule_specialization.rs b/crates/horizon-world/tests/material_rule_specialization.rs new file mode 100644 index 000000000..e953e908e --- /dev/null +++ b/crates/horizon-world/tests/material_rule_specialization.rs @@ -0,0 +1,172 @@ +use horizon_core::{ + density::{ConstantSampler, DensitySampler}, + position::BlockPos, + random::{RandomSource, XoroshiroRandom}, +}; +use horizon_world::{ + registry::BlockStateId, + worldgen::{ + DecodeError, + anchor::WorldGenerationContext, + material_condition::{ + MaterialCondition, MaterialConditions, MaterialRule, MaterialRuleError, + MaterialSurfaceQueries, + }, + }, +}; +use std::{collections::BTreeSet, sync::Arc}; + +#[derive(Default)] +struct Queries { + bindings: Vec, + temperatures: usize, + biomes: usize, + fail_binding: bool, + fail_temperature: bool, +} +impl MaterialSurfaceQueries for Queries { + fn possible_biomes(&self) -> Option> { + Some(BTreeSet::from(["minecraft:plains".into()])) + } + fn surface_depth(&mut self, _: i32, _: i32) -> i32 { + 1 + } + fn surface_secondary(&mut self, _: i32, _: i32) -> f64 { + 0. + } + fn bind_density( + &mut self, + _: Arc, + eager: bool, + ) -> Result { + self.bindings.push(eager); + if self.fail_binding { + return Err(DecodeError::Field("test binding failure")); + } + Ok(self.bindings.len() - 1) + } + fn biome(&mut self, _: BlockPos) -> Result>, MaterialRuleError> { + self.biomes += 1; + Ok(Some(Arc::from("minecraft:plains"))) + } + fn cold_enough_to_snow( + &mut self, + _: &str, + _: BlockPos, + _: i32, + ) -> Result { + self.temperatures += 1; + if self.fail_temperature { + Err(MaterialRuleError::BiomeQueryFailed) + } else { + Ok(true) + } + } +} +fn worker(surface: Queries) -> MaterialConditions { + MaterialConditions::new( + WorldGenerationContext::new(-64, 384, 63), + XoroshiroRandom::new(7).fork_positional(), + surface, + ) +} +fn condition(if_true: MaterialCondition, then_run: MaterialRule) -> MaterialRule { + MaterialRule::Condition { + if_true, + then_run: Box::new(then_run), + } +} +fn biome(name: &str) -> MaterialCondition { + MaterialCondition::Biome(vec![name.into()]) +} +fn ore() -> MaterialRule { + MaterialRule::OreVein { + ore: BlockStateId(1), + raw_ore: BlockStateId(2), + filler: BlockStateId(3), + raw_ore_chance: 0.02, + density: Arc::new(ConstantSampler(1.)), + richness: Arc::new(ConstantSampler(1.)), + filler_gap: Arc::new(ConstantSampler(-1.)), + } +} +#[test] +fn constant_branches_keep_binding_order_and_short_circuit_queries() { + let mut w = worker(Queries::default()); + let rule = w + .add_rule(MaterialRule::Sequence(vec![ + condition(biome("minecraft:desert"), ore()), + condition( + MaterialCondition::Not(Box::new(biome("minecraft:desert"))), + MaterialRule::Block(BlockStateId(9)), + ), + ore(), + ])) + .unwrap(); + w.update_xz(4, 5, 0, 0); + w.update_y(1, 1, i32::MIN, 64); + for _ in 0..2 { + assert_eq!( + w.try_apply(rule, BlockPos::new(4, 64, 5)), + Ok(Some(BlockStateId(9))) + ); + } + let q = w.into_surface(); + assert_eq!(q.bindings, [true, true, false, true, true, false]); + assert_eq!(q.biomes, 0); + assert_eq!(q.temperatures, 0); +} +#[test] +fn unreachable_children_still_fail_compilation_without_adding_a_rule() { + for preceding_block in [false, true] { + let mut w = worker(Queries { + fail_binding: true, + ..Queries::default() + }); + let dead = condition(biome("minecraft:desert"), ore()); + let rule = if preceding_block { + MaterialRule::Sequence(vec![MaterialRule::Block(BlockStateId(9)), dead]) + } else { + dead + }; + assert!(w.add_rule(rule).is_err()); + assert_eq!( + w.try_apply(0, BlockPos::new(0, 0, 0)), + Err(MaterialRuleError::UnknownRule) + ); + assert_eq!(w.into_surface().bindings, [true]); + } +} +#[test] +fn dynamic_predicate_on_empty_child_retains_each_temperature_call_and_error() { + for fail in [false, true] { + let mut w = worker(Queries { + fail_temperature: fail, + ..Queries::default() + }); + let rule = w + .add_rule(condition( + MaterialCondition::Temperature, + condition( + biome("minecraft:desert"), + MaterialRule::Block(BlockStateId(9)), + ), + )) + .unwrap(); + w.update_xz(0, 0, 0, 0); + w.update_y(1, 1, i32::MIN, 64); + for _ in 0..2 { + assert_eq!( + w.try_apply(rule, BlockPos::new(0, 64, 0)), + if fail { + Err(MaterialRuleError::BiomeQueryFailed) + } else { + Ok(None) + } + ); + } + let q = w.into_surface(); + assert_eq!(q.temperatures, 2); + assert_eq!(q.biomes, 1); + } +} diff --git a/crates/horizon-world/tests/state_provider_bounds.rs b/crates/horizon-world/tests/state_provider_bounds.rs index 033d4675c..23553e6b7 100644 --- a/crates/horizon-world/tests/state_provider_bounds.rs +++ b/crates/horizon-world/tests/state_provider_bounds.rs @@ -41,7 +41,13 @@ fn bound_recursive_providers_and_registry_lists_before_sampling() { let branching = serde_json::json!({"if_true":{"type":"all_of","predicates":vec![serde_json::json!({"type":"true"});7]},"then":{"id":"stone"}}); let oversized = serde_json::json!({"type":"rule_based","rules":vec![branching;8192]}); assert!(BlockStateProvider::from_json(&oversized.to_string(), &bindings).is_err()); - let tags = BTreeMap::from([("horizon:oversized".into(), vec!["stone".into(); 8193])]); + // Content mods' blocks join shared tags: the cap is 2^20 blocks. + let tags = BTreeMap::from([("horizon:large".into(), vec!["stone".into(); 8193])]); + assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_ok()); + let tags = BTreeMap::from([( + "horizon:oversized".into(), + vec!["stone".into(); (1 << 20) + 1], + )]); assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); let tags = BTreeMap::from([("tag".into(), vec![]), ("minecraft:tag".into(), vec![])]); assert!(StateProviderBindings::new(®istry, BTreeSet::new(), &tags).is_err()); diff --git a/docs/README.md b/docs/README.md index 7cf322042..9a5ea0483 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,8 @@ To play, use [the launcher](../launcher/README.md); the project site is [playhor - [Build from source](../README.md#build-from-source): your own copy of the game, resource preparation, `cargo run`. - [Native client](native-client.md): options, controls, the dedicated server, `horizon-ctl` scripting, packaging, architecture. -- [Hosting a server](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. +- [Host a server](hosting.md): install `horizon-server`, prepare the game files, first run, `server.toml`, the commands, the web panel, backups, services and Docker; what works today and what doesn't yet. +- [Hosting a server: design](server.md): `horizon-server`, the design and the plan: install, `server.toml`, the CLI, the web panel, backups, services, Docker, and the bot benchmark against vanilla. - [Agent control](agent-control.md): what AI agents can drive in the launcher and the game, and the design of the control socket, `horizon-ctl` and MCP. - [Graphics](graphics.md): the Simple and Advanced graphics settings, the graphics benchmark and what it measured. - [Benchmark](benchmark.md): Horizon against vanilla 26.3 and vanilla with performance mods, on the same machine, world, path and settings: what is measured, how it is kept fair, how to reproduce it. diff --git a/docs/graphics.md b/docs/graphics.md index a55313bea..7fa69577e 100644 --- a/docs/graphics.md +++ b/docs/graphics.md @@ -25,7 +25,7 @@ Every row has a one-line description and its cost in frame time (none, low, medi | Performance | battery mode, worker threads, upload budget per frame | `horizon-graphics.txt` | | Overlay | performance overlay: FPS, frame/CPU/GPU times, frame-time graph | `horizon-graphics.txt` | -`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. +`options.txt` keeps exactly vanilla's keys and values, so the options harness still compares it with vanilla; Horizon's settings live in `horizon-graphics.txt` beside it. Their defaults render as vanilla does: cave culling on, no upload budgets, sky, fog and weather on, 100% resolution, no FXAA, the present mode following VSync. VSync on always waits for the display (Fifo), in a window and in fullscreen, as in vanilla; the present mode setting chooses how frames are shown only while VSync is off. Frame pacing defaults to Efficient: the limiter sleeps through the last half millisecond where vanilla spins, which changes timing, not pixels. **Battery mode** (Performance, off by default) is for laptops and handhelds: at most 60 frames per second in a world, 30 in menus without a world or while another window has focus, and half the automatic worker threads (chunks load slower). It changes only when frames are drawn: what they show and the game's 20 ticks per second stay as they are. diff --git a/docs/hosting.md b/docs/hosting.md new file mode 100644 index 000000000..346eb7c8b --- /dev/null +++ b/docs/hosting.md @@ -0,0 +1,330 @@ +# Host a server + +`horizon-server` hosts a Minecraft Java Edition 26.3 server with Horizon's own game as the engine: one native +program, no Java, one settings file, a command line, and a web panel. Vanilla 26.3 clients and Horizon clients +can join it. This page covers what works on `main` today and says plainly what doesn't yet. The design and the +plan are in [docs/server.md](https://github.com/ludovic111/horizon/blob/main/docs/server.md). + +## Before you start + +- **Online mode checks accounts** (release v2026.10.17.07 and newer). With `online_mode = true`, the + default, players who sign in with the official Minecraft launcher join with their own accounts, as on a + vanilla server. +- **Names you add are accounts** (release v2026.10.17.14 and newer). `init --player`, `horizon-server + whitelist add` and `op`, and the console's `whitelist add`, `op` and `ban` look a name up the way vanilla + does: players already seen (kept in `usercache.json`), then Mojang's profile service. In online mode a name + with no account is refused. So you can whitelist friends before they first join. +- **Horizon's own client can't sign in to a Microsoft account yet.** That needs an Azure app registration and + Mojang's approval, which the project doesn't have + ([docs/microsoft-account.md](https://github.com/ludovic111/horizon/blob/main/docs/microsoft-account.md)). + Until then Horizon players can join offline servers only (`online_mode = false`). An offline server never + checks accounts: anyone who reaches it can join under any name. Keep it on your LAN or a tailnet + (Tailscale, ZeroTier), or share it only with friends you trust. +- **Secure chat** works as on vanilla's server: in online mode, vanilla clients sign their chat, and with + `enforce-secure-profile=true` (the default) unsigned chat is refused. On an offline server, or for a player + without a chat session (Horizon's own client today), chat stays unsigned and shows as not secure. +- **Nether and End:** each player travels on their own through portals, and operators with `execute in + run tp`. The players in the level they leave stop seeing them, and the ones in the level they + arrive in start to, as on vanilla (checked against vanilla with two players, by command and through an End + portal: `tools/test_server_dimension_players_parity.py`). The console can't send another player to a + dimension yet (`execute in ... run tp NAME`). +- **Movement checks and chunk pacing** (release v2026.10.17.16 and newer). The server pulls back players who + move too fast ("moved too quickly"), as vanilla does, and sends chunks as fast as each client acknowledges + them. +- **No Docker image is published.** You build it yourself from the repository (below). Publishing an image + needs the project owner. +- Nothing of Mojang's is downloaded or shipped. The server reads the game files you prepare from your own copy + of Minecraft 26.3. + +## 1. Install + +Linux (x86-64) and macOS (Apple Silicon): + +```sh +curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh +``` + +Windows (x64), in PowerShell: + +```powershell +irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex +``` + +The script downloads the latest Horizon release for your computer from GitHub, checks it against the SHA-256 +GitHub publishes, and never asks for sudo or administrator rights. It installs: + +- the release in `~/.local/share/horizon/releases/` (Windows: `%LOCALAPPDATA%\Horizon`), with + `current` pointing at the one in use; +- `horizon-server` and `horizon-prepare` in `~/.local/bin` (Windows: added to your PATH); +- a `game-files` folder for the files you prepare, kept across updates. + +Options: `--version vX.Y.Z`, `--dir FOLDER`, `--bin FOLDER` (Windows: `-Version`, `-Dir`). Other systems, +such as Linux on ARM, build from source: `cargo build --release -p horizon-client --bin horizon-client -p +horizon-server` and keep both programs in one folder. + +The Horizon launcher also installs releases. Every release folder holds `horizon-server`, so you can run it +from there too. + +## 2. Prepare the game files + +Horizon reads Minecraft's data from your own copy of the game. You need Minecraft Java Edition 26.3, played +once from the official launcher on this computer, Java 25 (a JDK), and the 26.3 `server.jar`: it's the +`downloads.server.url` in your launcher's `versions/26.3/26.3.json`. Then: + +```sh +horizon-prepare --prepare --server-jar /path/to/server.jar +``` + +Add `--minecraft-dir PATH` if your launcher keeps the game elsewhere. The prepared files go to +`game-files`, which updates keep. + +**On a headless machine** (a VPS, a home server), prepare on your own computer instead, with the launcher or +`horizon-prepare`, and copy the prepared `26.3` folder to the server: into +`~/.local/share/horizon/game-files/horizon-client/26.3`, or into `resources/` in the server folder, or anywhere +`[engine] resources` in `server.toml` names. A folder copied this way needs release v2026.10.17.07 or +newer: older ones don't keep `registries.json` and `commands.json` with the prepared files, and the +server then stops with "registries.json not found next to the resources". Prepare again with a newer release. + +## 3. First run + +```sh +mkdir my-server && cd my-server +horizon-server init +``` + +`init` asks five things and writes `server.toml`: + +1. whether you agree to the [Minecraft EULA](https://aka.ms/MinecraftEULA): only a yes writes `eula=true`; +2. the world's name and an optional seed (an existing world or vanilla server folder is kept and its + `server.properties` imported); +3. the port, 25565 by default; +4. whether to use a whitelist (yes by default, as in vanilla) and who to add; +5. whether to make the first player an operator. + +It then tells you where it found the game and its files. Every question has a flag, so it also runs from a +script: + +```sh +horizon-server init --eula --world survival --seed 12345 --port 25565 --whitelist --player Alex --op Alex --yes +``` + +`--no-whitelist` turns the whitelist off, and `--offline` turns online mode off (see "Before you start"). +The players you add are looked up as Minecraft accounts in online mode, and get offline UUIDs on an offline +server, as vanilla does. + +Start the server in the foreground, with the console on your terminal (Ctrl-C stops it cleanly): + +```sh +horizon-server run +``` + +or in the background: + +```sh +horizon-server start +horizon-server status +``` + +```text +Running, up 29 s +TPS 20.0, MSPT 1.0 ms average, 3.1 ms P95 +0 of 20 players, 377 chunks loaded +RAM 1.42 GB, CPU 2 % of a core +``` + +Players join at your computer's address and the port (`192.168.1.20:25565`, or a tailnet name). Every +command takes `--dir FOLDER` to work on a server folder from elsewhere. + +## 4. Settings: `server.toml` + +You edit one file. The server writes vanilla's `server.properties` from it before every start, so the game +reads exactly what a vanilla server reads, and a vanilla server folder works as it is. + +```toml +[server] +motd = "A Minecraft Server" +port = 25565 +bind = "" # listen on every address, or only on this one (server-ip) +max_players = 20 +online_mode = true # check accounts with Mojang (see "Before you start") +whitelist = true +enforce_whitelist = false +view_distance = 10 +simulation_distance = 10 + +[world] +name = "world" +seed = "" # empty: a random seed on the first start +game_mode = "survival" +difficulty = "easy" +hardcore = false + +# Any other server.properties key, spelled as vanilla spells it: +[properties] +# spawn-protection = 16 + +[engine] +path = "" # the game program; empty: the one beside horizon-server +resources = "" # the prepared game files; empty: resources/ here, else the usual places +restart_on_crash = true + +[backups] +every = "6h" # 30m, 6h, 1d...; "0" turns automatic backups off +keep = 12 # automatic backups kept; backups made by hand are never deleted + +[panel] +bind = "127.0.0.1:8130" # this computer only, or a tailnet address (100.x); "" turns it off +allow_public = false +``` + +The defaults are vanilla 26.3's. Unknown keys and values vanilla would refuse are errors, so a typo stops the +start instead of being ignored. When the game changes a setting itself (`/whitelist on`), the change is copied +back into `server.toml` when it stops, and your comments are kept. Changes to the file apply at the next +restart: there is no live reload yet. + +Already have a vanilla server? Run `horizon-server init` in its folder, or `horizon-server import +server.properties` to write `server.toml` from it. The world, `ops.json`, `whitelist.json` and the ban lists +keep vanilla's names and formats, so going back to vanilla works too. + +## 5. Commands + +```text +horizon-server init first run +horizon-server run in the foreground, with the console; Ctrl-C stops it +horizon-server start | stop | restart in the background (its output goes to logs/supervisor.log) +horizon-server status [--json] up or not, TPS, MSPT, players, chunks, RAM, CPU +horizon-server cmd COMMAND... one console command, and what it answers +horizon-server logs [-f] [-n N] the log; -f follows it +horizon-server op|deop NAME +horizon-server whitelist on|off|list +horizon-server whitelist add|remove NAME +horizon-server backup [NAME] back up now +horizon-server backups list the backups +horizon-server restore BACKUP [--yes] +horizon-server service install|uninstall|print [--system] +horizon-server panel a one-time login link for the web panel +horizon-server import FILE server.toml from a vanilla server.properties +``` + +While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so they act exactly as vanilla's +console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through +`cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. + +The server restarts the game by itself if it crashes: after 5 s, then waiting longer each time, up to 5 +minutes. It keeps the crash report and gives up after 5 crashes in 10 minutes, and `status` says why. + +Coming: `update` and `rollback`, `console` (attach to a server running in the background), `ban` and +`pardon` as their own commands, and `mcp` (an MCP server so an AI assistant can run the server). + +## 6. Web panel + +The panel runs inside `horizon-server` while the server runs. It shows live TPS, MSPT, RAM and CPU graphs for +the last 10 minutes, the players with their ping (and a kick button), the console with a command line, and the +backups (back up now, restore with a confirmation), with Restart and Stop. + +```sh +horizon-server panel +``` + +prints a login link that works once, for 10 minutes. The panel listens on `127.0.0.1:8130`, this computer +only. To reach it from your other devices: + +- put your tailnet address in `[panel] bind` (for example `bind = "100.101.102.103:8130"`), or +- forward the port over SSH: `ssh -L 8130:127.0.0.1:8130 your-server`, then open the link on your computer. + +Any other address, such as `0.0.0.0` or a public IP, is refused unless you set `allow_public = true`, and +even then the panel warns at every start. It has no passwords to leak: whoever can read the server folder can +make a login link, and no one else can. Never put it on the open internet. + +## 7. Backups + +```sh +horizon-server backup before-the-update +horizon-server backups +horizon-server restore before-the-update +``` + +A backup zips the world, vanilla's files and `server.toml` into `backups/`. A running server saves first and +stays up: players don't notice. Automatic backups run on the `[backups] every` schedule while the server runs, +and the oldest automatic ones beyond `keep` are deleted. Backups you make by hand are never deleted. + +`restore` takes a backup's file name, a unique start of it, or the name you gave it. It moves the current +world aside to `backups/replaced-