diff --git a/.github/workflows/cancel-on-close.yml b/.github/workflows/cancel-on-close.yml new file mode 100644 index 000000000..9a6e44965 --- /dev/null +++ b/.github/workflows/cancel-on-close.yml @@ -0,0 +1,27 @@ +name: cancel-on-close +# A closed or merged pull request's queued and running checks free the runners at once. +# pull_request_target so the token can cancel runs of pull requests from forks too; +# it checks out nothing and runs no code from the pull request. +on: + pull_request_target: + types: [closed] +permissions: + actions: write +jobs: + cancel: + runs-on: ubuntu-latest + steps: + - name: Cancel the pull request's unfinished runs + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + BRANCH: ${{ github.event.pull_request.head.ref }} + SHA: ${{ github.event.pull_request.head.sha }} + run: | + for status in queued in_progress waiting pending requested; do + gh run list -R "$REPO" --branch "$BRANCH" --status "$status" --limit 100 \ + --json databaseId,event,headSha \ + -q ".[] | select(.event == \"pull_request\" and .headSha == \"$SHA\") | .databaseId" + done | sort -u | while read -r id; do + gh run cancel -R "$REPO" "$id" || true + done diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5d5e285c5..da23874b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -56,6 +56,8 @@ jobs: run: | cargo +stable fmt --all -- --check cargo +stable clippy --workspace --all-targets -- -D warnings + # The server build (released as horizon-engine): the game without sound or controllers. + cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings - name: Test Rust core and voxel kernel correctness if: steps.rust.outputs.required != 'false' run: cargo +stable test --workspace diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a4780c85b..bd916514b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -76,6 +76,9 @@ jobs: os: ubuntu-22.04 dir: horizon-linux-x86_64 asset: horizon-linux-x86_64.tar.gz + # The server build too: packaging/server/install.sh installs it on Linux. + server_dir: horizon-server-linux-x86_64 + server_asset: horizon-server-linux-x86_64.tar.gz - name: windows os: windows-latest dir: horizon-windows-x64 @@ -190,6 +193,29 @@ jobs: path: dist/${{ matrix.asset }} if-no-files-found: error retention-days: 3 + - name: The server build (the game without sound or controllers, as horizon-engine) + if: matrix.server_asset + run: | + set -euo pipefail + # After the client is packaged: target/release/horizon-client is rebuilt without the audio and + # controllers features, so it needs neither libasound nor libudev (minimal server images lack them). + cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client + cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}" + folder="dist/${{ matrix.server_dir }}" + python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare" + "$folder/horizon-engine" --help | grep -q -- '--resources' + "$folder/horizon-server" --version + cd dist + rm -f "${{ matrix.server_asset }}" + tar czf "${{ matrix.server_asset }}" "${{ matrix.server_dir }}" + ls -l "${{ matrix.server_asset }}" + - uses: actions/upload-artifact@v4 + if: matrix.server_asset + with: + name: ${{ matrix.server_asset }} + path: dist/${{ matrix.server_asset }} + if-no-files-found: error + retention-days: 3 publish: needs: [decide, build] @@ -220,7 +246,7 @@ jobs: run: | gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ --notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ - dist/horizon-macos-arm64.zip + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/Cargo.lock b/Cargo.lock index b4081e7af..94e2052e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1435,6 +1435,7 @@ dependencies = [ "naga", "png", "pollster", + "rustix 1.1.5", "serde", "serde_json", "sha2", @@ -1555,6 +1556,7 @@ dependencies = [ name = "horizon-server" version = "0.1.0" dependencies = [ + "chrono", "horizon-bench", "horizon-server-files", "libc", diff --git a/benchmarks/server-equal-mixed-2026-10-18/README.md b/benchmarks/server-equal-mixed-2026-10-18/README.md new file mode 100644 index 000000000..5849e72ba --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/README.md @@ -0,0 +1,137 @@ +# Horizon's server against vanilla 26.3: mixed bots, equal work (2026-10-18) + +This reruns `../server-mixed-2026-10-18/` with the bots' load made the same on both servers. In that run the +`explore` bots flew as fast as each server sent them chunks. Horizon kept up and vanilla didn't, so Horizon +sent 2.9 to 5.9 times as many chunks a second, and vanilla's walking bots got a fifth of the chunks Horizon's +got. The comparison of tick times wasn't fair. + +## Summary + +- **The work was equal** at 1 and 10 bots. At 25 bots it was equal in chunks sent a second (158.6 against 157.6); + vanilla was still catching up on chunks its bots hadn't had yet, see "Equal work" below. Every bot joined, none + was dropped, no chunk was sent twice, and no bot ever waited for the chunk it stood in. +- **Tick time (MSPT), same work:** + - 1 bot: 1.8 ms on Horizon against 11.3 on vanilla; + - 10 bots: 4.7 against 34.3 ms; + - 25 bots: 11.7 against 50.5 ms. Vanilla dropped just under 20 TPS (19.8) and its worst 5-second P99 was + 1388 ms, against Horizon's 130; + - 50 bots: Horizon ran at 23.8 ms (20 TPS). Vanilla's watchdog stopped its server 30 s after the last bot + joined ("A single server tick took 60.01 seconds"). +- **Memory:** Horizon's RSS was 4.1 to 4.9 times smaller: 0.69 against 3.40 GB with one bot, 0.95 against + 3.87 GB with 25, and 1.03 GB with 50. Vanilla's heap is fixed at 4 GB, so its RSS is mostly that heap. +- **CPU** (100 % is one of the machine's 4 threads): 30 against 128 % at 10 bots, 58 against 192 % at 25. +- **What changed since the first run:** the first run's vanilla held 50 bots at 29.7 ms because its walking + bots got 640 to 1100 chunks each. With the explore bots paced, vanilla serves the walking bots in full + (5400 to 6100 chunks each, against Horizon's 6100 to 6600), and that is the load it can't carry at 50. + +## Results + +MSPT is milliseconds per tick from each server's own `/tick query` (50 is the limit for 20 TPS). P95 and P99 +are over the 300 measured seconds. "Worst P99" is the highest P99 of a single 5-second query. RSS and CPU +cover the server's process tree. "First-time chunks/s" counts chunks a bot hadn't received before (summed +over the bots). "Waited" is ticks a second that bots stood still waiting for their own chunk. "Pulled back" +counts position packets that moved a bot back. + +| Bots | Server | MSPT | P95 | P99 | Worst P99 | TPS | RSS (mean / max) | CPU | Start | Chunks/s | First-time chunks/s | Waited | Pulled back | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | **1.77** | 4.21 | 13.04 | 47.5 | 20 | **0.69 / 0.69 GB** | 28 % | 19.7 s | 9.94 | 0.01 | 0 | 0 | +| 1 | vanilla | 11.34 | 17.12 | 33.22 | 119.1 | 20 | 3.40 / 3.42 GB | 36 % | 20.4 s | 9.98 | 0.01 | 0 | 0 | +| 10 | Horizon | **4.74** | 10.48 | 19.69 | 120.1 | 20 | **0.86 / 0.88 GB** | 30 % | 19.5 s | 61.35 | 1.79 | 0 | 4159 | +| 10 | vanilla | 34.30 | 53.72 | 89.08 | 375.8 | 20 | 3.71 / 3.75 GB | 128 % | 19.9 s | 61.66 | 1.93 | 0 | 3976 | +| 25 | Horizon | **11.72** | 24.45 | 43.79 | 129.8 | 20 | **0.95 / 1.09 GB** | 58 % | 9.6 s | 158.57 | 5.78 | 0 | 3496 | +| 25 | vanilla | 50.45 | 74.09 | 191.21 | 1388.1 | 19.82 | 3.87 / 4.75 GB | 192 % | 37.8 s | 157.63 | 8.25 | 0 | 3629 | +| 50 | Horizon | **23.82** | 50.98 | 74.64 | 195.9 | 20 | **1.03 / 1.20 GB** | 98 % | 14.9 s | 302.81 | 10.96 | 0 | 7565 | +| 50 | vanilla | stopped by its watchdog | | | | | | | 11.2 s | | | | | + +Chunks each bot received over the whole run, by behaviour (mean): + +| Bots | Server | walk | explore | idle | +|---:|---|---:|---:|---:| +| 1 | Horizon | 6092 | | | +| 1 | vanilla | 6084 | | | +| 10 | Horizon | 6248 | 1165 | 473 | +| 10 | vanilla | 5729 | 1124 | 473 | +| 25 | Horizon | 6629 | 1267 | 473 | +| 25 | vanilla | 5387 | 1119 | 473 | +| 50 | Horizon | 6497 | 1256 | 473 | + +Both servers pulled bots back about as often (`moved too quickly` 20 and 296 times on vanilla at 10 and 25 +bots). + +## Equal work + +`tools/server_bench.py` now prints a work table after the runs. At each bot count it compares every server's +chunks sent a second and first-time chunks a second with the busiest server's. Work counts as equal when +both are within 10 % (or within a chunk a second when there are few). The report keeps the table as `work`. + +| Bots | Chunks/s (Horizon, vanilla) | First-time chunks/s (Horizon, vanilla) | Equal | +|---:|---|---|---| +| 1 | 9.94, 9.98 | 0.01, 0.01 | yes | +| 10 | 61.35, 61.66 | 1.79, 1.93 | yes | +| 25 | 158.57, 157.63 | 5.78, 8.25 | no: vanilla sent 2.5 more first-time chunks a second | + +Two settings made the load the same: + +- **Explore bots paced at 0.8 blocks a second** (`--explore-speed 0.8`), the rate the 2026-10-17 run showed + both servers keep up with. Every bot then follows the same path on both servers. The path is deterministic + per bot, and a bot only stops while the chunk it stands in hasn't arrived, which never happened here + (`Waited` 0). So both servers had the same chunks to send. +- **A 300-second warm-up** before the 300 measured seconds. A first pass with the old 60-second warm-up + (aborted after 10 bots) sent the same chunks a second on both (63.1 against 61.4). But vanilla was still + delivering the bots' first views during the measurement (12.9 first-time chunks a second against Horizon's + 4.1), so its window held more work than Horizon's. With 300 seconds both were in steady state at 1 and 10 + bots. At 25, vanilla still sent 2.5 more first-time chunks a second than Horizon: 1.6 % of all it sent, and + its walking bots ended the run with 19 % fewer chunks. Read the 25-bot tick times with that in mind: the + extra first-time chunks are work vanilla had still to do because it fell behind. + +## Method + +`tools/server_bench.py` ran 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`, white-list off; +- `gamerule respawn_radius 0`, and otherwise vanilla's default game rules (the locator bar on for both); +- the server waits for `Done`, the bots join one a second, warm up for 300 seconds and are measured for 300, + with `/tick query` every 5 seconds and RSS and CPU every second. + +The bots are `horizon-bots --behaviour mixed`: 60 % walk, 20 % explore and 20 % idle, each choice deterministic +per bot. All are creative and fly 24 blocks above spawn. `walk` flies to random points within 48 blocks at +5.6 blocks a second, `explore` flies straight out at 0.8 blocks a second, and `idle` hovers. + +**Machine.** The ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS. The desktop (24 threads) +was meant to run it, but it didn't wake (`~/fleet/power wake desktop` timed out, as it did for the first run). +No other session ran on the ThinkPad during the runs (`load.txt`, a sample a minute). The servers ran under +`nice -n 19`. The bots ran on the Mac mini (M4 Pro, shared with other work at 70 to 90 % CPU) and reached the +ThinkPad over the tailnet. + +**What ran.** + +- Horizon: the server build from #916 (`horizon-client --no-default-features`, no sound or controllers) at + 519ec121, packaged with `xtask package-server` and installed with `install.sh --archive`, as Linux owners + will get it. `horizon-server` ran it as `horizon-engine`. The game files were prepared from the owner's own + Minecraft. `horizon-bots` and `server_bench.py` came from this PR. +- Vanilla: the pinned 26.3 server jar (the owner's own copy) on OpenJDK 25.0.4.1, `-Xms4g -Xmx4g`. + +`server_bench.py` stopped after vanilla's 50-bot server crashed and before it wrote its report. +`mixed-equal.json` holds the run lines it printed. The vanilla 50 entry and its error come from that server's +log, and the `work` table was computed with `server_bench.work`. `load.txt` is the fleet monitor's view of the +machines during the runs. + +## Reproduce + + curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy + cargo build --release -p horizon-bots # on the machine that runs the bots + # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): + HORIZON_BENCH_BIN=~/.local/share/horizon/current \ + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50 --behaviour mixed \ + --explore-speed 0.8 --warmup 300 --nice 19 \ + --bots-via 'ssh ' --bots-bin /path/to/horizon-bots --connect \ + --out mixed-equal.json + +## Next + +- One pass per configuration ran. Vanilla at 50 bots, in particular, needs a second pass, ideally on the + desktop (24 threads), where neither server is CPU-bound. +- 100 bots, and Paper and Fabric + Lithium (docs/server.md section 9). +- A longer warm-up, or measuring from when the first-time chunk rate settles, so the 25-bot work is equal too. diff --git a/benchmarks/server-equal-mixed-2026-10-18/load.txt b/benchmarks/server-equal-mixed-2026-10-18/load.txt new file mode 100644 index 000000000..2992b4a26 --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/load.txt @@ -0,0 +1,702 @@ +2026-10-18T19:32:39Z +ludothinkpad ok: 27.2 GB free, 4 threads 17% busy, 0 sessions +desktop offline +macmini ok: 25.9 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 27.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 42% busy (agents 0.0, rest 1.6 cores) · 80°C · load 5.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:33:44Z +ludothinkpad ok: 26.7 GB free, 4 threads 19% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.7 cores) · 81°C · load 4.0 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:34:48Z +ludothinkpad ok: 26.4 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 26.9 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 54% busy (agents 0.0, rest 2.2 cores) · 79°C · load 2.8 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:35:52Z +ludothinkpad ok: 26.7 GB free, 4 threads 27% busy, 0 sessions +desktop offline +macmini ok: 25.4 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.1 cores) · 82°C · load 2.2 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:36:57Z +ludothinkpad ok: 26.7 GB free, 4 threads 25% busy, 0 sessions +desktop offline +macmini busy: 25.4 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 37% busy (agents 0.0, rest 1.2 cores) · 80°C · load 1.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:38:01Z +ludothinkpad ok: 26.6 GB free, 4 threads 54% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 64% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 21% busy (agents 0.0, rest 1.2 cores) · 81°C · load 1.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:39:05Z +ludothinkpad ok: 26.7 GB free, 4 threads 20% busy, 0 sessions +desktop offline +macmini ok: 26.1 GB free, 14 threads 70% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 28% busy (agents 0.0, rest 1.0 cores) · 81°C · load 1.3 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:40:10Z +ludothinkpad ok: 26.7 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 32% busy (agents 0.0, rest 1.7 cores) · 80°C · load 0.9 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:41:14Z +ludothinkpad ok: 26.7 GB free, 4 threads 31% busy, 0 sessions +desktop offline +macmini ok: 28.8 GB free, 14 threads 77% busy, 1 sessions +macbook offline + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 15% busy (agents 0.0, rest 1.1 cores) · 82°C · load 1.3 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:42:19Z +ludothinkpad ok: 26.5 GB free, 4 threads 26% busy, 0 sessions +desktop offline +macmini busy: 26.1 GB free, 14 threads 94% busy, 1 sessions +macbook offline + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.3 cores) · 78°C · load 1.1 + · disk 289.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:43:23Z +ludothinkpad busy: 26.7 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 83% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 3.8 cores) · 86°C · load 2.4 + · disk 289.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:44:27Z +ludothinkpad busy: 25.2 GB free, 4 threads 98% busy, 0 sessions +desktop offline +macmini ok: 29.0 GB free, 14 threads 73% busy, 1 sessions +macbook offline + RAM 24.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 83% busy (agents 0.0, rest 3.7 cores) · 83°C · load 5.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:45:31Z +ludothinkpad ok: 24.5 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini busy: 27.0 GB free, 14 threads 93% busy, 1 sessions +macbook offline + RAM 24.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.5 cores) · 84°C · load 3.5 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:46:35Z +ludothinkpad ok: 23.7 GB free, 4 threads 69% busy, 0 sessions +desktop offline +macmini busy: 26.2 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 23.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 75% busy (agents 0.0, rest 2.8 cores) · 87°C · load 2.7 + · disk 289.5 GB free · battery 96% · Ludovic: away + +2026-10-18T19:47:40Z +ludothinkpad ok: 23.8 GB free, 4 threads 66% busy, 0 sessions +desktop offline +macmini busy: 25.9 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 23.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 59% busy (agents 0.0, rest 2.5 cores) · 83°C · load 2.9 + · disk 291.7 GB free · battery 96% · Ludovic: away + +2026-10-18T19:48:44Z +ludothinkpad ok: 24.2 GB free, 4 threads 61% busy, 0 sessions +desktop offline +macmini busy: 29.0 GB free, 14 threads 90% busy, 1 sessions +macbook offline + RAM 24.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 62% busy (agents 0.0, rest 2.5 cores) · 84°C · load 3.2 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:49:48Z +ludothinkpad ok: 25.1 GB free, 4 threads 59% busy, 0 sessions +desktop offline +macmini ok: 31.1 GB free, 14 threads 81% busy, 1 sessions +macbook offline + RAM 25.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 57% busy (agents 0.0, rest 2.4 cores) · 85°C · load 2.9 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:50:52Z +ludothinkpad ok: 25.7 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini busy: 28.4 GB free, 14 threads 88% busy, 2 sessions +macbook offline + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 18% busy (agents 0.0, rest 1.4 cores) · 67°C · load 2.4 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:51:57Z +ludothinkpad ok: 23.7 GB free, 4 threads 40% busy, 0 sessions +desktop offline +macmini ok: 27.9 GB free, 14 threads 83% busy, 1 sessions +macbook offline + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 23% busy (agents 0.0, rest 1.4 cores) · 81°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:53:01Z +ludothinkpad ok: 25.3 GB free, 4 threads 25% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 84% busy, 1 sessions +macbook offline + RAM 25.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 31% busy (agents 0.0, rest 1.2 cores) · 80°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:54:05Z +ludothinkpad ok: 26.5 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 91% busy, 1 sessions +macbook offline + RAM 26.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 69% busy (agents 0.0, rest 2.5 cores) · 78°C · load 2.3 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:55:09Z +ludothinkpad busy: 26.4 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 86% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 32% busy (agents 0.0, rest 2.4 cores) · 79°C · load 2.9 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:56:14Z +ludothinkpad ok: 26.4 GB free, 4 threads 39% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 68% busy, 1 sessions +macbook offline + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 63% busy (agents 0.0, rest 1.8 cores) · 82°C · load 2.3 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:57:18Z +ludothinkpad ok: 26.3 GB free, 4 threads 20% busy, 0 sessions +desktop offline +macmini busy: 29.2 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 19% busy (agents 0.0, rest 1.0 cores) · 80°C · load 1.8 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:58:22Z +ludothinkpad ok: 26.3 GB free, 4 threads 28% busy, 0 sessions +desktop offline +macmini busy: 27.3 GB free, 14 threads 88% busy, 1 sessions +macbook offline + RAM 26.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 93% busy (agents 0.0, rest 2.5 cores) · 80°C · load 2.0 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T19:59:27Z +ludothinkpad ok: 26.2 GB free, 4 threads 52% busy, 0 sessions +desktop offline +macmini ok: 35.0 GB free, 14 threads 85% busy, 1 sessions +macbook offline + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 22% busy (agents 0.0, rest 1.8 cores) · 80°C · load 3.6 + · disk 291.4 GB free · battery 96% · Ludovic: away + +2026-10-18T20:00:31Z +ludothinkpad busy: 25.8 GB free, 4 threads 87% busy, 0 sessions +desktop offline +macmini busy: 33.0 GB free, 14 threads 87% busy, 1 sessions +macbook offline + RAM 27.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 51% busy (agents 0.0, rest 2.9 cores) · 79°C · load 3.6 + · disk 291.5 GB free · battery 96% · Ludovic: away + +2026-10-18T20:01:35Z +ludothinkpad ok: 25.6 GB free, 4 threads 35% busy, 0 sessions +desktop offline +macmini ok: 32.4 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 7.2 GB free, 12 threads 32% busy, 0 sessions + RAM 25.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 34% busy (agents 0.0, rest 1.3 cores) · 81°C · load 2.5 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T20:02:40Z +ludothinkpad ok: 26.6 GB free, 4 threads 35% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 79% busy, 1 sessions +macbook ok: 6.5 GB free, 12 threads 39% busy, 0 sessions + RAM 26.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 33% busy (agents 0.0, rest 1.3 cores) · 81°C · load 2.7 + · disk 291.6 GB free · battery 96% · Ludovic: away + +2026-10-18T20:03:44Z +ludothinkpad ok: 25.5 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 31.1 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 6% busy, 0 sessions + RAM 25.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.5 cores) · 87°C · load 2.5 + · disk 291.3 GB free · battery 96% · Ludovic: away + +2026-10-18T20:04:48Z +ludothinkpad busy: 26.2 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini busy: 30.0 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 31% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.7 cores) · 85°C · load 3.4 + · disk 291.3 GB free · battery 96% · Ludovic: away + +2026-10-18T20:05:52Z +ludothinkpad busy: 24.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 34.1 GB free, 14 threads 89% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 24.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 100% busy (agents 0.0, rest 4.0 cores) · 83°C · load 9.0 + · disk 291.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:06:57Z +ludothinkpad busy: 23.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 5% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 10.1 + · disk 309.2 GB free · battery 96% · Ludovic: away + +2026-10-18T20:08:01Z +ludothinkpad busy: 23.4 GB free, 4 threads 88% busy, 0 sessions +desktop offline +macmini ok: 29.6 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 2% busy, 0 sessions + RAM 23.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 77% busy (agents 0.0, rest 3.4 cores) · 84°C · load 7.5 + · disk 309.2 GB free · battery 96% · Ludovic: away + +2026-10-18T20:09:05Z +ludothinkpad busy: 24.0 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini ok: 25.9 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 7.1 GB free, 12 threads 19% busy, 0 sessions + RAM 23.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 91% busy (agents 0.0, rest 3.6 cores) · 82°C · load 5.9 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:10:09Z +ludothinkpad busy: 24.0 GB free, 4 threads 98% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 19% busy, 0 sessions + RAM 24.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 92% busy (agents 0.0, rest 3.7 cores) · 84°C · load 6.6 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:11:14Z +ludothinkpad busy: 24.3 GB free, 4 threads 92% busy, 0 sessions +desktop offline +macmini ok: 26.3 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 18% busy, 0 sessions + RAM 24.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 3.7 cores) · 85°C · load 6.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:12:18Z +ludothinkpad busy: 24.7 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini ok: 28.6 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 7.3 GB free, 12 threads 20% busy, 0 sessions + RAM 24.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 82% busy (agents 0.0, rest 3.4 cores) · 84°C · load 6.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:13:22Z +ludothinkpad ok: 23.4 GB free, 4 threads 53% busy, 0 sessions +desktop offline +macmini ok: 28.1 GB free, 14 threads 77% busy, 1 sessions +macbook ok: 7.3 GB free, 12 threads 20% busy, 0 sessions + RAM 23.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.4 cores) · 80°C · load 4.2 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:14:27Z +ludothinkpad ok: 24.0 GB free, 4 threads 44% busy, 0 sessions +desktop offline +macmini ok: 28.0 GB free, 14 threads 71% busy, 1 sessions +macbook ok: 6.9 GB free, 12 threads 2% busy, 0 sessions + RAM 24.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 23% busy (agents 0.0, rest 2.0 cores) · 77°C · load 4.3 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:15:31Z +ludothinkpad ok: 22.7 GB free, 4 threads 31% busy, 0 sessions +desktop offline +macmini busy: 27.2 GB free, 14 threads 86% busy, 1 sessions +macbook ok: 6.9 GB free, 12 threads 19% busy, 0 sessions + RAM 22.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 30% busy (agents 0.0, rest 1.3 cores) · 77°C · load 2.6 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:16:35Z +ludothinkpad ok: 26.8 GB free, 4 threads 37% busy, 0 sessions +desktop offline +macmini ok: 28.6 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 9% busy, 0 sessions + RAM 26.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 42% busy (agents 0.0, rest 1.7 cores) · 81°C · load 2.3 + · disk 309.1 GB free · battery 96% · Ludovic: away + +2026-10-18T20:17:39Z +ludothinkpad ok: 26.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 19% busy, 0 sessions + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 64% busy (agents 0.0, rest 2.6 cores) · 87°C · load 1.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:18:43Z +ludothinkpad ok: 26.9 GB free, 4 threads 37% busy, 0 sessions +desktop offline +macmini busy: 32.2 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 10% busy, 0 sessions + RAM 26.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 56% busy (agents 0.0, rest 1.9 cores) · 84°C · load 3.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:19:48Z +ludothinkpad ok: 26.0 GB free, 4 threads 77% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 83% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 10% busy, 0 sessions + RAM 26.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.9 cores) · 86°C · load 3.2 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:20:52Z +ludothinkpad ok: 25.9 GB free, 4 threads 80% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 7.0 GB free, 12 threads 17% busy, 0 sessions + RAM 25.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 68% busy (agents 0.0, rest 3.2 cores) · 86°C · load 4.4 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:21:56Z +ludothinkpad ok: 26.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.3 GB free, 14 threads 77% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 14% busy, 0 sessions + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 66% busy (agents 0.0, rest 2.8 cores) · 84°C · load 3.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:23:00Z +ludothinkpad ok: 26.8 GB free, 4 threads 74% busy, 0 sessions +desktop offline +macmini ok: 26.1 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 11% busy, 0 sessions + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 65% busy (agents 0.0, rest 2.8 cores) · 84°C · load 5.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:24:05Z +ludothinkpad ok: 26.9 GB free, 4 threads 64% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 90% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 8% busy, 0 sessions + RAM 26.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 64% busy (agents 0.0, rest 2.7 cores) · 86°C · load 4.9 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:25:09Z +ludothinkpad ok: 26.0 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 26.2 GB free, 14 threads 88% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 12% busy, 0 sessions + RAM 26.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 49% busy (agents 0.0, rest 2.1 cores) · 72°C · load 5.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:26:13Z +ludothinkpad ok: 25.8 GB free, 4 threads 47% busy, 0 sessions +desktop offline +macmini ok: 27.8 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 56% busy (agents 0.0, rest 2.1 cores) · 78°C · load 3.1 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:27:18Z +ludothinkpad busy: 25.5 GB free, 4 threads 94% busy, 0 sessions +desktop offline +macmini ok: 26.6 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 25.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 100% busy (agents 0.0, rest 3.9 cores) · 78°C · load 4.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:28:22Z +ludothinkpad busy: 24.6 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 24.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 77°C · load 10.5 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:29:27Z +ludothinkpad busy: 24.3 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 29.8 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 24.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 10.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:30:31Z +ludothinkpad busy: 23.7 GB free, 4 threads 91% busy, 0 sessions +desktop offline +macmini ok: 30.1 GB free, 14 threads 71% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 94% busy (agents 0.0, rest 3.8 cores) · 80°C · load 10.3 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:31:36Z +ludothinkpad busy: 23.6 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 28.0 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 14% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 95% busy (agents 0.0, rest 3.7 cores) · 80°C · load 10.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:32:40Z +ludothinkpad busy: 23.6 GB free, 4 threads 94% busy, 0 sessions +desktop offline +macmini ok: 26.9 GB free, 14 threads 76% busy, 1 sessions +macbook ok: 6.8 GB free, 12 threads 22% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.5 cores) · 80°C · load 9.7 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:33:45Z +ludothinkpad ok: 25.2 GB free, 4 threads 51% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 82% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 25.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.1 cores) · 87°C · load 6.5 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:34:49Z +ludothinkpad ok: 25.1 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini busy: 28.2 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 24.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 78% busy (agents 0.0, rest 2.7 cores) · 88°C · load 4.0 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:35:53Z +ludothinkpad busy: 23.6 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini busy: 27.9 GB free, 14 threads 86% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 17% busy, 0 sessions + RAM 23.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 88% busy (agents 0.0, rest 3.3 cores) · 85°C · load 4.9 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:36:58Z +ludothinkpad ok: 23.6 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini ok: 29.4 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.5 GB free, 12 threads 18% busy, 0 sessions + RAM 23.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.2 cores) · 85°C · load 5.1 + · disk 309.0 GB free · battery 96% · Ludovic: away + +2026-10-18T20:38:02Z +ludothinkpad ok: 22.6 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini ok: 26.5 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 22.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 54% busy (agents 0.0, rest 2.2 cores) · 85°C · load 4.5 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:39:06Z +ludothinkpad ok: 27.2 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini busy: 29.5 GB free, 14 threads 85% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 27.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 48% busy (agents 0.0, rest 2.2 cores) · 87°C · load 4.0 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:40:10Z +ludothinkpad ok: 26.2 GB free, 4 threads 72% busy, 0 sessions +desktop offline +macmini ok: 27.7 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 19% busy, 0 sessions + RAM 26.3 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 80% busy (agents 0.0, rest 3.1 cores) · 86°C · load 10.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:41:15Z +ludothinkpad busy: 26.4 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 28.5 GB free, 14 threads 79% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 26.4 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 90% busy (agents 0.0, rest 3.4 cores) · 86°C · load 12.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:42:19Z +ludothinkpad ok: 26.2 GB free, 4 threads 82% busy, 0 sessions +desktop offline +macmini ok: 26.9 GB free, 14 threads 78% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 11% busy, 0 sessions + RAM 26.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 74% busy (agents 0.0, rest 3.3 cores) · 85°C · load 8.8 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:43:23Z +ludothinkpad busy: 26.7 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 27.3 GB free, 14 threads 81% busy, 1 sessions +macbook ok: 6.6 GB free, 12 threads 10% busy, 0 sessions + RAM 26.7 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 88% busy (agents 0.0, rest 3.4 cores) · 85°C · load 5.4 + · disk 308.9 GB free · battery 96% · Ludovic: away + +2026-10-18T20:44:27Z +ludothinkpad ok: 27.0 GB free, 4 threads 82% busy, 0 sessions +desktop offline +macmini busy: 26.9 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 13% busy, 0 sessions + RAM 27.0 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 75% busy (agents 0.0, rest 3.3 cores) · 82°C · load 9.8 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:45:32Z +ludothinkpad ok: 27.2 GB free, 4 threads 76% busy, 0 sessions +desktop offline +macmini ok: 26.8 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 84% busy (agents 0.0, rest 3.2 cores) · 85°C · load 6.9 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:46:36Z +ludothinkpad busy: 27.1 GB free, 4 threads 87% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 92% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 26.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.2 cores) · 82°C · load 4.4 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:47:40Z +ludothinkpad busy: 25.3 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 26.5 GB free, 14 threads 72% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 25.5 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 85% busy (agents 0.0, rest 3.4 cores) · 86°C · load 3.7 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:48:45Z +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 28.5 GB free, 14 threads 84% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 15% busy, 0 sessions + RAM 26.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 98% busy (agents 0.0, rest 3.9 cores) · 80°C · load 6.5 + · disk 308.8 GB free · battery 96% · Ludovic: away + +2026-10-18T20:49:50Z +ludothinkpad ok: 26.8 GB free, 4 threads 71% busy, 0 sessions +desktop offline +macmini busy: 27.7 GB free, 14 threads 93% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 26.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 92% busy (agents 0.0, rest 3.4 cores) · 81°C · load 5.2 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:50:54Z +ludothinkpad busy: 25.8 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.3 GB free, 14 threads 95% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 11% busy, 0 sessions + RAM 25.8 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 99% busy (agents 0.0, rest 4.0 cores) · 82°C · load 8.1 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:51:59Z +ludothinkpad ok: 27.2 GB free, 4 threads 12% busy, 0 sessions +desktop offline +macmini ok: 31.2 GB free, 14 threads 76% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 8% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 15% busy (agents 0.0, rest 1.3 cores) · 81°C · load 7.9 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:53:03Z +ludothinkpad ok: 27.3 GB free, 4 threads 42% busy, 0 sessions +desktop offline +macmini busy: 27.8 GB free, 14 threads 87% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 27.2 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 14% busy (agents 0.0, rest 0.8 cores) · 82°C · load 3.1 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:54:08Z +ludothinkpad ok: 28.9 GB free, 4 threads 4% busy, 0 sessions +desktop offline +macmini ok: 29.2 GB free, 14 threads 80% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 9% busy, 0 sessions + RAM 28.9 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 2% busy (agents 0.0, rest 0.3 cores) · 82°C · load 1.3 + · disk 308.7 GB free · battery 96% · Ludovic: away + +2026-10-18T20:55:12Z +ludothinkpad ok: 27.7 GB free, 4 threads 27% busy, 0 sessions +desktop offline +macmini ok: 31.2 GB free, 14 threads 70% busy, 1 sessions +macbook ok: 6.7 GB free, 12 threads 10% busy, 0 sessions + RAM 27.6 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 26% busy (agents 0.0, rest 1.2 cores) · 69°C · load 1.0 + · disk 308.8 GB free · battery 96% · Ludovic: away + diff --git a/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json b/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json new file mode 100644 index 000000000..c494f3b24 --- /dev/null +++ b/benchmarks/server-equal-mixed-2026-10-18/mixed-equal.json @@ -0,0 +1,421 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-18T19:32:00+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4, + "name": "ThinkPad, Intel Core i7-7500U, 32 GB, NixOS" + }, + "commit": "f1d5bf520986b00a5b968a84d85809fca1a039fa", + "engine": "horizon-engine: the server build of #916 (horizon-client --no-default-features) at 519ec121, as install.sh --archive installed it", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "mixed", + "join_every": 1.0, + "warmup": 300, + "seconds": 300, + "seed": 12345, + "explore_speed": 0.8, + "gamerule": "", + "heap": "4g", + "nice": 19, + "bots_via": "ssh macmini", + "connect": "the ThinkPad's tailnet address", + "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" + } + }, + "note": "server_bench.py was stopped after vanilla's 50-bot server crashed, before it wrote this file; the runs are the lines it printed, and the vanilla 50 entry is taken from that server's log.", + "runs": [ + { + "server": "horizon", + "bots": 1, + "behaviour": "mixed", + "start_seconds": 19.73, + "mspt": { + "average": 1.77, + "p50": 1.34, + "p95": 4.21, + "p99": 13.04 + }, + "mspt_worst_p99": 47.5, + "tps": 20.0, + "rss_mb": { + "mean": 686.54, + "max": 686.7 + }, + "cpu_percent": 27.92, + "chunks_per_second": 9.94, + "unique_per_second": 0.01, + "forgotten_per_second": 9.9, + "waited_ticks_per_second": 0.0, + "chunks_total": 6092, + "chunks_per_bot": { + "walk": 6092.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": 1, + "behaviour": "mixed", + "start_seconds": 20.45, + "mspt": { + "average": 11.34, + "p50": 10.6, + "p95": 17.12, + "p99": 33.22 + }, + "mspt_worst_p99": 119.1, + "tps": 20.0, + "rss_mb": { + "mean": 3404.16, + "max": 3416.3 + }, + "cpu_percent": 35.93, + "chunks_per_second": 9.98, + "unique_per_second": 0.01, + "forgotten_per_second": 9.93, + "waited_ticks_per_second": 0.0, + "chunks_total": 6084, + "chunks_per_bot": { + "walk": 6084.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": 59 + }, + { + "server": "horizon", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 19.54, + "mspt": { + "average": 4.74, + "p50": 3.83, + "p95": 10.48, + "p99": 19.69 + }, + "mspt_worst_p99": 120.1, + "tps": 20.0, + "rss_mb": { + "mean": 855.26, + "max": 882.7 + }, + "cpu_percent": 29.78, + "chunks_per_second": 61.35, + "unique_per_second": 1.79, + "forgotten_per_second": 61.47, + "waited_ticks_per_second": 0.0, + "chunks_total": 40762, + "chunks_per_bot": { + "walk": 6247.67, + "explore": 1165.0, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.83, + "explore": 1086.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 4159, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 19.95, + "mspt": { + "average": 34.3, + "p50": 32.2, + "p95": 53.72, + "p99": 89.08 + }, + "mspt_worst_p99": 375.8, + "tps": 20.0, + "rss_mb": { + "mean": 3713.5, + "max": 3754.9 + }, + "cpu_percent": 128.07, + "chunks_per_second": 61.66, + "unique_per_second": 1.93, + "forgotten_per_second": 61.71, + "waited_ticks_per_second": 0.0, + "chunks_total": 37568, + "chunks_per_bot": { + "walk": 5729.0, + "explore": 1124.0, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.17, + "explore": 1055.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 3976, + "moved_too_quickly": 20, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 9.61, + "mspt": { + "average": 11.72, + "p50": 9.88, + "p95": 24.45, + "p99": 43.79 + }, + "mspt_worst_p99": 129.8, + "tps": 20.0, + "rss_mb": { + "mean": 947.35, + "max": 1086.1 + }, + "cpu_percent": 57.83, + "chunks_per_second": 158.57, + "unique_per_second": 5.78, + "forgotten_per_second": 158.45, + "waited_ticks_per_second": 0.0, + "chunks_total": 108126, + "chunks_per_bot": { + "walk": 6628.53, + "explore": 1266.6, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 704.67, + "explore": 1189.2, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 3496, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 37.78, + "mspt": { + "average": 50.45, + "p50": 46.39, + "p95": 74.09, + "p99": 191.21 + }, + "mspt_worst_p99": 1388.1, + "tps": 19.82, + "rss_mb": { + "mean": 3866.18, + "max": 4745.0 + }, + "cpu_percent": 192.42, + "chunks_per_second": 157.63, + "unique_per_second": 8.25, + "forgotten_per_second": 156.12, + "waited_ticks_per_second": 0.0, + "chunks_total": 88763, + "chunks_per_bot": { + "walk": 5387.0, + "explore": 1118.6, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 699.0, + "explore": 1075.0, + "idle": 473.0 + }, + "resent": 2, + "pulled_back": 3629, + "moved_too_quickly": 296, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 14.93, + "mspt": { + "average": 23.82, + "p50": 20.11, + "p95": 50.98, + "p99": 74.64 + }, + "mspt_worst_p99": 195.9, + "tps": 20.0, + "rss_mb": { + "mean": 1031.41, + "max": 1201.2 + }, + "cpu_percent": 98.21, + "chunks_per_second": 302.81, + "unique_per_second": 10.96, + "forgotten_per_second": 303.47, + "waited_ticks_per_second": 0.0, + "chunks_total": 212181, + "chunks_per_bot": { + "walk": 6496.53, + "explore": 1255.5, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 701.9, + "explore": 1184.7, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 7565, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 11.16, + "error": "stopped by its watchdog 30 s after the last bot joined: \"A single server tick took 60.01 seconds (should be max 0.05)\" (Player.tick)" + } + ], + "work": [ + { + "behaviour": "mixed", + "bots": 1, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 9.94, + "share": 0.996 + }, + "unique_per_second": { + "value": 0.01, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 9.98, + "share": 1.0 + }, + "unique_per_second": { + "value": 0.01, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": true + }, + { + "behaviour": "mixed", + "bots": 10, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 61.35, + "share": 0.995 + }, + "unique_per_second": { + "value": 1.79, + "share": 0.927 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 61.66, + "share": 1.0 + }, + "unique_per_second": { + "value": 1.93, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": true + }, + { + "behaviour": "mixed", + "bots": 25, + "servers": { + "horizon": { + "chunks_per_second": { + "value": 158.57, + "share": 1.0 + }, + "unique_per_second": { + "value": 5.78, + "share": 0.701 + }, + "waited_ticks_per_second": 0.0 + }, + "vanilla": { + "chunks_per_second": { + "value": 157.63, + "share": 0.994 + }, + "unique_per_second": { + "value": 8.25, + "share": 1.0 + }, + "waited_ticks_per_second": 0.0 + } + }, + "equal": false + } + ] +} diff --git a/benchmarks/server-mixed-2026-10-18/README.md b/benchmarks/server-mixed-2026-10-18/README.md new file mode 100644 index 000000000..3cbe3897f --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/README.md @@ -0,0 +1,125 @@ +# Horizon's server against vanilla 26.3: mixed bots (2026-10-18) + +The first benchmark from docs/server.md section 10 (item 4): the same bots on Horizon's dedicated server, as +`install.sh` installs it today, and on vanilla 26.3's, one server at a time on the same quiet machine. +There were 1, 10, 25 and 50 bots, all with the `mixed` behaviour. + +## Summary + +- **Both servers held 20 TPS in every run.** +- **Memory:** Horizon's RSS was 3.7 to 5.2 times smaller: 0.65 GB against 3.4 GB with one player, and + 1.0 GB against 4.0 GB with 50. Vanilla runs with the usual fixed heap (`-Xms4g -Xmx4g`), so its RSS + is mostly that heap. +- **Tick time (MSPT):** + - with 1, 10 and 25 players, Horizon's average tick was shorter (2.4 against 17.9 ms, 12.4 against 34.5, + 24.0 against 31.6); + - with 50, it was longer (35.2 against 29.7 ms); + - Horizon's P99 was lower at every count, and so were its worst 5-second windows (241 ms at most, + against 424 to 2320 ms for vanilla). +- **The work was not equal, and the difference counts against Horizon.** In `mixed`, 20 % of the bots + fly straight out at 22 blocks a second, as fast as each server sends them chunks. Horizon kept up: + - with 10 or more players it sent 2.9 to 5.9 times as many chunks a second, and generated 1.9 to 2.9 + times as much new terrain a second; + - its walking bots each received 3300 to 4000 chunks, against 640 to 1100 on vanilla once 10 or more + were online. + + So at 50 players Horizon's tick is 18 % longer while it generates twice the new terrain. The + equal-rate explore pass of `../server-equal-work-2026-10-17/` is the fair comparison for exploring. +- **Start (fresh world, to `Done`):** 10 to 20 s for Horizon, 14.5 to 28.6 s for vanilla. + +## Results + +MSPT is milliseconds per tick from each server's own `/tick query` (50 is the limit for 20 TPS). P95 and +P99 are over the whole run. "Worst P99" is the highest P99 of a single 5-second query. RSS and CPU cover +the server's whole process tree (100 % is one thread; the machine has 4). "New chunks/s" counts chunks +no bot had before. "Pulled back" counts position packets that moved a bot back. + +| Bots | Server | MSPT | P95 | P99 | Worst P99 | TPS | RSS (mean / max) | CPU | Start | Chunks/s | New chunks/s | Pulled back | +|---:|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| 1 | Horizon | **2.4** | 5.2 | 18.2 | 45.6 | 20 | **0.65 / 0.66 GB** | 25 % | 10.9 s | 9.9 | 0.3 | 0 | +| 1 | vanilla | 17.9 | 27.6 | 47.3 | 423.8 | 20 | 3.38 / 3.39 GB | 64 % | 14.8 s | 9.9 | 0.3 | 0 | +| 10 | Horizon | **12.4** | 36.0 | 65.9 | 117.1 | 20 | **0.94 / 1.01 GB** | 210 % | 10.2 s | 98.2 | 36.5 | 6267 | +| 10 | vanilla | 34.5 | 63.5 | 138.6 | 884.7 | 20 | 3.59 / 3.66 GB | 217 % | 14.5 s | 24.3 | 19.1 | 5500 | +| 25 | Horizon | **24.0** | 49.7 | 80.6 | 168.8 | 20 | **1.01 / 1.18 GB** | 192 % | 14.7 s | 178.2 | 31.9 | 5532 | +| 25 | vanilla | 31.6 | 70.0 | 222.7 | 2319.6 | 20 | 3.74 / 4.06 GB | 218 % | 28.6 s | 30.4 | 10.8 | 4524 | +| 50 | Horizon | 35.2 | 69.0 | 96.6 | 240.8 | 20 | **1.01 / 1.25 GB** | 218 % | 19.8 s | 273.2 | 34.6 | 8369 | +| 50 | vanilla | **29.7** | 62.3 | 137.4 | 489.3 | 20 | 4.00 / 4.60 GB | 294 % | 20.6 s | 94.4 | 17.8 | 12034 | + +Chunks each bot received, by behaviour (mean): + +| Bots | Server | walk | explore | idle | +|---:|---|---:|---:|---:| +| 10 | Horizon | 3992 | 7360 | 473 | +| 10 | vanilla | 680 | 2824 | 358 | +| 25 | Horizon | 3928 | 2475 | 473 | +| 25 | vanilla | 640 | 738 | 180 | +| 50 | Horizon | 3300 | 1192 | 460 | +| 50 | vanilla | 1105 | 629 | 220 | + +No bot failed to join or was dropped, and no chunk was sent twice (`resent` 0), on either server. Vanilla +also logged "moved too quickly" 12, 324 and 2193 times at 10, 25 and 50 bots. + +## Method + +`tools/server_bench.py`, unchanged, 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`, white-list off; +- `gamerule respawn_radius 0`, and otherwise vanilla's default game rules on both. The locator bar is on + for both: Horizon's server has run it since v2026.10.18.13. The 2026-10-17 runs turned it off on vanilla + because Horizon had none then; +- the server waits for `Done`, then the bots join one a second, warm up for 60 seconds, and are measured + for 300 seconds, with `/tick query` every 5 seconds and RSS and CPU every second. + +The bots are `horizon-bots --behaviour mixed`: 60 % walk, 20 % explore and 20 % idle, each choice +deterministic per bot. All are creative and fly 24 blocks above their spawn: + +- `walk`: random points within 48 blocks at 5.6 blocks a second; +- `explore`: straight out at up to 22 blocks a second, as fast as chunks come; +- `idle`: hovers. + +A bot doesn't move while the chunk it stands in hasn't arrived, and it acknowledges chunk batches as +vanilla's client does. + +**Machine.** The ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS (Linux 6.18). No other +session ran on it (`load.txt`: the fleet monitor shows 0 sessions throughout). The busy periods are the +servers themselves, which used 2 to 3 of its 4 threads from 10 bots up, so both servers were CPU-bound +there. The servers ran under `nice -n 19`. The desktop was meant to run this (24 threads) but didn't +wake. The bots ran on the Mac mini (M4 Pro) and reached the ThinkPad over the tailnet, so they took none +of the servers' CPU. The Mac mini was shared with other work (70 to 90 % busy), which only affects the +bots' timing. + +**What ran.** + +- Horizon: the published v2026.10.18.15 release, `horizon-client` (the engine) at 6c078b28, as + `install.sh` installs it. Its game files were prepared from the owner's own Minecraft by the release's + `horizon-prepare`. `horizon-server` (the supervisor, which takes no part in the tick) came from #898 + (4ea2243e), because the release's copy can't find game files prepared without sounds (#893). + `horizon-bots` came from main. +- Vanilla: the pinned 26.3 server jar (the owner's own copy) on OpenJDK 25.0.4.1, `-Xms4g -Xmx4g`. + +On Linux the release's engine needs `libasound.so.2` and `libudev.so.1`. The ThinkPad has them only in +the Nix store, so the run set `LD_LIBRARY_PATH` to them (see #898). + +## Reproduce + + curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh + horizon-prepare --prepare --server-jar /path/to/server.jar # your own copy + cargo build --release -p horizon-bots # on the machine that runs the bots + # in a checkout whose .local/minecraft holds the pinned vanilla jars (tools/lab.py prepare): + HORIZON_BENCH_BIN= \ + python3 tools/server_bench.py --servers horizon,vanilla --bots 1,10,25,50 --behaviour mixed --nice 19 \ + --bots-via 'ssh ' --bots-bin /path/to/horizon-bots --connect \ + --out mixed.json + +`mixed.json` is the report (`horizon-server-benchmark`: machine, versions, settings and every run), and +`load.txt` is the ThinkPad's load before and during the run. + +## Next + +- An equal-work `mixed` pass (`--explore-speed` at a rate both servers keep up with), then 100 bots. +- The same run on a bigger machine, so neither server is CPU-bound at 25 to 50 bots. +- Paper and Fabric + Lithium (docs/server.md section 9). +- At 50 players Horizon's tick is longer than vanilla's while it generates and sends far more. The + profile of the 2026-10-17 run (streaming and block entity ticks growing with players) is + perf-server's to take on. diff --git a/benchmarks/server-mixed-2026-10-18/load.txt b/benchmarks/server-mixed-2026-10-18/load.txt new file mode 100644 index 000000000..3468f9f86 --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/load.txt @@ -0,0 +1,286 @@ +ludothinkpad — OK + RAM 29.1 GB free of 31.2 GB · swap 0.3 GB/15.6 GB + CPU 4 threads, 2% busy (agents 0.0, rest 0.1 cores) · 67°C · load 2.1 + · disk 295.5 GB free · battery 96% + +Sessions, most important first: + (finished session) 0.0 GB leftovers: node 0.0 GB + +Other machines (≤ 1 min old): desktop offline · macbook offline · macmini ok: 26.6 GB free, 14 threads 69% busy, 1 sessions + +# During the run, once a minute (uptime, then ~/fleet/load fleet) +18:25:30 + 18:25:30 up 8 days 3:08, 0 users, load average: 2.13, 1.53, 1.29 +ludothinkpad ok: 29.1 GB free, 4 threads 2% busy, 0 sessions +desktop offline +macmini busy: 27.6 GB free, 14 threads 87% busy, 1 sessions +18:26:34 + 18:26:34 up 8 days 3:09, 0 users, load average: 1.70, 1.56, 1.31 +ludothinkpad ok: 28.5 GB free, 4 threads 23% busy, 0 sessions +desktop offline +macmini busy: 26.4 GB free, 14 threads 85% busy, 1 sessions +18:27:38 + 18:27:38 up 8 days 3:10, 0 users, load average: 1.10, 1.43, 1.28 +ludothinkpad ok: 28.5 GB free, 4 threads 4% busy, 0 sessions +desktop offline +macmini ok: 27.7 GB free, 14 threads 80% busy, 1 sessions +18:28:42 + 18:28:42 up 8 days 3:11, 0 users, load average: 0.93, 1.29, 1.24 +ludothinkpad ok: 28.5 GB free, 4 threads 22% busy, 0 sessions +desktop offline +macmini ok: 26.0 GB free, 14 threads 82% busy, 1 sessions +18:29:46 + 18:29:46 up 8 days 3:12, 0 users, load average: 0.62, 1.12, 1.18 +ludothinkpad ok: 28.5 GB free, 4 threads 12% busy, 0 sessions +desktop offline +macmini ok: 25.7 GB free, 14 threads 81% busy, 1 sessions +18:30:50 + 18:30:51 up 8 days 3:13, 0 users, load average: 0.79, 1.05, 1.15 +ludothinkpad ok: 28.5 GB free, 4 threads 7% busy, 0 sessions +desktop offline +macmini busy: 27.0 GB free, 14 threads 88% busy, 1 sessions +18:31:55 + 18:31:55 up 8 days 3:14, 0 users, load average: 0.67, 0.96, 1.11 +ludothinkpad ok: 28.6 GB free, 4 threads 73% busy, 0 sessions +desktop offline +macmini ok: 27.3 GB free, 14 threads 79% busy, 1 sessions +18:32:59 + 18:32:59 up 8 days 3:15, 0 users, load average: 4.01, 1.91, 1.44 +ludothinkpad ok: 25.9 GB free, 4 threads 24% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 85% busy, 1 sessions +18:34:03 + 18:34:03 up 8 days 3:16, 0 users, load average: 2.24, 1.84, 1.44 +ludothinkpad ok: 25.9 GB free, 4 threads 21% busy, 0 sessions +desktop offline +macmini busy: 29.2 GB free, 14 threads 86% busy, 1 sessions +18:35:07 + 18:35:07 up 8 days 3:17, 0 users, load average: 1.28, 1.63, 1.40 +ludothinkpad ok: 25.8 GB free, 4 threads 21% busy, 0 sessions +desktop offline +macmini busy: 31.0 GB free, 14 threads 86% busy, 1 sessions +18:36:11 + 18:36:11 up 8 days 3:18, 0 users, load average: 0.79, 1.41, 1.33 +ludothinkpad ok: 25.9 GB free, 4 threads 18% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 93% busy, 1 sessions +18:37:15 + 18:37:15 up 8 days 3:20, 0 users, load average: 1.44, 1.47, 1.36 +ludothinkpad ok: 25.9 GB free, 4 threads 23% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 86% busy, 1 sessions +18:38:19 + 18:38:19 up 8 days 3:21, 0 users, load average: 1.37, 1.45, 1.36 +ludothinkpad ok: 25.9 GB free, 4 threads 13% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 86% busy, 1 sessions +18:39:24 + 18:39:24 up 8 days 3:22, 0 users, load average: 2.27, 1.66, 1.44 +ludothinkpad ok: 28.3 GB free, 4 threads 62% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 70% busy, 1 sessions +18:40:28 + 18:40:28 up 8 days 3:23, 0 users, load average: 1.95, 1.72, 1.48 +ludothinkpad ok: 28.3 GB free, 4 threads 63% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 84% busy, 1 sessions +18:41:32 + 18:41:32 up 8 days 3:24, 0 users, load average: 3.32, 2.22, 1.67 +ludothinkpad ok: 28.2 GB free, 4 threads 61% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 85% busy, 1 sessions +18:42:36 + 18:42:36 up 8 days 3:25, 0 users, load average: 3.13, 2.33, 1.75 +ludothinkpad ok: 28.2 GB free, 4 threads 60% busy, 0 sessions +desktop offline +macmini busy: 27.1 GB free, 14 threads 91% busy, 1 sessions +18:43:40 + 18:43:40 up 8 days 3:26, 0 users, load average: 3.27, 2.48, 1.83 +ludothinkpad busy: 28.1 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 92% busy, 1 sessions +18:44:44 + 18:44:44 up 8 days 3:27, 0 users, load average: 2.14, 2.32, 1.82 +ludothinkpad ok: 28.1 GB free, 4 threads 55% busy, 0 sessions +desktop offline +macmini busy: 30.4 GB free, 14 threads 88% busy, 1 sessions +18:45:48 + 18:45:48 up 8 days 3:28, 0 users, load average: 4.94, 3.06, 2.11 +ludothinkpad busy: 25.9 GB free, 4 threads 86% busy, 0 sessions +desktop offline +macmini ok: 28.7 GB free, 14 threads 84% busy, 1 sessions +18:46:53 + 18:46:53 up 8 days 3:29, 0 users, load average: 6.55, 3.92, 2.47 +ludothinkpad busy: 25.4 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 29.3 GB free, 14 threads 81% busy, 1 sessions +18:47:57 + 18:47:57 up 8 days 3:30, 0 users, load average: 8.50, 4.96, 2.93 +ludothinkpad busy: 24.0 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 27.9 GB free, 14 threads 90% busy, 1 sessions +18:49:01 + 18:49:01 up 8 days 3:31, 0 users, load average: 8.59, 5.68, 3.31 +ludothinkpad busy: 22.7 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 85% busy, 1 sessions +18:50:05 + 18:50:05 up 8 days 3:32, 0 users, load average: 7.81, 6.07, 3.61 +ludothinkpad busy: 24.5 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.6 GB free, 14 threads 96% busy, 1 sessions +18:51:09 + 18:51:09 up 8 days 3:33, 0 users, load average: 8.29, 6.50, 3.93 +ludothinkpad busy: 24.3 GB free, 4 threads 92% busy, 0 sessions +desktop offline +macmini busy: 28.0 GB free, 14 threads 94% busy, 1 sessions +18:52:14 + 18:52:14 up 8 days 3:35, 0 users, load average: 5.58, 6.06, 3.95 +ludothinkpad busy: 26.0 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 26.3 GB free, 14 threads 87% busy, 1 sessions +18:53:18 + 18:53:18 up 8 days 3:36, 0 users, load average: 4.53, 5.69, 3.97 +ludothinkpad busy: 27.2 GB free, 4 threads 89% busy, 0 sessions +desktop offline +macmini busy: 26.8 GB free, 14 threads 87% busy, 1 sessions +18:54:22 + 18:54:22 up 8 days 3:37, 0 users, load average: 5.31, 5.64, 4.07 +ludothinkpad busy: 26.3 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 29.3 GB free, 14 threads 91% busy, 1 sessions +18:55:26 + 18:55:26 up 8 days 3:38, 0 users, load average: 10.47, 6.99, 4.63 +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 26.7 GB free, 14 threads 90% busy, 1 sessions +18:56:30 + 18:56:30 up 8 days 3:39, 0 users, load average: 9.27, 7.45, 4.96 +ludothinkpad busy: 26.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.5 GB free, 14 threads 92% busy, 1 sessions +18:57:35 + 18:57:35 up 8 days 3:40, 0 users, load average: 7.79, 7.39, 5.10 +ludothinkpad busy: 26.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 27.1 GB free, 14 threads 80% busy, 1 sessions +18:58:39 + 18:58:39 up 8 days 3:41, 0 users, load average: 8.06, 7.55, 5.32 +ludothinkpad busy: 26.4 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.8 GB free, 14 threads 95% busy, 1 sessions +18:59:43 + 18:59:43 up 8 days 3:42, 0 users, load average: 8.44, 7.65, 5.50 +ludothinkpad busy: 26.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.4 GB free, 14 threads 94% busy, 1 sessions +19:00:47 + 19:00:47 up 8 days 3:43, 0 users, load average: 11.04, 8.66, 6.00 +ludothinkpad busy: 24.9 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 31.8 GB free, 14 threads 88% busy, 1 sessions +19:01:51 + 19:01:51 up 8 days 3:44, 0 users, load average: 11.91, 9.37, 6.41 +ludothinkpad busy: 24.4 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 32.9 GB free, 14 threads 77% busy, 1 sessions +19:02:56 + 19:02:56 up 8 days 3:45, 0 users, load average: 11.64, 9.85, 6.79 +ludothinkpad ok: 25.5 GB free, 4 threads 70% busy, 0 sessions +desktop offline +macmini busy: 30.9 GB free, 14 threads 91% busy, 1 sessions +19:04:00 + 19:04:00 up 8 days 3:46, 0 users, load average: 11.42, 10.06, 7.06 +ludothinkpad busy: 23.4 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini busy: 28.4 GB free, 14 threads 94% busy, 1 sessions +19:05:04 + 19:05:04 up 8 days 3:47, 0 users, load average: 9.83, 9.96, 7.24 +ludothinkpad busy: 23.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 31.4 GB free, 14 threads 80% busy, 1 sessions +19:06:09 + 19:06:09 up 8 days 3:48, 0 users, load average: 8.38, 9.68, 7.34 +ludothinkpad ok: 22.7 GB free, 4 threads 17% busy, 0 sessions +desktop offline +macmini busy: 29.8 GB free, 14 threads 86% busy, 1 sessions +19:07:13 + 19:07:13 up 8 days 3:49, 0 users, load average: 4.51, 8.27, 7.00 +ludothinkpad ok: 25.7 GB free, 4 threads 75% busy, 0 sessions +desktop offline +macmini busy: 26.5 GB free, 14 threads 89% busy, 1 sessions +19:08:17 + 19:08:17 up 8 days 3:51, 0 users, load average: 6.77, 8.13, 7.04 +ludothinkpad busy: 25.8 GB free, 4 threads 95% busy, 0 sessions +desktop offline +macmini busy: 30.8 GB free, 14 threads 91% busy, 1 sessions +19:09:22 + 19:09:22 up 8 days 3:52, 0 users, load average: 8.27, 8.25, 7.14 +ludothinkpad busy: 25.2 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.3 GB free, 14 threads 91% busy, 1 sessions +19:10:26 + 19:10:26 up 8 days 3:53, 0 users, load average: 8.88, 8.57, 7.34 +ludothinkpad busy: 24.8 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 32.4 GB free, 14 threads 72% busy, 1 sessions +19:11:30 + 19:11:30 up 8 days 3:54, 0 users, load average: 13.33, 10.05, 7.94 +ludothinkpad busy: 24.7 GB free, 4 threads 97% busy, 0 sessions +desktop offline +macmini busy: 30.1 GB free, 14 threads 87% busy, 1 sessions +19:12:35 + 19:12:35 up 8 days 3:55, 0 users, load average: 10.92, 10.13, 8.12 +ludothinkpad ok: 26.4 GB free, 4 threads 76% busy, 0 sessions +desktop offline +macmini busy: 29.3 GB free, 14 threads 86% busy, 1 sessions +19:13:39 + 19:13:39 up 8 days 3:56, 0 users, load average: 9.98, 9.89, 8.16 +ludothinkpad busy: 25.8 GB free, 4 threads 90% busy, 0 sessions +desktop offline +macmini busy: 28.8 GB free, 14 threads 93% busy, 1 sessions +19:14:43 + 19:14:43 up 8 days 3:57, 0 users, load average: 8.95, 9.63, 8.19 +ludothinkpad busy: 25.1 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 29.6 GB free, 14 threads 71% busy, 1 sessions +19:15:47 + 19:15:47 up 8 days 3:58, 0 users, load average: 12.02, 10.38, 8.55 +ludothinkpad busy: 24.5 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini busy: 28.1 GB free, 14 threads 93% busy, 1 sessions +19:16:52 + 19:16:52 up 8 days 3:59, 0 users, load average: 13.82, 11.21, 8.95 +ludothinkpad busy: 23.9 GB free, 4 threads 100% busy, 0 sessions +desktop offline +macmini ok: 28.4 GB free, 14 threads 75% busy, 1 sessions +19:17:56 + 19:17:56 up 8 days 4:00, 0 users, load average: 11.95, 11.20, 9.10 +ludothinkpad busy: 25.0 GB free, 4 threads 99% busy, 0 sessions +desktop offline +macmini ok: 28.4 GB free, 14 threads 81% busy, 1 sessions +19:19:00 + 19:19:00 up 8 days 4:01, 0 users, load average: 11.46, 11.14, 9.22 +ludothinkpad busy: 24.6 GB free, 4 threads 95% busy, 0 sessions +desktop offline +macmini ok: 26.4 GB free, 14 threads 83% busy, 1 sessions +19:20:04 + 19:20:04 up 8 days 4:02, 0 users, load average: 11.11, 10.97, 9.28 +ludothinkpad busy: 24.6 GB free, 4 threads 93% busy, 0 sessions +desktop offline +macmini ok: 26.7 GB free, 14 threads 85% busy, 1 sessions +19:21:08 + 19:21:08 up 8 days 4:03, 0 users, load average: 9.81, 10.60, 9.27 +ludothinkpad busy: 24.4 GB free, 4 threads 91% busy, 0 sessions +desktop offline +macmini ok: 27.8 GB free, 14 threads 75% busy, 1 sessions +19:22:13 + 19:22:13 up 8 days 4:04, 0 users, load average: 5.98, 9.51, 9.00 +ludothinkpad ok: 23.8 GB free, 4 threads 18% busy, 0 sessions +desktop offline +macmini busy: 29.7 GB free, 14 threads 85% busy, 1 sessions +19:23:17 + 19:23:17 up 8 days 4:06, 0 users, load average: 4.01, 8.27, 8.60 +ludothinkpad ok: 23.1 GB free, 4 threads 56% busy, 0 sessions +desktop offline +macmini ok: 28.2 GB free, 14 threads 79% busy, 1 sessions diff --git a/benchmarks/server-mixed-2026-10-18/mixed.json b/benchmarks/server-mixed-2026-10-18/mixed.json new file mode 100644 index 000000000..36b21c327 --- /dev/null +++ b/benchmarks/server-mixed-2026-10-18/mixed.json @@ -0,0 +1,367 @@ +{ + "kind": "horizon-server-benchmark", + "date": "2026-10-18T17:23:30+00:00", + "machine": { + "system": "Linux", + "machine": "x86_64", + "cpus": 4, + "note": "ThinkPad: Intel Core i7-7500U (2 cores, 4 threads), 32 GB, NixOS, Linux 6.18; the bots on the Mac mini (M4 Pro) over the tailnet" + }, + "commit": "4ea2243e4d1a44f910857bd759845db70e3690a8", + "java": [ + "openjdk 25.0.4.1 2026-08-18" + ], + "settings": { + "servers": "horizon,vanilla", + "bots": "1,10,25,50", + "behaviour": "mixed", + "join_every": 1.0, + "warmup": 60, + "seconds": 300, + "seed": 12345, + "explore_speed": 0, + "gamerule": "", + "heap": "4g", + "out": "mixed.json", + "nice": 19, + "bots_via": "ssh macmini", + "bots_bin": "horizon-bots (on the Mac mini)", + "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": "mixed", + "start_seconds": 10.92, + "mspt": { + "average": 2.38, + "p50": 1.97, + "p95": 5.17, + "p99": 18.2 + }, + "mspt_worst_p99": 45.6, + "tps": 20.0, + "rss_mb": { + "mean": 653.7, + "max": 659.2 + }, + "cpu_percent": 24.51, + "chunks_per_second": 9.9, + "unique_per_second": 0.3, + "forgotten_per_second": 9.93, + "waited_ticks_per_second": 0.0, + "chunks_total": 3951, + "chunks_per_bot": { + "walk": 3951.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": 1, + "behaviour": "mixed", + "start_seconds": 14.75, + "mspt": { + "average": 17.9, + "p50": 18.39, + "p95": 27.58, + "p99": 47.28 + }, + "mspt_worst_p99": 423.8, + "tps": 20.0, + "rss_mb": { + "mean": 3382.06, + "max": 3394.1 + }, + "cpu_percent": 64.02, + "chunks_per_second": 9.92, + "unique_per_second": 0.29, + "forgotten_per_second": 9.95, + "waited_ticks_per_second": 0.0, + "chunks_total": 3846, + "chunks_per_bot": { + "walk": 3846.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": "mixed", + "start_seconds": 10.22, + "mspt": { + "average": 12.39, + "p50": 8.33, + "p95": 35.99, + "p99": 65.9 + }, + "mspt_worst_p99": 117.1, + "tps": 20.0, + "rss_mb": { + "mean": 935.85, + "max": 1008.6 + }, + "cpu_percent": 210.37, + "chunks_per_second": 98.22, + "unique_per_second": 36.49, + "forgotten_per_second": 98.25, + "waited_ticks_per_second": 0.0, + "chunks_total": 39618, + "chunks_per_bot": { + "walk": 3992.17, + "explore": 7359.5, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 696.83, + "explore": 6869.0, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 6267, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 10, + "behaviour": "mixed", + "start_seconds": 14.54, + "mspt": { + "average": 34.47, + "p50": 29.67, + "p95": 63.52, + "p99": 138.58 + }, + "mspt_worst_p99": 884.7, + "tps": 20.0, + "rss_mb": { + "mean": 3594.26, + "max": 3661.7 + }, + "cpu_percent": 217.13, + "chunks_per_second": 24.34, + "unique_per_second": 19.13, + "forgotten_per_second": 20.12, + "waited_ticks_per_second": 0.62, + "chunks_total": 10443, + "chunks_per_bot": { + "walk": 679.83, + "explore": 2824.0, + "idle": 358.0 + }, + "unique_chunks_per_bot": { + "walk": 389.17, + "explore": 2824.0, + "idle": 358.0 + }, + "resent": 0, + "pulled_back": 5500, + "moved_too_quickly": 12, + "moved_wrongly": 0, + "bots_joined": 10, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "horizon", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 14.73, + "mspt": { + "average": 24.0, + "p50": 21.07, + "p95": 49.72, + "p99": 80.57 + }, + "mspt_worst_p99": 168.8, + "tps": 20.0, + "rss_mb": { + "mean": 1013.07, + "max": 1179.4 + }, + "cpu_percent": 192.47, + "chunks_per_second": 178.23, + "unique_per_second": 31.85, + "forgotten_per_second": 177.93, + "waited_ticks_per_second": 60.59, + "chunks_total": 73657, + "chunks_per_bot": { + "walk": 3927.87, + "explore": 2474.8, + "idle": 473.0 + }, + "unique_chunks_per_bot": { + "walk": 691.73, + "explore": 2447.8, + "idle": 473.0 + }, + "resent": 0, + "pulled_back": 5532, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 58 + }, + { + "server": "vanilla", + "bots": 25, + "behaviour": "mixed", + "start_seconds": 28.57, + "mspt": { + "average": 31.59, + "p50": 25.18, + "p95": 70.03, + "p99": 222.74 + }, + "mspt_worst_p99": 2319.6, + "tps": 20.0, + "rss_mb": { + "mean": 3742.51, + "max": 4055.0 + }, + "cpu_percent": 218.34, + "chunks_per_second": 30.37, + "unique_per_second": 10.84, + "forgotten_per_second": 29.44, + "waited_ticks_per_second": 50.91, + "chunks_total": 14193, + "chunks_per_bot": { + "walk": 640.2, + "explore": 738.0, + "idle": 180.0 + }, + "unique_chunks_per_bot": { + "walk": 211.33, + "explore": 737.6, + "idle": 180.0 + }, + "resent": 0, + "pulled_back": 4524, + "moved_too_quickly": 324, + "moved_wrongly": 0, + "bots_joined": 25, + "bots_failed": [], + "tick_queries": 56 + }, + { + "server": "horizon", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 19.84, + "mspt": { + "average": 35.2, + "p50": 32.12, + "p95": 69.04, + "p99": 96.56 + }, + "mspt_worst_p99": 240.8, + "tps": 20.0, + "rss_mb": { + "mean": 1013.2, + "max": 1249.1 + }, + "cpu_percent": 217.68, + "chunks_per_second": 273.18, + "unique_per_second": 34.58, + "forgotten_per_second": 268.19, + "waited_ticks_per_second": 138.29, + "chunks_total": 115527, + "chunks_per_bot": { + "walk": 3300.1, + "explore": 1192.4, + "idle": 460.0 + }, + "unique_chunks_per_bot": { + "walk": 632.67, + "explore": 1186.9, + "idle": 460.0 + }, + "resent": 0, + "pulled_back": 8369, + "moved_too_quickly": 0, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + }, + { + "server": "vanilla", + "bots": 50, + "behaviour": "mixed", + "start_seconds": 20.58, + "mspt": { + "average": 29.74, + "p50": 23.6, + "p95": 62.25, + "p99": 137.41 + }, + "mspt_worst_p99": 489.3, + "tps": 20.0, + "rss_mb": { + "mean": 3995.71, + "max": 4597.8 + }, + "cpu_percent": 294.31, + "chunks_per_second": 94.36, + "unique_per_second": 17.76, + "forgotten_per_second": 94.69, + "waited_ticks_per_second": 101.48, + "chunks_total": 41637, + "chunks_per_bot": { + "walk": 1104.97, + "explore": 628.8, + "idle": 220.0 + }, + "unique_chunks_per_bot": { + "walk": 279.4, + "explore": 626.4, + "idle": 220.0 + }, + "resent": 0, + "pulled_back": 12034, + "moved_too_quickly": 2193, + "moved_wrongly": 0, + "bots_joined": 50, + "bots_failed": [], + "tick_queries": 57 + } + ], + "horizon_build": "v2026.10.18.15 release binaries (horizon-client, the engine, at 6c078b28); horizon-server from #898 (4ea2243e, the supervisor only)" +} \ No newline at end of file diff --git a/crates/horizon-client/Cargo.toml b/crates/horizon-client/Cargo.toml index ffccb88e8..82dca390d 100644 --- a/crates/horizon-client/Cargo.toml +++ b/crates/horizon-client/Cargo.toml @@ -31,7 +31,8 @@ toml = "1.1" naga = { version = "30.0.1", features = ["wgsl-in"] } # Java (OptiFine/Iris) shader packs, translated to WGSL. horizon-shaderpack = { path = "../horizon-shaderpack" } -cpal = "0.16" +# Sound (ALSA on Linux); the `audio` feature. +cpal = { version = "0.16", optional = true } symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] } miniz_oxide = "0.8" ab_glyph = "0.2.32" @@ -44,18 +45,28 @@ horizon-telemetry = { path = "../horizon-telemetry", default-features = false } horizon-bench = { path = "../horizon-bench" } arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] } zip = { version = "2", default-features = false, features = ["deflate"] } -# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input). -gilrs = "0.11" +# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input); the `controllers` feature. +gilrs = { version = "0.11", optional = true } # The DualSense's rumble, adaptive triggers and lights over HID (gilrs only reads it). -horizon-dualsense = { path = "../horizon-dualsense" } +horizon-dualsense = { path = "../horizon-dualsense", optional = true } # HTTPS to the Minecraft services (online-mode session join). ureq = { version = "2", default-features = false, features = ["tls"] } +[target.'cfg(unix)'.dependencies] +# The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs). +rustix = { version = "1", default-features = false, features = ["std", "time"] } + [target.'cfg(windows)'.build-dependencies] # The icon resource in the .exe (build.rs). winresource = "0.1" [features] +default = ["audio", "controllers"] +# Sound output. Without it (and `controllers`) the program links neither libasound nor libudev on +# Linux: the server build (`--no-default-features`, released as horizon-engine; docs/server.md). +audio = ["dep:cpal"] +# Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad. +controllers = ["dep:gilrs", "dep:horizon-dualsense"] # Records the call sites of mob random draws (`mob_ai_probe` traces). rng-trace = ["horizon-core/rng-trace"] diff --git a/crates/horizon-client/examples/arrow_probe.rs b/crates/horizon-client/examples/arrow_probe.rs index 20c0883e3..63ff2df32 100644 --- a/crates/horizon-client/examples/arrow_probe.rs +++ b/crates/horizon-client/examples/arrow_probe.rs @@ -58,11 +58,12 @@ fn main() -> Result<()> { let root = PathBuf::from(&args[0]); let dir = PathBuf::from(&args[1]); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; fs::write( dir.join("scene.json"), serde_json::to_vec( - &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}), + &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":render.model_gallery}), )?, )?; if args[2] == "--describe" { diff --git a/crates/horizon-client/examples/auto_jump_probe.rs b/crates/horizon-client/examples/auto_jump_probe.rs index e4a9848e8..d8dee95df 100644 --- a/crates/horizon-client/examples/auto_jump_probe.rs +++ b/crates/horizon-client/examples/auto_jump_probe.rs @@ -31,13 +31,14 @@ fn main() -> Result<()> { }; let root = PathBuf::from(root); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; let binding = collisions::load(&root, assets.registry)?; let resources = MotionResources::load(&root, &assets)?; fs::write( scene_json, serde_json::to_vec(&serde_json::json!({ - "radius": 1, "resident_chunks": scene.chunks.len(), "model_gallery": assets.model_gallery, + "radius": 1, "resident_chunks": scene.chunks.len(), "model_gallery": render.model_gallery, }))?, )?; let mut out = BufWriter::new(fs::File::create(output)?); diff --git a/crates/horizon-client/examples/block_particles_fixture.rs b/crates/horizon-client/examples/block_particles_fixture.rs index e9c207a7e..63ef242b7 100644 --- a/crates/horizon-client/examples/block_particles_fixture.rs +++ b/crates/horizon-client/examples/block_particles_fixture.rs @@ -12,9 +12,11 @@ fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let facts = BlockFacts::load(root, assets.registry)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(root, assets.registry)?, )?; diff --git a/crates/horizon-client/examples/breaking_fixture.rs b/crates/horizon-client/examples/breaking_fixture.rs index ec8f7a68b..2016fd613 100644 --- a/crates/horizon-client/examples/breaking_fixture.rs +++ b/crates/horizon-client/examples/breaking_fixture.rs @@ -18,9 +18,11 @@ fn main() -> Result<(), Box> { let args: Vec<_> = std::env::args().collect(); let root = Path::new(&args[1]); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let facts = BlockFacts::load(root, assets.registry)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(root, assets.registry)?, )?; @@ -33,7 +35,7 @@ fn main() -> Result<(), Box> { let mut vertices = Vec::new(); let mut translucent = false; if facts.get(state).render_shape == RenderShape::Model { - let models = assets + let models = render .model_catalog .collect(state, BlockPos::new(p[0], p[1], p[2]))?; let offset = tables.offset(state, p[0], p[2]).unwrap_or([0.0; 3]); diff --git a/crates/horizon-client/examples/chunk_bench.rs b/crates/horizon-client/examples/chunk_bench.rs index 6ad2cbd99..be619245f 100644 --- a/crates/horizon-client/examples/chunk_bench.rs +++ b/crates/horizon-client/examples/chunk_bench.rs @@ -31,10 +31,12 @@ fn main() -> Result<()> { }; let (seed, size) = (flag("--seed", 12345), flag("--size", 8) as i32); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; let biomes = Biomes::load(&root)?; let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(&root, assets.registry)?, )?; @@ -132,6 +134,7 @@ fn main() -> Result<()> { let mut mesher = Mesher { nether_shading: false, assets: &assets, + render: &render, tables: &tables, biomes: &biomes, visibility: tables.visibility.clone(), diff --git a/crates/horizon-client/examples/game_loop_probe.rs b/crates/horizon-client/examples/game_loop_probe.rs index 56da454d9..66a428162 100644 --- a/crates/horizon-client/examples/game_loop_probe.rs +++ b/crates/horizon-client/examples/game_loop_probe.rs @@ -233,22 +233,32 @@ fn mouse(c: &Value, out: &mut impl Write) -> Result<()> { fn scroll(c: &Value, out: &mut impl Write) -> Result<()> { let mut handler = MouseLook::default(); let mut slot = c["slot"].as_i64().unwrap() as i32; + let spectator = c["spectator"].as_bool().unwrap_or(false); + let mut speed = 0.05; // OptionInstance.set quantises the wheel sensitivity. let mut file = OptionsFile::default(); file.set("mouseWheelSensitivity", V::Double(db(&c["sens"]))); let sensitivity = file.double("mouseWheelSensitivity"); writeln!(out, "scroll")?; for op in c["ops"].as_array().unwrap() { - if let Some((wheel, _)) = + if let Some((wheel, (_, y))) = handler.on_scroll(db(&op[0]), db(&op[1]), b(&c["discrete"]), sensitivity) { - slot = horizon_client::mouse::ScrollWheelHandler::next_selection( - f64::from(wheel), - slot, - 9, - ); + if spectator { + speed = horizon_client::mouse::spectator_flying_speed(speed, y); + } else { + slot = horizon_client::mouse::ScrollWheelHandler::next_selection( + f64::from(wheel), + slot, + 9, + ); + } + } + if spectator { + writeln!(out, "{slot} {}", fb(speed))?; + } else { + writeln!(out, "{slot}")?; } - writeln!(out, "{slot}")?; } Ok(()) } diff --git a/crates/horizon-client/examples/interaction_input_fixture.rs b/crates/horizon-client/examples/interaction_input_fixture.rs new file mode 100644 index 000000000..bb408dd88 --- /dev/null +++ b/crates/horizon-client/examples/interaction_input_fixture.rs @@ -0,0 +1,122 @@ +use horizon_client::interaction_input::{ + Button, InteractionInput, InteractionWorld, TargetUseWorld, use_on_target, +}; +use serde_json::Value; +use std::io::{BufRead, Write}; + +struct World { + using: bool, + destroying: bool, + entity: bool, + dig_on_attack: bool, + begin_using: bool, + delay: u32, + events: Vec, + passing: bool, +} +impl InteractionWorld for World { + fn using_item(&self) -> bool { + self.using + } + fn release_using(&mut self) { + self.events.push("release".into()); + self.using = false; + } + fn start_attack(&mut self) -> bool { + self.events.push("attack".into()); + if !self.entity { + self.destroying = self.dig_on_attack; + } + false + } + fn start_use(&mut self) { + if self.destroying { + return; + } + self.delay = 4; + let entity = self.entity; + use_on_target(self, entity); + } + fn pick(&mut self) { + self.events.push("pick".into()); + } + fn use_delay(&self) -> u32 { + self.delay + } + fn continue_attack(&mut self, down: bool) { + if self.using { + return; + } + let down = down && !self.entity; + self.events.push(format!("continue {down}")); + if !down { + self.destroying = false; + } + } +} + +impl TargetUseWorld for World { + fn use_entity(&mut self) -> bool { + self.events + .push(if self.passing { "entity" } else { "use" }.into()); + if self.passing { + false + } else { + self.using = self.begin_using; + true + } + } + fn use_block(&mut self) -> bool { + self.events + .push(if self.passing { "block" } else { "use" }.into()); + if self.passing { + false + } else { + self.using = self.begin_using; + true + } + } + fn use_item(&mut self) { + self.events.push("item".into()); + self.using = self.begin_using; + } +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); + for (i, line) in input.lines().enumerate() { + let row: Value = serde_json::from_str(&line?)?; + let flag = |key: &str| row[key].as_bool().unwrap(); + let mut world = World { + using: flag("using"), + destroying: flag("destroying"), + entity: flag("entity"), + dig_on_attack: flag("dig_on_attack"), + begin_using: flag("begin_using"), + delay: row["delay"].as_u64().unwrap() as u32, + events: vec![], + passing: row["passing"].as_bool().unwrap_or(false), + }; + let mut input = InteractionInput::default(); + for button in row["clicks"].as_array().unwrap() { + input.press(match button.as_u64().unwrap() { + 0 => Button::Attack, + 1 => Button::Use, + _ => Button::Pick, + }); + } + input.tick(&mut world, flag("attack_down"), flag("use_down")); + writeln!(out, "== {i}")?; + for event in world.events { + writeln!(out, "{event}")?; + } + writeln!( + out, + "state {} {} {}", + world.using, world.destroying, world.delay + )?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/lan_flat.rs b/crates/horizon-client/examples/lan_flat.rs index 20d87e03c..283c3a22b 100644 --- a/crates/horizon-client/examples/lan_flat.rs +++ b/crates/horizon-client/examples/lan_flat.rs @@ -101,6 +101,8 @@ fn main() -> Result<(), Box> { sprinting: false, equipment: Default::default(), health: 20.0, + attributes: Vec::new(), + living_flags: 0, }; loop { world.game_time += 1; diff --git a/crates/horizon-client/examples/light_parity.rs b/crates/horizon-client/examples/light_parity.rs index 29488130e..f660189a2 100644 --- a/crates/horizon-client/examples/light_parity.rs +++ b/crates/horizon-client/examples/light_parity.rs @@ -206,7 +206,7 @@ fn incremental( sky_light: bool, edits: usize, ) { - use horizon_client::light::relight; + use horizon_client::light::{LightChanges, relight}; use std::sync::Arc; let mut world: HashMap<(i32, i32), Arc> = HashMap::new(); let inner: Vec<(i32, i32)> = { @@ -285,7 +285,14 @@ fn incremental( if old == state || !tables.differs(old, state) { continue; } - relight(&mut world, tables, sky_light, &[(x, y, z)], false); + relight( + &mut world, + tables, + sky_light, + &[(x, y, z)], + false, + &mut LightChanges::default(), + ); for dz in -1..=1 { for dx in -1..=1 { let (kx, kz) = (cx + dx, cz + dz); diff --git a/crates/horizon-client/examples/mob_ai_probe.rs b/crates/horizon-client/examples/mob_ai_probe.rs index 0b3adec31..2a4969221 100644 --- a/crates/horizon-client/examples/mob_ai_probe.rs +++ b/crates/horizon-client/examples/mob_ai_probe.rs @@ -1024,6 +1024,7 @@ fn main() -> horizon_client::Result<()> { collision: &collision, data: &data, player: player.clone(), + nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), others: $snapshot, others_grid: $grid, daylight: (world.day_time.rem_euclid(24000)) < 12000, diff --git a/crates/horizon-client/examples/model_library_bench.rs b/crates/horizon-client/examples/model_library_bench.rs index d3aba51e0..2089e39e1 100644 --- a/crates/horizon-client/examples/model_library_bench.rs +++ b/crates/horizon-client/examples/model_library_bench.rs @@ -56,10 +56,11 @@ fn main() -> horizon_client::Result<()> { let initial = LIVE.load(Relaxed); let start = Instant::now(); let assets = Assets::load(root)?; + let render = assets.reload(root)?; let block_ms = start.elapsed().as_secs_f64() * 1000.; let block_retained = LIVE.load(Relaxed) - initial; let start_items = Instant::now(); - let items = ItemRenderer::load_with_library(root, assets.model_library.clone())?; + let items = ItemRenderer::load_with_library(root, render.model_library.clone())?; let item_ms = start_items.elapsed().as_secs_f64() * 1000.; let total_ms = start.elapsed().as_secs_f64() * 1000.; let retained = LIVE.load(Relaxed) - initial; @@ -74,7 +75,7 @@ fn main() -> horizon_client::Result<()> { horizon_core::position::BlockPos::new(0, 0, 0), horizon_core::position::BlockPos::new(-17, 65, 31), ] { - if let Ok(selected) = assets.model_catalog.collect(id, pos) { + if let Ok(selected) = render.model_catalog.collect(id, pos) { for (variant, model) in selected { format!("{variant:?}").hash(&mut hash); model.ambient_occlusion.hash(&mut hash); diff --git a/crates/horizon-client/examples/player_sync_fixture.rs b/crates/horizon-client/examples/player_sync_fixture.rs new file mode 100644 index 000000000..b50a672af --- /dev/null +++ b/crates/horizon-client/examples/player_sync_fixture.rs @@ -0,0 +1,72 @@ +use horizon_client::player_sync::{PositionSender, teleport_velocity}; +use horizon_core::geometry::Vec3; +use horizon_protocol::packets::play::{PlayerPosition, Serverbound as S}; +use serde_json::Value; +use std::io::{BufRead, Write}; + +fn number(value: &Value) -> f64 { + f64::from_bits(u64::from_str_radix(value.as_str().unwrap(), 16).unwrap()) +} + +fn main() -> Result<(), Box> { + let args: Vec<_> = std::env::args().collect(); + let input = std::io::BufReader::new(std::fs::File::open(&args[1])?); + let mut out = std::io::BufWriter::new(std::fs::File::create(&args[2])?); + for line in input.lines() { + let row: Value = serde_json::from_str(&line?)?; + if row["kind"] == "movement" { + let mut sender = PositionSender::default(); + for op in row["ops"].as_array().unwrap() { + let pos = std::array::from_fn(|i| number(&op[i])); + let rot = (number(&op[3]) as f32, number(&op[4]) as f32); + if let Some(packet) = + sender.update(pos, rot, op[5].as_bool().unwrap(), op[6].as_bool().unwrap()) + { + let name = match packet { + S::MovePlayerPos(_) => "pos", + S::MovePlayerPosRot(_) => "posrot", + S::MovePlayerRot(_) => "rot", + S::MovePlayerStatus(_) => "status", + _ => unreachable!(), + }; + write!(out, "{name} ")?; + for byte in &packet.encode()[1..] { + write!(out, "{byte:02x}")?; + } + writeln!(out)?; + } else { + writeln!(out, "-")?; + } + } + } else { + let vector = |key: &str| { + Vec3::new( + number(&row[key][0]), + number(&row[key][1]), + number(&row[key][2]), + ) + }; + let rotation = |key: &str| (number(&row[key][0]) as f32, number(&row[key][1]) as f32); + let old = rotation("old"); + let new = rotation("new"); + let delta = vector("delta"); + let packet = PlayerPosition { + teleport: 0, + position: [0.0; 3], + delta: [delta.x, delta.y, delta.z], + yaw: new.0, + pitch: new.1, + relatives: row["flags"].as_i64().unwrap() as i32, + }; + let v = teleport_velocity(vector("velocity"), old, new, &packet); + writeln!( + out, + "{:016x} {:016x} {:016x}", + v.x.to_bits(), + v.y.to_bits(), + v.z.to_bits() + )?; + } + } + Ok(()) +} diff --git a/crates/horizon-client/examples/resource_memory.rs b/crates/horizon-client/examples/resource_memory.rs index 1eb6c45b7..0408b138b 100644 --- a/crates/horizon-client/examples/resource_memory.rs +++ b/crates/horizon-client/examples/resource_memory.rs @@ -94,12 +94,13 @@ fn main() -> Result<()> { drop(registry); step("registry dropped"); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; step("assets"); println!( " sprites: {} layers of {}px, {:.0} MB of pixels", - assets.texture_layers, - assets.sprite_size, - assets.pixels.len() as f64 / MB + render.texture_layers, + render.sprite_size, + render.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)?; @@ -114,6 +115,7 @@ fn main() -> Result<()> { step("light tables"); let tables = MeshTables::new( &assets, + &render, &facts, models::load_visibility(&root, assets.registry)?, )?; diff --git a/crates/horizon-client/examples/save_batch_bench.rs b/crates/horizon-client/examples/save_batch_bench.rs index 4ee5103de..d35ca8bbb 100644 --- a/crates/horizon-client/examples/save_batch_bench.rs +++ b/crates/horizon-client/examples/save_batch_bench.rs @@ -66,7 +66,6 @@ fn fixture(per_chunk: usize) -> (Vec>, Entities, Names) { for s in &mut template.sections[..8] { Arc::make_mut(s).blocks = PalettedContainer::new(block_strategy(), 1); } - template.heights = Arc::new([64; 256]); for i in 0..256 { let x = i % 16 - 8; let z = i / 16 - 8; diff --git a/crates/horizon-client/examples/save_bench.rs b/crates/horizon-client/examples/save_bench.rs new file mode 100644 index 000000000..2e3084290 --- /dev/null +++ b/crates/horizon-client/examples/save_bench.rs @@ -0,0 +1,128 @@ +//! The region writer on real chunks, without a window: how long a world's +//! chunks take to be encoded, compressed and written by `SaveDir`, against +//! the same encoding and compression done one chunk after another (what the +//! writer thread did alone before it had helpers). +//! +//! save_bench RESOURCES DIMENSION_DIR [--rounds N] +//! +//! DIMENSION_DIR is a saved dimension folder (`saves/W/dimensions/minecraft/ +//! overworld`); its chunks are read once, then each round saves them all into +//! a scratch folder with `save_later` + `flush`, and times the one-thread +//! baseline. The written chunks are checked byte for byte against the +//! baseline's compressed records. +use horizon_client::{ + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + save::{SaveDir, SaveTables, encode_with}, +}; +use horizon_core::position::ChunkPos; +use horizon_world::{ + compression::Compression, + nbt::Limits, + region::{ChunkRecord, RegionFile}, +}; +use std::{path::PathBuf, sync::Arc, time::Instant}; + +type Result = std::result::Result>; + +fn main() -> Result<()> { + let args: Vec = std::env::args().skip(1).collect(); + let usage = "usage: save_bench RESOURCES DIMENSION_DIR [--rounds N]"; + let root = PathBuf::from(args.first().ok_or(usage)?); + let dimension = PathBuf::from(args.get(1).ok_or(usage)?); + let rounds: usize = args + .iter() + .position(|a| a == "--rounds") + .and_then(|i| args.get(i + 1)) + .and_then(|v| v.parse().ok()) + .unwrap_or(5); + + let assets = Assets::load(&root)?; + let facts = BlockFacts::load(&root, assets.registry)?; + let biomes = Arc::new(Biomes::load(&root)?); + let tables = Arc::new(SaveTables::new(&assets).with_block_entities(&facts)); + let registry = assets.registry; + + let source = SaveDir::new(dimension.clone()); + let _ = source.tables.set(tables.clone()); + let mut chunks = Vec::new(); + for entry in std::fs::read_dir(dimension.join("region"))? { + let path = entry?.path(); + if path.extension().is_none_or(|e| e != "mca") { + continue; + } + let region = RegionFile::open(&path)?; + for (pos, _) in region.chunks() { + if let Some(chunk) = source.load(pos.x, pos.z, registry, &biomes) { + chunks.push(Arc::new(chunk)); + } + } + } + chunks.sort_by_key(|c| (c.x, c.z)); + println!("{} chunks from {}", chunks.len(), dimension.display()); + + let scratch = std::env::temp_dir().join(format!("save_bench_{}", std::process::id())); + // Encoding and compressing on one thread (what the writer did alone), + // then SaveDir's writer with its helpers. + let mut times = [Vec::new(), Vec::new(), Vec::new()]; + let mut written = Vec::new(); + for round in 0..rounds { + let started = Instant::now(); + let tags: Vec<_> = chunks + .iter() + .map(|c| encode_with(c, registry, &biomes, Some(&tables), true)) + .collect(); + times[0].push(started.elapsed().as_secs_f64()); + let started = Instant::now(); + let baseline: Vec = tags + .iter() + .map(|tag| ChunkRecord::from_nbt(tag, Compression::Zlib, 0, Limits::default())) + .collect::>()?; + times[1].push(started.elapsed().as_secs_f64()); + drop(tags); + + let _ = std::fs::remove_dir_all(&scratch); + let save = SaveDir::new(scratch.clone()); + let _ = save.tables.set(tables.clone()); + let started = Instant::now(); + save.save_later(&chunks, registry, &biomes)?; + save.flush(); + times[2].push(started.elapsed().as_secs_f64()); + drop(save); + + if round == 0 { + for (chunk, want) in chunks.iter().zip(&baseline) { + let path = scratch.join(format!("region/r.{}.{}.mca", chunk.x >> 5, chunk.z >> 5)); + let got = RegionFile::open(&path)? + .read(ChunkPos::new(chunk.x, chunk.z))? + .ok_or("a saved chunk is missing")?; + if got.compressed != want.compressed { + return Err(format!("chunk {} {} differs", chunk.x, chunk.z).into()); + } + } + written = baseline.iter().map(|r| r.compressed.len()).collect(); + } + } + let _ = std::fs::remove_dir_all(&scratch); + println!( + "{} KiB compressed, identical to the one-thread records", + written.iter().sum::() / 1024 + ); + let per_chunk = 1000.0 / chunks.len() as f64; + let names = [ + "one thread: encode", + "one thread: compress", + "SaveDir (encode, compress, write)", + ]; + for (name, t) in names.iter().zip(&mut times) { + t.sort_by(f64::total_cmp); + println!( + "{name}: best {:.0} ms, median {:.0} ms of {rounds} ({:.3} ms per chunk at best)", + t[0] * 1000.0, + t[t.len() / 2] * 1000.0, + t[0] * per_chunk + ); + } + Ok(()) +} diff --git a/crates/horizon-client/examples/scene_collision_probe.rs b/crates/horizon-client/examples/scene_collision_probe.rs index c1a1e77ad..ec20eee74 100644 --- a/crates/horizon-client/examples/scene_collision_probe.rs +++ b/crates/horizon-client/examples/scene_collision_probe.rs @@ -40,7 +40,8 @@ fn main() -> Result<()> { return Err("radius must be 1..16".into()); } let assets = assets::Assets::load(&resources)?; - let world = world::World::test_scene(&assets, radius)?; + let render = assets.reload(&resources)?; + let world = world::World::test_scene(&assets, &render, radius)?; let binding = collisions::load(&resources, assets.registry)?; let mut scene = collisions::SceneCollisions { world: &world, @@ -50,7 +51,7 @@ fn main() -> Result<()> { fs::write( dir.join("scene.json"), serde_json::to_vec(&serde_json::json!({ - "radius":radius,"resident_chunks":world.chunks.len(),"model_gallery":assets.model_gallery, + "radius":radius,"resident_chunks":world.chunks.len(),"model_gallery":render.model_gallery, }))?, )?; let mut output = std::io::BufWriter::new(fs::File::create(dir.join("rust.txt"))?); diff --git a/crates/horizon-client/examples/scene_motion_probe.rs b/crates/horizon-client/examples/scene_motion_probe.rs index 6caa51463..f4ff07ebf 100644 --- a/crates/horizon-client/examples/scene_motion_probe.rs +++ b/crates/horizon-client/examples/scene_motion_probe.rs @@ -243,13 +243,14 @@ fn main() -> Result<()> { let root = PathBuf::from(&args[0]); let dir = PathBuf::from(&args[1]); let assets = Assets::load(&root)?; - let mut scene = World::test_scene(&assets, 1)?; + let render = assets.reload(&root)?; + let mut scene = World::test_scene(&assets, &render, 1)?; let binding = collisions::load(&root, assets.registry)?; let resources = MotionResources::load(&root, &assets)?; fs::write( dir.join("scene.json"), serde_json::to_vec( - &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}), + &serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":render.model_gallery}), )?, )?; if args[2] == "--describe" { diff --git a/crates/horizon-client/examples/section_mesh_fixture.rs b/crates/horizon-client/examples/section_mesh_fixture.rs index 6359f32d0..13f1a0f1a 100644 --- a/crates/horizon-client/examples/section_mesh_fixture.rs +++ b/crates/horizon-client/examples/section_mesh_fixture.rs @@ -3,7 +3,7 @@ //! the oracle's canonical form (vanilla ARGB colours and packed light coords). #![forbid(unsafe_code)] use horizon_client::{ - assets::Assets, + assets::{Assets, RenderAssets}, biome::{BiomeInfo, Biomes, GrassModifier}, blocks::BlockFacts, chunk::{Chunk, Light, MIN_Y, index}, @@ -48,6 +48,7 @@ fn chunk_index(x: i32, z: i32) -> Result { fn scene( row: &Value, assets: &Assets, + render: &RenderAssets, tables: &MeshTables, biomes: &mut Biomes, pristine: &[BiomeInfo], @@ -127,6 +128,7 @@ fn scene( let mut mesher = Mesher { nether_shading: row["nether"].as_bool().unwrap_or(false), assets, + render, tables, biomes: &*biomes, visibility: tables.visibility.clone(), @@ -159,15 +161,8 @@ fn scene( let vertices: Vec = quad .iter() .map(|v| { - json!([ - v.pos[0], - v.pos[1], - v.pos[2], - v.uv[0], - v.uv[1], - argb(v.color), - light_coords(v.light) - ]) + let ([x, y, z], [u, w]) = (v.pos, v.uv()); + json!([x, y, z, u, w, argb(v.color), light_coords(v.light)]) }) .collect(); quads.push(json!({"layer": layer, "sprite": sprite, "vertices": vertices})); @@ -184,11 +179,12 @@ fn main() -> Result<()> { } let root = PathBuf::from(&args[0]); let assets = Assets::load(&root)?; + let render = assets.reload(&root)?; let facts = BlockFacts::load(&root, assets.registry)?; let mut biomes = Biomes::load(&root)?; let visibility = models::load_visibility(&root, assets.registry)?; - let tables = MeshTables::new(&assets, &facts, visibility)?; - let names: BTreeMap = assets + let tables = MeshTables::new(&assets, &render, &facts, visibility)?; + let names: BTreeMap = render .sprite_layers .iter() .map(|(name, layer)| (*layer, name.as_str())) @@ -222,6 +218,7 @@ fn main() -> Result<()> { let result = scene( &row, &assets, + &render, &tables, &mut biomes, &pristine, diff --git a/crates/horizon-client/examples/streaming_bench.rs b/crates/horizon-client/examples/streaming_bench.rs index f99c594bb..9f8e99899 100644 --- a/crates/horizon-client/examples/streaming_bench.rs +++ b/crates/horizon-client/examples/streaming_bench.rs @@ -144,10 +144,12 @@ fn main() -> Result<()> { let hz = flag("--hz", 240.0); let assets = Arc::new(Assets::load(&root)?); + let render = Arc::new(assets.reload(&root)?); let facts = BlockFacts::load(&root, assets.registry)?; let biomes = Arc::new(Biomes::load(&root)?); let tables = Arc::new(MeshTables::new( &assets, + &render, &facts, models::load_visibility(&root, assets.registry)?, )?); @@ -160,6 +162,7 @@ fn main() -> Result<()> { )?); let context = Arc::new(WorkerContext { assets, + render: render.clone(), tables, biomes, light, diff --git a/crates/horizon-client/src/assets.rs b/crates/horizon-client/src/assets.rs index c42f0aaf7..3e7c6e909 100644 --- a/crates/horizon-client/src/assets.rs +++ b/crates/horizon-client/src/assets.rs @@ -48,11 +48,20 @@ impl TerrainBlockStates for Properties { self.0[id.0 as usize] } } +/// The block registry and the facts read from `facts.json` and the block tags: +/// everything world generation and collisions need, with none of the block +/// models or baked sprites. pub struct Assets { /// Leaked once per process: shared by world generation threads. pub registry: &'static BlockRegistry, pub properties: Properties, pub material_states: [BlockStateId; 6], + /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). + pub blocks_fluid_flow: BTreeSet, +} +/// The block models and their baked sprites, read from the pack at `root` over +/// an existing block registry: everything the mesher and renderer need. +pub struct RenderAssets { pub sprite_size: u32, pub sprite_minimum_size: u32, pub pixels: Vec, @@ -67,8 +76,6 @@ pub struct Assets { pub translucent_layers: Vec, /// Each layer's `MipmapGenerator` settings. pub sprite_mips: Vec, - /// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors). - pub blocks_fluid_flow: BTreeSet, } fn invalid(message: &str) -> io::Error { io::Error::new(io::ErrorKind::InvalidData, message) @@ -152,33 +159,23 @@ impl Assets { // 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, + Ok(Self { registry, properties, material_states, blocks_fluid_flow, - ) + }) } - /// The same blocks with the models and sprites of another resource root + /// The models and sprites of another resource root over these blocks /// (resource packs changed): the registry and block facts come from the /// game data, which resource packs do not touch. - pub fn reload(&self, root: &Path) -> Result { - Self::with_models( - root, - self.registry, - self.properties.clone(), - self.material_states, - self.blocks_fluid_flow.clone(), - ) + pub fn reload(&self, root: &Path) -> Result { + RenderAssets::load(root, self) } - fn with_models( - root: &Path, - registry: &'static BlockRegistry, - properties: Properties, - material_states: [BlockStateId; 6], - blocks_fluid_flow: BTreeSet, - ) -> Result { +} +impl RenderAssets { + pub fn load(root: &Path, assets: &Assets) -> Result { + let registry = assets.registry; let mut sprites = crate::sprites::Sprites::default(); for name in MATERIALS { sprites.insert(root, &format!("minecraft:block/{name}"))?; @@ -202,9 +199,6 @@ impl Assets { } sprites.finish(); Ok(Self { - registry, - properties, - material_states, sprite_size: sprites.size, sprite_minimum_size: sprites.minimum_size, texture_layers: u32::try_from(sprites.count())?, @@ -217,7 +211,6 @@ impl Assets { sprite_layers: sprites.layers, translucent_layers: sprites.translucent, sprite_mips: sprites.mips, - blocks_fluid_flow, }) } } diff --git a/crates/horizon-client/src/audio.rs b/crates/horizon-client/src/audio.rs index 0c45fa934..250babf22 100644 --- a/crates/horizon-client/src/audio.rs +++ b/crates/horizon-client/src/audio.rs @@ -9,6 +9,7 @@ use crate::sound_engine::{ Sounds, TickContext, }; use crate::sound_events::{Sound, SoundRegistry}; +#[cfg(feature = "audio")] use cpal::traits::{DeviceTrait, HostTrait, StreamTrait}; use horizon_core::random::{LegacyRandom, RandomSource}; use std::{ @@ -134,8 +135,14 @@ fn attach(mixer: &Mutex, channel: ChannelId, samples: Samples, looping: b c.looping |= looping; } } +/// The open output stream. A build without the `audio` feature (the server build, which must not +/// need libasound) never has one. +#[cfg(feature = "audio")] +type Stream = cpal::Stream; +#[cfg(not(feature = "audio"))] +type Stream = std::convert::Infallible; pub struct Audio { - _stream: Option, + _stream: Option, pub engine: SoundEngine, backend: MixerBackend, /// Record `Heard` sounds (the subtitle overlay is listening). @@ -333,6 +340,8 @@ fn distance_gain(linear: Option, distance: f32) -> f32 { Some(_) => 0.0, } } +// Only the output stream mixes; a build without one (no `audio` feature) never does. +#[cfg_attr(not(feature = "audio"), allow(dead_code))] fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { data.fill(0.0); let listener = mixer.listener; @@ -415,6 +424,7 @@ fn mix(mixer: &mut Mixer, data: &mut [f32], channels: usize, rate: u32) { /// `HORIZON_NO_AUDIO`, or a virtual screen (`vscreen`), where agents and /// harnesses run the game and must stay off the user's speakers. /// `HORIZON_AUDIO=1` opens the output anyway (testing into a null sink). +#[cfg(any(feature = "audio", test))] fn output_disabled(var: impl Fn(&str) -> Option) -> Option { if var("HORIZON_NO_AUDIO").is_some() { return Some("audio off: HORIZON_NO_AUDIO is set".into()); @@ -430,6 +440,7 @@ fn output_disabled(var: impl Fn(&str) -> Option) -> Option>, @@ -450,6 +461,7 @@ fn open_device( stream.play()?; Ok((stream, config)) } +#[cfg(feature = "audio")] fn build_stream>( device: &cpal::Device, config: &cpal::SupportedStreamConfig, @@ -523,7 +535,12 @@ impl Audio { capture: None, } } - fn open(mixer: Arc>) -> Result { + #[cfg(not(feature = "audio"))] + fn open(_: Arc>) -> Result { + Err("this build has no sound output (built without the `audio` feature)".into()) + } + #[cfg(feature = "audio")] + fn open(mixer: Arc>) -> Result { if let Some(reason) = output_disabled(|name| std::env::var_os(name)) { return Err(reason.into()); } diff --git a/crates/horizon-client/src/bin/horizon-ctl/commands.rs b/crates/horizon-client/src/bin/horizon-ctl/commands.rs index 3e47a0545..8f64705c6 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/commands.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/commands.rs @@ -343,7 +343,7 @@ pub const COMMANDS: &[Cmd] = &[ cmd!("bench", Scripting, "bench SECONDS", "reset frame stats, wait, reply with the summary", "", ["horizon-ctl bench 10"], &[], mcp: false, local: false), cmd!("stats", Scripting, "stats [reset]", "frame-time summary since the last reset", "", ["horizon-ctl stats"], &[], mcp: false, local: false), cmd!("fly", Scripting, "fly X1 Y1 Z1 X2 Y2 Z2 SECONDS [PITCH [raw]]", "fly the camera along a line, then reply with the frame summary", - "With raw, the reply also lists every frame time in milliseconds (frame_ms).", + "The reply's tick_ms and tick_ms_max are the world's smoothed tick time over the flight (the server thread's when single player runs on one). With raw, the reply also lists every frame time in milliseconds (frame_ms).", ["horizon-ctl fly 0 100 0 500 100 0 20"], &[], mcp: false, local: false), ]; diff --git a/crates/horizon-client/src/bin/horizon-ctl/main.rs b/crates/horizon-client/src/bin/horizon-ctl/main.rs index 2e1b1bb56..27d9d5ba1 100644 --- a/crates/horizon-client/src/bin/horizon-ctl/main.rs +++ b/crates/horizon-client/src/bin/horizon-ctl/main.rs @@ -215,7 +215,12 @@ impl Session { let deadline = Instant::now() + Duration::from_secs_f64(limit.max(0.0)); loop { let status = self.game("status")?; - if !status["player"].is_null() && status["pending_chunks"] == 0 { + // On a server (single player's server thread too), also the + // level around the player. + if !status["player"].is_null() + && status["pending_chunks"] == 0 + && status["server"]["loaded"] != false + { return Ok(status); } if Instant::now() > deadline { diff --git a/crates/horizon-client/src/chunk.rs b/crates/horizon-client/src/chunk.rs index ce2c4ea71..857372045 100644 --- a/crates/horizon-client/src/chunk.rs +++ b/crates/horizon-client/src/chunk.rs @@ -3,7 +3,7 @@ //! (copy-on-write through `Arc::make_mut`). use horizon_core::paletted::{PalettedContainer, Strategy}; use horizon_world::registry::BlockStateId; -use std::sync::Arc; +use std::sync::{Arc, OnceLock}; pub const MIN_Y: i32 = -64; pub const HEIGHT: i32 = 384; @@ -45,6 +45,10 @@ impl Light { } } #[inline] +fn column(x: i32, z: i32) -> usize { + ((z & 15) << 4 | (x & 15)) as usize +} +#[inline] pub fn index(x: i32, y: i32, z: i32) -> usize { ((y & 15) << 8 | (z & 15) << 4 | (x & 15)) as usize } @@ -118,8 +122,10 @@ pub struct Chunk { pub x: i32, pub z: i32, pub sections: Vec>, - /// Highest non-air, light-blocking-or-fluid Y per column (MOTION_BLOCKING-like), for rain/sky. - pub heights: Arc<[i16; 256]>, + /// `Heightmap.Types.WORLD_SURFACE` per column (`z << 4 | x`): one above + /// the highest non-air block, or `MIN_Y`. Built on the first read; a + /// `set` that can move a column's surface drops it. + surface: OnceLock>, pub lit: bool, /// Light read from a save with `isLightOn`: no light job is needed. pub light_loaded: bool, @@ -148,7 +154,7 @@ impl Chunk { sections: (0..SECTIONS) .map(|_| Arc::new(Section::default())) .collect(), - heights: Arc::new([MIN_Y as i16; 256]), + surface: OnceLock::new(), lit: false, light_loaded: false, fresh: false, @@ -190,7 +196,52 @@ impl Chunk { if !(0..SECTIONS as i32).contains(&s) { return v; } - Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v) + let previous = Arc::make_mut(&mut self.sections[s as usize]).set(index(x, y, z), v); + // `Heightmap.update`: a write two or more below the surface can't + // move it. Any other change rebuilds the map on the next read. + if previous != v + && let Some(surface) = self.surface.get() + && y >= i32::from(surface[column(x, z)]) - 1 + { + self.surface = OnceLock::new(); + } + previous + } + /// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)` (`x`, `z` within the + /// chunk): one above the highest block that isn't `air`, or `MIN_Y`. + /// Sections must change only through `set` once this has been read. + pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(u32) -> bool) -> i32 { + let surface = self.surface.get_or_init(|| self.prime_surface(air)); + i32::from(surface[column(x, z)]) + } + /// `Heightmap.primeHeightmaps` for WORLD_SURFACE: each section from the + /// top, skipping those of one air state, until every column is found. + fn prime_surface(&self, air: impl Fn(u32) -> bool) -> Box<[i16; 256]> { + let mut surface = Box::new([MIN_Y as i16; 256]); + let mut found = [false; 256]; + let mut left = 256; + let mut values = [0u32; 4096]; + for (s, section) in self.sections.iter().enumerate().rev() { + if left == 0 { + break; + } + if section.blocks.uniform().is_some_and(&air) { + continue; + } + section.unpack(&mut values); + let base = MIN_Y + s as i32 * 16; + for i in 0..256 { + if found[i] { + continue; + } + if let Some(dy) = (0..16).rev().find(|&dy| !air(values[dy << 8 | i])) { + surface[i] = (base + dy as i32 + 1) as i16; + found[i] = true; + left -= 1; + } + } + } + surface } #[inline] pub fn light(&self, x: i32, y: i32, z: i32) -> u8 { @@ -261,4 +312,50 @@ mod tests { ); assert_eq!(Chunk::empty(0, 0).highest(air, |_| unreachable!()), None); } + /// The kept WORLD_SURFACE heights match a scan of every column after + /// each of a few thousand writes (air, cave air, stone, whole sections). + #[test] + fn world_surface_follows_writes() { + let (air, cave_air, stone) = (0, 7, 1); + let is_air = |v: u32| v == air || v == cave_air; + let scan = |c: &Chunk, x: i32, z: i32| { + (MIN_Y..MIN_Y + HEIGHT) + .rev() + .find(|&y| !is_air(c.get(x, y, z))) + .map_or(MIN_Y, |y| y + 1) + }; + let mut chunk = Chunk::empty(0, 0); + assert_eq!(chunk.world_surface(5, 5, is_air), MIN_Y); + for y in MIN_Y..MIN_Y + 70 { + for i in 0..256 { + chunk.set(i & 15, y, i >> 4, stone); + } + } + for i in 0..4096 { + Arc::make_mut(&mut chunk.sections[8]).set(i, cave_air); + } + let mut random = horizon_core::random::LegacyRandom::new(9); + use horizon_core::random::RandomSource; + for step in 0..4000 { + let x = random.next_int_bound(16).unwrap(); + let z = random.next_int_bound(16).unwrap(); + let y = MIN_Y + 40 + random.next_int_bound(120).unwrap(); + let v = [air, cave_air, stone][random.next_int_bound(3).unwrap() as usize]; + chunk.set(x, y, z, v); + if step % 7 == 0 { + for i in 0..256 { + assert_eq!( + chunk.world_surface(i & 15, i >> 4, is_air), + scan(&chunk, i & 15, i >> 4) + ); + } + } + } + // Out-of-range writes and unchanged states keep the map. + let before = chunk.world_surface(3, 3, is_air); + chunk.set(3, MIN_Y + HEIGHT, 3, stone); + chunk.set(3, before - 1, 3, chunk.get(3, before - 1, 3)); + assert!(chunk.surface.get().is_some()); + assert_eq!(chunk.world_surface(3, 3, |_| unreachable!()), before); + } } diff --git a/crates/horizon-client/src/effects.rs b/crates/horizon-client/src/effects.rs index a258ccf3a..17dce93ab 100644 --- a/crates/horizon-client/src/effects.rs +++ b/crates/horizon-client/src/effects.rs @@ -336,73 +336,8 @@ impl PlayerEffects { pub fn modifiers(&self) -> Vec<(&'static str, &'static str, f64, &'static str)> { let mut out = Vec::new(); for e in &self.list { - let level = f64::from(e.amplifier + 1); - let m = match e.id { - "speed" => Some(( - "minecraft:movement_speed", - "minecraft:effect.speed", - 0.2, - "add_multiplied_total", - )), - "slowness" => Some(( - "minecraft:movement_speed", - "minecraft:effect.slowness", - -0.15, - "add_multiplied_total", - )), - "haste" => Some(( - "minecraft:attack_speed", - "minecraft:effect.haste", - 0.1, - "add_multiplied_total", - )), - "mining_fatigue" => Some(( - "minecraft:attack_speed", - "minecraft:effect.mining_fatigue", - -0.1, - "add_multiplied_total", - )), - "strength" => Some(( - "minecraft:attack_damage", - "minecraft:effect.strength", - 3.0, - "add_value", - )), - "weakness" => Some(( - "minecraft:attack_damage", - "minecraft:effect.weakness", - -4.0, - "add_value", - )), - "jump_boost" => Some(( - "minecraft:safe_fall_distance", - "minecraft:effect.jump_boost", - 1.0, - "add_value", - )), - "health_boost" => Some(( - "minecraft:max_health", - "minecraft:effect.health_boost", - 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", - "minecraft:effect.unluck", - -1.0, - "add_value", - )), - _ => None, - }; - if let Some((a, id, amount, op)) = m { - out.push((a, id, amount * level, op)); + if let Some((a, id, amount, op)) = effect_modifier(e.id) { + out.push((a, id, amount * f64::from(e.amplifier + 1), op)); } } out @@ -445,6 +380,76 @@ impl StatusFlags { } } +/// The attribute modifier an effect adds at amplifier 0 +/// (`MobEffect.addAttributeModifier`): (attribute, id, amount, operation). +/// Each level multiplies the amount (`amplifier + 1`). +pub fn effect_modifier(effect: &str) -> Option<(&'static str, &'static str, f64, &'static str)> { + match effect { + "speed" => Some(( + "minecraft:movement_speed", + "minecraft:effect.speed", + 0.2, + "add_multiplied_total", + )), + "slowness" => Some(( + "minecraft:movement_speed", + "minecraft:effect.slowness", + -0.15, + "add_multiplied_total", + )), + "haste" => Some(( + "minecraft:attack_speed", + "minecraft:effect.haste", + 0.1, + "add_multiplied_total", + )), + "mining_fatigue" => Some(( + "minecraft:attack_speed", + "minecraft:effect.mining_fatigue", + -0.1, + "add_multiplied_total", + )), + "strength" => Some(( + "minecraft:attack_damage", + "minecraft:effect.strength", + 3.0, + "add_value", + )), + "weakness" => Some(( + "minecraft:attack_damage", + "minecraft:effect.weakness", + -4.0, + "add_value", + )), + "jump_boost" => Some(( + "minecraft:safe_fall_distance", + "minecraft:effect.jump_boost", + 1.0, + "add_value", + )), + "health_boost" => Some(( + "minecraft:max_health", + "minecraft:effect.health_boost", + 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", + "minecraft:effect.unluck", + -1.0, + "add_value", + )), + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/entities.rs b/crates/horizon-client/src/entities.rs index 5c905ac54..b9c8ee896 100644 --- a/crates/horizon-client/src/entities.rs +++ b/crates/horizon-client/src/entities.rs @@ -602,9 +602,10 @@ mod fire_environment_tests { return; } let assets = crate::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let items = crate::items::Items::load(&root, assets.registry, &facts).unwrap(); - let mut world = World::test_scene(&assets, 3).unwrap(); + let mut world = World::test_scene(&assets, &render, 3).unwrap(); let at = Vec3::new(20.5, 4.0, 20.5); world .set( diff --git a/crates/horizon-client/src/entity_nbt.rs b/crates/horizon-client/src/entity_nbt.rs index d627dc363..ee86211a1 100644 --- a/crates/horizon-client/src/entity_nbt.rs +++ b/crates/horizon-client/src/entity_nbt.rs @@ -840,9 +840,12 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap>, id: u32) - m.species(), crate::mobs::Species::Slime | crate::mobs::Species::MagmaCube ) { - let health = m.health; + // AbstractCubeMob.readAdditionalSaveData: the size's attributes, then + // the saved health, the max health when there is none. crate::mobs::cube::set_size(&mut m, number(tag.get("Size")).unwrap_or(0) as i32 + 1); - m.health = health; + if let Some(h) = float(tag.get("Health")) { + m.health = h as f32; + } m.extra.flag2 = flag(tag, "wasOnGround"); } // Zombie, Piglin and Zoglin.readAdditionalSaveData: IsBaby (the baby diff --git a/crates/horizon-client/src/fog.rs b/crates/horizon-client/src/fog.rs index 83f1a8bf5..4e29aeae9 100644 --- a/crates/horizon-client/src/fog.rs +++ b/crates/horizon-client/src/fog.rs @@ -32,6 +32,7 @@ pub struct FogData { } /// Per-biome water fog end multipliers (`visual/water_fog_end_distance`). +#[derive(Default)] pub struct FogTables { water_fog_end: Vec, } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 68058cbeb..bc818fe44 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -25,6 +25,7 @@ mod command_blocks; mod command_harness; mod commands; mod composter; +mod consume; mod control; mod copper_golems; mod creaking; @@ -64,6 +65,7 @@ mod item_particles; mod jukebox; mod lan; mod lan_actions; +mod lan_attributes; mod lan_chat; mod lan_crafting; mod lan_entities; @@ -126,6 +128,7 @@ mod sign_edit; mod sniffers; mod spawner; mod spill; +mod startup_menu; mod station_control; mod stations; mod stats; @@ -151,7 +154,7 @@ mod wither; mod zombie_villagers; use horizon_client::{ Result, - assets::Assets, + assets::{Assets, RenderAssets}, audio::Audio, biome::Biomes, blocks::{BlockFacts, Fluid}, @@ -460,6 +463,8 @@ struct GameLevel<'w> { raining: bool, thundering: bool, player_box: Option<([f64; 3], [f64; 3])>, + /// The LAN guests in this level who trigger blocks (not spectators). + guest_boxes: Vec<([f64; 3], [f64; 3])>, player_collision: Option, /// Minecart boxes (detector rails). cart_boxes: Vec<([f64; 3], [f64; 3])>, @@ -475,6 +480,8 @@ struct GameLevel<'w> { rand_sequences: &'w mut horizon_client::random_sequences::RandomSequences, pending: &'w mut spill::Pending, spill: &'w mut spill::Spill, + /// Where the chunk tickets let blocks tick. + tickets: horizon_client::ticket_levels::Levels, } struct PlayerCollision { y: f64, @@ -503,6 +510,9 @@ impl EntityObstructionWorld for PlayerObstruction { } } impl LevelAccess for GameLevel<'_> { + fn world_surface(&self, x: i32, z: i32) -> i32 { + self.world.world_surface(x, z, |s| self.facts.is_air(s)) + } fn precipitation(&self, pos: BlockPos) -> Option { self.behaviours.precipitation_info(self, pos) } @@ -672,8 +682,13 @@ impl LevelAccess for GameLevel<'_> { ) .unwrap_or(false) } + /// `ServerLevel.isPositionTickingWithEntitiesLoaded`: block ticking, and + /// a ticking chunk. + fn is_ticking_chunk(&self, chunk: horizon_core::position::ChunkPos) -> bool { + self.tickets.block_ticking(chunk.x, chunk.z) && ticking_chunk(self.world, chunk.x, chunk.z) + } /// Entities that trigger pressure plates, tripwires and detector rails: - /// the player (a mob) and the minecarts. + /// the players (the host and the LAN guests, mobs) and the minecarts. fn count_entities(&self, area: Aabb, query: EntityQuery) -> usize { let hit = |(lo, hi): &([f64; 3], [f64; 3])| { area.intersects(Aabb::new( @@ -682,10 +697,17 @@ impl LevelAccess for GameLevel<'_> { )) }; let carts = || self.cart_boxes.iter().filter(|b| hit(b)).count(); + let players = || { + self.player_box + .iter() + .chain(&self.guest_boxes) + .filter(|b| hit(b)) + .count() + }; match query { EntityQuery::Minecart => carts(), - EntityQuery::Mobs => self.player_box.iter().filter(|b| hit(b)).count(), - EntityQuery::Everything => self.player_box.iter().filter(|b| hit(b)).count() + carts(), + EntityQuery::Mobs => players(), + EntityQuery::Everything => players() + carts(), } } fn emit(&mut self, event: LevelEvent) { @@ -748,12 +770,23 @@ struct FallingBlock { /// recipes, biomes, mobs, collision and motion. Read-only and `Send + Sync`, /// so the client and an integrated server thread can share one copy. pub struct Resources { + core: WorldCore, + rest: std::sync::OnceLock, +} + +struct WorldCore { facts: BlockFacts, + biomes: Arc, + environment: Environment, + collision: BlockCollisionRegistry<'static>, + motion: MotionResources, + threads: usize, +} + +struct WorldRest { items: Items, recipes: Recipes, transformers: horizon_client::block_transform::Transformers, - biomes: Arc, - environment: Environment, mob_types: HashMap>, mob_data: horizon_client::mobs::MobData, providers: Providers, @@ -765,14 +798,105 @@ pub struct Resources { nether_environment: Environment, end_environment: Environment, behaviours: Behaviours, - collision: BlockCollisionRegistry<'static>, - motion: MotionResources, - threads: usize, player_arm: Option, player_type: Option>, - /// Enchantments, workstation recipes and brewing (game/stations.rs). stations: horizon_client::stations::StationData, } + +impl Resources { + fn rest(&self) -> &WorldRest { + self.rest + .get() + .expect("world resources joined before entry") + } + fn facts(&self) -> &BlockFacts { + &self.core.facts + } + fn items(&self) -> &Items { + &self.rest().items + } + fn recipes(&self) -> &Recipes { + &self.rest().recipes + } + fn transformers(&self) -> &horizon_client::block_transform::Transformers { + &self.rest().transformers + } + fn biomes(&self) -> &Arc { + &self.core.biomes + } + fn environment(&self) -> &Environment { + &self.core.environment + } + fn mob_types(&self) -> &HashMap> { + &self.rest().mob_types + } + fn mob_data(&self) -> &horizon_client::mobs::MobData { + &self.rest().mob_data + } + fn providers(&self) -> &Providers { + &self.rest().providers + } + fn block_entity_render(&self) -> &horizon_client::block_entity_render::BlockEntityRenderer { + &self.rest().block_entity_render + } + fn animate(&self) -> &horizon_client::animate_tick::AnimateTables { + &self.rest().animate + } + fn fog(&self) -> &horizon_client::fog::FogTables { + &self.rest().fog + } + fn music(&self) -> &horizon_client::music::MusicTables { + &self.rest().music + } + fn ambient(&self) -> &horizon_client::ambience::AmbientTables { + &self.rest().ambient + } + fn nether_environment(&self) -> &Environment { + &self.rest().nether_environment + } + fn end_environment(&self) -> &Environment { + &self.rest().end_environment + } + fn behaviours(&self) -> &Behaviours { + &self.rest().behaviours + } + fn collision(&self) -> &BlockCollisionRegistry<'static> { + &self.core.collision + } + fn motion(&self) -> &MotionResources { + &self.core.motion + } + fn threads(&self) -> usize { + self.core.threads + } + fn player_arm(&self) -> &Option { + &self.rest().player_arm + } + fn player_type(&self) -> &Option> { + &self.rest().player_type + } + fn stations(&self) -> &horizon_client::stations::StationData { + &self.rest().stations + } +} + +/// Everything the title and menus draw: the GUI atlas with its font and the +/// title panorama. Kept apart from the world bundle so the title can appear +/// before the block sprites, models and gameplay tables are ready. +pub struct UiResources { + /// The GUI, font, particle, map and skin atlas. + pub atlas: HudAtlas, + /// The title screen's panorama faces. + pub panorama: Arc, +} +impl UiResources { + pub fn load(root: &std::path::Path) -> Result { + Ok(Self { + atlas: HudAtlas::build(root)?, + panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + }) + } +} /// What a resource pack reload replaces (`Minecraft.reloadResourcePacks`): /// block models and sprites with their meshing tables, item models, /// translations and the textures read on the CPU. Each game holds its own; @@ -780,9 +904,9 @@ pub struct Resources { #[derive(Clone)] pub struct PackResources { assets: Arc, + render: Arc, context: Arc, layer_names: Arc>, - panorama: Arc, /// Item definitions, baked item models and special renderers. item_renderer: Arc, names: Arc, @@ -792,23 +916,25 @@ pub struct PackResources { forcefield: Arc<(u32, u32, Vec)>, } impl PackResources { - /// Everything a pack overlay at `root` provides, over `assets` loaded from it. + /// Everything a pack overlay at `root` provides, over `assets` and `render` + /// loaded from it. fn load( root: &std::path::Path, assets: Arc, + render: Arc, facts: &BlockFacts, biomes: Arc, light: Arc, ) -> Result { let visibility = models::load_visibility(root, assets.registry)?; - let tables = Arc::new(MeshTables::new(&assets, facts, visibility)?); + let tables = Arc::new(MeshTables::new(&assets, &render, facts, visibility)?); let item_renderer = horizon_client::item_render::ItemRenderer::load_with_library( root, - assets.model_library.clone(), + render.model_library.clone(), )?; Ok(Self { layer_names: Arc::new( - assets + render .sprite_layers .iter() .map(|(name, layer)| (*layer, name.trim_start_matches("minecraft:").to_owned())) @@ -816,12 +942,13 @@ impl PackResources { ), context: Arc::new(WorkerContext { assets: assets.clone(), + render: render.clone(), tables, biomes, light, }), assets, - panorama: Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + render, item_renderer: Arc::new(item_renderer), names: Arc::new(Names::load(root)), clouds: Arc::new(load_clouds(root)), @@ -836,6 +963,12 @@ struct DragView { left: Option, } /// Ctrl+Q reads the physical keyboard, independently of sprint key mappings. +/// A chunk whose ticking future can complete (`ChunkMap.prepareTickingChunk`): +/// lit, with its neighbours loaded, as `postprocess_chunks` waits for. +fn ticking_chunk(world: &World, x: i32, z: i32) -> bool { + world.chunks.get(&(x, z)).is_some_and(|c| c.lit) + && (-1..=1).all(|dz| (-1..=1).all(|dx| world.chunks.contains_key(&(x + dx, z + dz)))) +} fn drop_whole_stack(physical_keys: &HashSet) -> bool { physical_keys.contains(&KeyCode::ControlLeft) || physical_keys.contains(&KeyCode::ControlRight) } @@ -854,12 +987,16 @@ fn select_creative_tab( struct Game<'a> { /// Shared with an integrated server; `collision` and `motion` borrow from it. res: Arc, + rest_loader: Option, + pending_entry: Option, + pending_pack_reload: bool, + world_renderer_ready: bool, collision: &'a BlockCollisionRegistry<'a>, motion: &'a MotionResources, /// This game's resource packs (`reload_packs` replaces them). pack: PackResources, - /// The GUI, font, particle, map and skin atlas. - atlas: HudAtlas, + /// The title and menu bundle (GUI atlas, font and panorama). + gui: UiResources, /// `FogRenderer`'s evolving state. fog: horizon_client::fog::FogState, screen_fx: horizon_client::screen_effects::ScreenEffects, @@ -1084,6 +1221,7 @@ struct Game<'a> { end: end::EndState, block_ticks: Ticks, tick_chunks: horizon_client::tick_chunk_membership::TickChunkMembership, + tickets: horizon_client::ticket_levels::ChunkTickets, random_tick_sections: horizon_client::random_tick_sections::RandomTickSections, level_events: Vec, falling: Vec, @@ -1290,6 +1428,21 @@ impl Dim { _ => Self::Overworld, } } + /// `Level.getMinY`: the dimension type's minimum y. + fn min_y(self) -> i32 { + match self { + Self::Overworld => MIN_Y, + Self::Nether | Self::End => 0, + } + } + /// `DimensionType.logicalHeight`. + fn logical_height(self) -> i32 { + match self { + Self::Overworld => HEIGHT, + Self::Nether => 128, + Self::End => 256, + } + } /// `Level.getMaxY`: the dimension type's minimum y plus height, less one. fn max_y(self) -> i32 { match self { @@ -1348,7 +1501,7 @@ impl Game<'_> { /// A block's outline boxes in world space (`getShape` plus the random offset). fn outline_boxes(&self, pos: [i32; 3]) -> Vec<[f64; 6]> { let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let o = if f.outline_offset { self.pack .context @@ -1410,8 +1563,8 @@ impl Game<'_> { let mut t = 0.0; while t <= reach { let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); - if !self.res.facts.is_air(state) + let f = self.res.facts().get(state); + if !self.res.facts().is_air(state) && !(f.fluid != Fluid::None && !f.waterlogged && &*f.name != "minecraft:kelp" @@ -1513,7 +1666,11 @@ impl Game<'_> { } /// Inventory.add: returns the stack that did not fit. fn give(&mut self, mut stack: ItemStack) -> Option { - let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + let max = self + .res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack); // Prefer the selected slot, then the hotbar, then the main inventory. let order: Vec = std::iter::once(self.selected) .chain((0..36).filter(|&i| i != self.selected)) @@ -1549,7 +1706,7 @@ impl Game<'_> { fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { let models = self .pack - .assets + .render .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) .ok()?; @@ -1564,7 +1721,7 @@ impl Game<'_> { .or_else(|| models.iter().find_map(|(_, model)| model.particle))?; let name = self.pack.layer_names.get(&layer)?.clone(); let tint = if face.is_some_and(|face| face.quad.tint_index >= 0) { - let n = &self.res.facts.get(state).name; + let n = &self.res.facts().get(state).name; if n.contains("leaves") || n.contains("vine") { 0x48B518 } else { @@ -1576,7 +1733,7 @@ impl Game<'_> { Some((name, tint)) } fn particle_shape(&self, pos: [i32; 3], state: BlockStateId) -> Vec<[f64; 6]> { - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let offset = if f.outline_offset { self.pack .context @@ -1654,14 +1811,14 @@ impl Game<'_> { ) -> Vec { let registry = self.pack.assets.registry; let dynamic = self.pending.dynamic(pos); - match self.res.items.block_loot_sequence(registry, state) { + match self.res.items().block_loot_sequence(registry, state) { Some(sequence) => { let random = self.rand_sequences.get(&sequence, self.level.seed); self.res - .items + .items() .block_drops_with(registry, state, held, &dynamic, random) } - None => self.res.items.block_drops_with( + None => self.res.items().block_drops_with( registry, state, held, @@ -1731,14 +1888,14 @@ impl Game<'_> { ) { return true; } - if !item.tick(&self.world, &self.res.facts, self.collision) { + if !item.tick(&self.world, self.res.facts(), self.collision) { return false; } let environment = item.environment_tick( &self.world, - &self.res.facts, + self.res.facts(), self.pack.assets.registry, - &self.res.items, + self.res.items(), ); // shortcut: age is the fresh-drop clock; use entity ticks for saved/frozen-age phase parity. if environment.should_play_lava_hurt_sound(item.age) { @@ -1868,6 +2025,7 @@ impl Game<'_> { ) }) .collect(); + let guest_boxes = self.lan_block_trigger_boxes(); let dimension = match self.dim { Dim::Overworld => LevelDimension::Overworld, Dim::Nether => LevelDimension::Nether, @@ -1877,7 +2035,7 @@ impl Game<'_> { let mut level = GameLevel { cart_boxes, world: &mut self.world, - facts: &self.res.facts, + facts: self.res.facts(), collision: self.collision, events: &mut self.level_events, dimension, @@ -1885,19 +2043,21 @@ impl Game<'_> { raining: rain > 0.2, thundering: thunder > 0.9, player_box, + guest_boxes, player_collision, - biomes: &self.res.biomes, + biomes: self.res.biomes(), seed: self.level.seed, - behaviours: &self.res.behaviours, - items: &self.res.items, + behaviours: self.res.behaviours(), + items: self.res.items(), loot: horizon_client::structure_blocks::loot_data(&self.options.resources), registry: self.pack.assets.registry, rules, rand_sequences: &mut self.rand_sequences, pending: &mut self.pending, spill: &mut self.spill, + tickets: self.tickets.levels(), }; - let result = f(&self.res.behaviours, &mut level, &mut self.block_ticks); + let result = f(self.res.behaviours(), &mut level, &mut self.block_ticks); self.flush_spill(); result } @@ -1938,22 +2098,62 @@ impl Game<'_> { } self.tick_chunks.recycle_added(added); } - /// ServerLevel.tick block phases: scheduled ticks, random ticks within the - /// simulation distance, block events and moving pistons. + /// `DistanceManager`'s tickets of the level in place, from every player in + /// it (the local player, LAN guests, a server's players) and its forced + /// chunks. A game with neither a server nor a player (the headless + /// fixtures) ticks everywhere. + fn update_chunk_tickets(&mut self) { + let mut players: Vec<(i32, i32)> = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g)) + .map(|g| g.chunk()) + .collect() + }); + if let Some(p) = &self.player { + players.push(( + (p.position.x.floor() as i32) >> 4, + (p.position.z.floor() as i32) >> 4, + )); + } + let sources = (self.options.dedicated.is_some() || !players.is_empty()).then(|| { + horizon_client::ticket_levels::Sources { + players, + forced: self.streaming.forced.iter().copied().collect(), + view_distance: self.settings.render_distance.clamp(2, 32), + simulation_distance: self.settings.simulation_distance.max(2), + } + }); + self.tickets.update(sources); + } + /// `ServerLevel.startTickingChunk`: a loaded chunk's saved ticks are + /// scheduled from the game time at which it becomes a ticking chunk + /// (block ticking, with its neighbours loaded). Chunks become ticking + /// between ticks in vanilla: before this tick's clock advanced. + fn start_ticking_chunks(&mut self) { + let levels = self.tickets.levels(); + let world = &self.world; + let started = self + .tick_chunks + .start_ticking(|(x, z)| levels.loaded_ticking(x, z) && ticking_chunk(world, x, z)); + let time = self.world.game_time - 1; + for (x, z) in started { + let pos = horizon_core::position::ChunkPos::new(x, z); + self.block_ticks.blocks.unpack_chunk(pos, time); + self.block_ticks.fluids.unpack_chunk(pos, time); + } + } + /// ServerLevel.tick block phases: scheduled ticks, random ticks in the + /// chunks the tickets simulate, block events and moving pistons. fn tick_blocks(&mut self) -> Result<()> { self.sync_tick_chunks(); - let Some(p) = self.player.as_ref() else { - return Ok(()); - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); + self.start_ticking_chunks(); + let levels = self.tickets.levels(); let mut ticking = Vec::new(); - let facts = &self.res.facts; + let facts = self.res.facts(); for (&(x, z), chunk) in &self.world.chunks { - if (x - pcx).abs() > simulation || (z - pcz).abs() > simulation || !chunk.lit { + if !levels.random_ticking(x, z) || !ticking_chunk(&self.world, x, z) { continue; } // Capture eligibility before inside-block and scheduled updates, as @@ -1963,8 +2163,9 @@ impl Game<'_> { ticking.push((x, z, sections)); } // Entity.checkInsideBlocks for the plates, tripwires and detector rails - // under the player and the minecarts. + // under the players (the host and the LAN guests) and the minecarts. let mut inside = Vec::new(); + let guests = self.lan_block_trigger_boxes(); let boxes = self .player .iter() @@ -1983,7 +2184,8 @@ impl Game<'_> { [p.x - 0.49, p.y, p.z - 0.49], [p.x + 0.49, p.y + 0.7, p.z + 0.49], ) - })); + })) + .chain(guests); for (lo, hi) in boxes { for x in (lo[0] + 1e-7).floor() as i32..=(hi[0] - 1e-7).floor() as i32 { for y in (lo[1] + 1e-7).floor() as i32..=(hi[1] - 1e-7).floor() as i32 { @@ -2053,10 +2255,10 @@ impl Game<'_> { let state = BlockStateId(data as u32); let p = [pos.x, pos.y, pos.z]; self.destroy_particles(p, state); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); let c = [ f64::from(pos.x) + 0.5, f64::from(pos.y) + 0.5, @@ -2083,6 +2285,11 @@ impl Game<'_> { pos, data, } => self.dragon_egg_particles([pos.x, pos.y, pos.z], data), + LevelEvent::LevelEvent { + id: 2017, + pos, + data, + } => self.consume_teleport_particles([pos.x, pos.y, pos.z], data), LevelEvent::LevelEvent { id: 2013, pos, @@ -2168,7 +2375,7 @@ impl Game<'_> { no_gravity: false, drop_item: true, fall_distance: 0.0, - damage: if self.res.facts.get(state).name.ends_with("anvil") { + damage: if self.res.facts().get(state).name.ends_with("anvil") { horizon_client::falling_block::Damage::anvil() } else { Default::default() @@ -2281,7 +2488,7 @@ impl Game<'_> { fn open_menu(&mut self, pos: [i32; 3]) { let name = self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name .clone(); @@ -2390,7 +2597,12 @@ impl Game<'_> { let mut dropped = Vec::new(); let mut collision_error = None; let entity_drops = self.ui.rules.bool("entity_drops"); + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); falling.retain_mut(|f| { + if !ticking(f.position.x.floor() as i32, f.position.z.floor() as i32) { + return true; + } let original = f.clone(); f.previous = f.position; f.age = f.age.wrapping_add(1); @@ -2479,7 +2691,7 @@ impl Game<'_> { self.falling = falling; for (state, at) in dropped { // Entity.spawnAtLocation: an item entity where the block was. - let item = self.res.facts.get(state).item.clone(); + let item = self.res.facts().get(state).item.clone(); if &*item != "minecraft:air" { let r = &mut self.world.random; let v = [ @@ -2505,6 +2717,75 @@ impl Game<'_> { } Ok(()) } + /// `DecoratedPotBlock.playerWillDestroy`: a pot mined with an item in + /// `breaks_decorated_pots`, unless an enchantment prevents shattering, is + /// cracked first (flags 260), so it shatters into its sherds. + fn crack_mined_pot(&mut self, pos: [i32; 3], state: BlockStateId) -> BlockStateId { + let registry = &self.pack.assets.registry; + let Some(mut pot) = registry + .state(state) + .filter(|s| s.name == "minecraft:decorated_pot") + .cloned() + else { + return state; + }; + let Some(held) = self.held() else { + return state; + }; + let breaks = self + .res + .items() + .item_tags + .get("minecraft:breaks_decorated_pots") + .is_some_and(|t| t.contains(&*held.item)); + let enchantments = &self.res.stations().enchantments; + let kept = held + .enchantments() + .iter() + .any(|(e, _)| enchantments.in_tag("minecraft:prevents_decorated_pot_shattering", e)); + if !breaks || kept { + return state; + } + pot.properties.insert("cracked".into(), "true".into()); + let Ok(cracked) = registry.resolve(&pot) else { + return state; + }; + let at = BlockPos::new(pos[0], pos[1], pos[2]); + self.with_level(|b, level, ticks| b.set_block(level, ticks, at, cracked, 260)); + cracked + } + /// `ItemStack.mineBlock` for the held stack once a survival player has + /// mined the block `name`: an item with a `tool` component counts as used + /// and loses its `damage_per_block` on a block that doesn't break + /// instantly (`ShearsItem`: on any block but fire). + fn mine_block_with_held(&mut self, name: &str, hardness: f32) { + let Some(stack) = self.inventory[self.selected].clone() else { + return; + }; + let Some((per_block, max)) = self + .res + .items() + .get(&stack.item) + .and_then(|i| Some((i.tool_damage_per_block?, i.max_damage))) + else { + return; + }; + let wears = if &*stack.item == "minecraft:shears" { + !self.res.items().block_in_tag("minecraft:fire", name) + } else { + hardness != 0.0 + }; + if wears && per_block > 0 && max > 0 { + let loss = self.durability_loss(&stack, per_block); + if let Some(held) = self.inventory[self.selected].as_mut() { + held.damage += loss; + if held.damage >= max { + self.inventory[self.selected] = None; + } + } + } + self.stats.add("used", &stack.item, 1); + } fn break_block(&mut self, pos: [i32; 3]) -> Result<()> { self.with_player_actor(|game| game.break_block_as_player(pos)) } @@ -2512,7 +2793,8 @@ impl Game<'_> { self.pad_rumble(horizon_client::gamepad::Rumble::BlockBroken); // ServerPlayerGameMode.destroyBlock. let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state).clone(); + let facts = self.res.facts().get(state).clone(); + let state = self.crack_mined_pot(pos, state); // Block.playerWillDestroy: mining their gold angers all nearby piglins. if self.guarded_by_piglins(&facts.name) { self.anger_piglins(false); @@ -2544,26 +2826,12 @@ impl Game<'_> { }); if removed && !creative { let held = self.held().cloned(); - // ItemStack.mineBlock: tools lose durability on blocks with nonzero hardness. - if facts.hardness > 0.0 - && let Some(stack) = self.inventory[self.selected].clone() - && let Some(max) = self - .res - .items - .get(&stack.item) - .filter(|i| i.max_damage > 0 && !i.tool.is_empty()) - .map(|i| i.max_damage) - { - let loss = self.durability_loss(&stack, 1); - if let Some(stack) = self.inventory[self.selected].as_mut() { - stack.damage += loss; - if stack.damage >= max { - self.inventory[self.selected] = None; - } - } - } + self.mine_block_with_held(&facts.name, facts.hardness); let harvest = !facts.requires_tool - || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + || self + .res + .items() + .correct_for_drops(held.as_ref(), &facts.name); if harvest { // Block.playerDestroy: the mined statistic, the exhaustion and the drops. self.stats.add("mined", &facts.name, 1); @@ -2734,7 +3002,7 @@ impl Game<'_> { let Some(stack) = self.held().cloned() else { return Ok(false); }; - let Some(info) = self.res.items.get(&stack.item).cloned() else { + let Some(info) = self.res.items().get(&stack.item).cloned() else { return Ok(false); }; if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) { @@ -2845,7 +3113,7 @@ impl Game<'_> { return Ok(true); }; let target = [pos.x, pos.y, pos.z]; - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { let key = (target[0], target[1], target[2]); self.world.block_entities.insert(key, entity); let game_master = self.can_use_game_master_blocks(); @@ -2889,15 +3157,15 @@ impl Game<'_> { } Ok(true) } - /// `Consumable.startConsuming` for held food the player can eat - /// (`Player.canEat`): the right click is held for `consume_seconds`. + /// `Consumable.startConsuming` for a held consumable: food needs + /// `Player.canEat` (`Consumable.canConsume`), anything else is always + /// consumed. The right click is held for `consume_seconds`. fn start_eating(&mut self, info: &horizon_client::items::ItemInfo) -> bool { - if !info.consumable - || info.food.is_none() - || !self - .player - .as_ref() - .is_some_and(|p| info.can_always_eat || p.health.food.food < 20 || self.creative) + if info.consumable.is_none() + || (info.food.is_some() + && !self.player.as_ref().is_some_and(|p| { + info.can_always_eat || p.health.food.food < 20 || self.creative + })) { return false; } @@ -2906,18 +3174,17 @@ impl Game<'_> { } true } - fn apply_consume_effect( - &mut self, - effect: &horizon_client::items::ConsumeEffect, - eye: [f64; 3], - ) { + fn apply_consume_effect(&mut self, effect: &horizon_client::items::ConsumeEffect) { use horizon_client::items::ConsumeEffect; match effect { ConsumeEffect::ApplyEffects { effects, probability, } => { - if *probability >= 1.0 || self.world.random.next_float() <= *probability { + // ApplyStatusEffectsConsumeEffect.apply: the user's random + // (the level's stands in, as for every player draw) is drawn + // even at probability 1. + if self.world.random.next_float() < *probability { for eff in effects { if let Some(def) = horizon_client::brewing::effect(&eff.id) { if def.instant { @@ -2950,9 +3217,14 @@ impl Game<'_> { } self.apply_effect_status(); } - ConsumeEffect::TeleportRandomly => {} + ConsumeEffect::TeleportRandomly(teleport) => self.teleport_randomly(teleport), ConsumeEffect::PlaySound(sound) => { - self.audio.play(sound, Some(eye), 1.0, 1.0); + // PlaySoundConsumeEffect: at the user's block position. + let at = self.player.as_ref().map(|p| { + let b = horizon_core::position::BlockPos::containing(p.position); + [b.x, b.y, b.z].map(|v| f64::from(v) + 0.5) + }); + self.audio.play(sound, at, 1.0, 1.0); } } } @@ -3000,7 +3272,7 @@ impl Game<'_> { self.using = None; return; } - let Some(info) = self.res.items.get(&stack.item).cloned() else { + let Some(info) = self.res.items().get(&stack.item).cloned() else { self.using = None; return; }; @@ -3034,49 +3306,21 @@ impl Game<'_> { } return; } - let duration = 32; - // Consumable.shouldEmitParticlesAndSounds(useItemRemainingTicks), with - // the remaining ticks before this tick counts down: every 4 ticks once - // more than 21.875% of the time has passed (none on the last tick). + let Some(consumable) = info.consumable.as_ref() else { + self.using = None; + return; + }; + // ItemStack.onUseTick: Consumable.shouldEmitParticlesAndSounds with + // the remaining ticks before this tick counts them down. + let duration = consumable.ticks().max(0) as u32; let remaining = duration - ticks.min(duration); let ticks = ticks + 1; - let eye = self.eye_position().unwrap_or_default(); - if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { - let pitch = - (self.world.random.next_float() - self.world.random.next_float()) * 0.2 + 1.0; - self.audio.play( - "minecraft:entity.generic.eat", - Some(eye), - 0.5 + 0.5 * self.world.random.next_int_bound(2).unwrap_or(0) as f32, - pitch, - ); - self.eat_particles(&stack, 5); + if consumable.should_emit(remaining as i32) { + self.emit_consume(consumable, &stack, 5); } if ticks >= duration { self.using = None; - // Consumable.onConsume: emitParticlesAndSounds(..., 16). - 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 { - 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(); - } + self.finish_consuming(&info, consumable, &stack); } else { self.using = Some((slot, ticks)); } @@ -3117,13 +3361,13 @@ impl Game<'_> { }); } let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if facts.hardness < 0.0 { return Ok(()); } // Player.getDestroySpeed / BlockBehaviour.getDestroyProgress. let held = self.held(); - let mut speed = self.res.items.mining_speed(held, &facts.name); + let mut speed = self.res.items().mining_speed(held, &facts.name); speed = self.modify_destroy_speed(speed); let player = self.player.as_ref().ok_or("no player")?; if !player.ground.on_ground { @@ -3132,7 +3376,7 @@ impl Game<'_> { let eye = self.eye_position().unwrap_or_default(); if self .res - .facts + .facts() .get(self.world.block( eye[0].floor() as i32, eye[1].floor() as i32, @@ -3143,7 +3387,7 @@ impl Game<'_> { { speed *= self.submerged_mining_speed(); } - let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); + let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); let progress = if facts.hardness == 0.0 { 1.0 } else { @@ -3183,11 +3427,11 @@ impl Game<'_> { if self.dim == Dim::Nether { // Below the bedrock ceiling: a solid floor with two air blocks above. for y in (32..120).rev() { - let floor = self.res.facts.get(self.world.block(x, y - 1, z)); + let floor = self.res.facts().get(self.world.block(x, y - 1, z)); if floor.full_collision && floor.fluid == Fluid::None - && self.res.facts.is_air(self.world.block(x, y, z)) - && self.res.facts.is_air(self.world.block(x, y + 1, z)) + && self.res.facts().is_air(self.world.block(x, y, z)) + && self.res.facts().is_air(self.world.block(x, y + 1, z)) { return Some(y); } @@ -3197,8 +3441,8 @@ impl Game<'_> { let mut y = MIN_Y + HEIGHT - 1; while y > MIN_Y { let s = self.world.block(x, y, z); - if !self.res.facts.is_air(s) { - let f = self.res.facts.get(s); + if !self.res.facts().is_air(s) { + let f = self.res.facts().get(s); let ok = f.full_collision && f.fluid == Fluid::None && !f.name.contains("leaves") @@ -3301,7 +3545,7 @@ impl Game<'_> { // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); @@ -3425,7 +3669,7 @@ impl Game<'_> { // LivingEntity.canGlideUsing: a glider in its slot that will not break next. player.glider = self.armor[1].as_ref().is_some_and(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| i.glider && (i.max_damage == 0 || s.damage + 1 < i.max_damage)) }); @@ -3439,7 +3683,7 @@ impl Game<'_> { self.inventory.get(slot)?.as_ref() } }) - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .map(|i| i.use_speed); // PowderSnowBlock.canEntityWalkOnPowderSnow and LivingEntity.canFreeze. player.leather_boots = self.armor[3] @@ -3447,7 +3691,7 @@ impl Game<'_> { .is_some_and(|s| &*s.item == "minecraft:leather_boots"); let immune = self .res - .items + .items() .item_tags .get("minecraft:freeze_immune_wearables"); player.freeze_immune = self @@ -3504,7 +3748,7 @@ impl Game<'_> { MotionEvent::Emission { state, in_water, .. } if !crouching => { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); // Entity.playStepSound: the block's step sound at 0.15 volume, // muffled under the swim sound in water. let (volume, pitch) = if in_water { @@ -3679,6 +3923,10 @@ impl Game<'_> { } self.audio .play("minecraft:entity.player.death", Some(at), 1.0, 1.0); + // LivingEntity.die: the LAN guests see the host's death animation. + if let Some(host) = &self.lan { + host.hub.entity_event(host.host_entity, 3, feet); + } self.screen = Screen::Dead; self.capture(false); } @@ -3687,6 +3935,7 @@ impl Game<'_> { /// What the tick runs after the local player's own update: effects, the /// world's entities and blocks, and the network hub. fn tick_world(&mut self, running: bool) -> Result<()> { + self.update_chunk_tickets(); horizon_client::spans::time("tick_effects", || self.tick_effects()); horizon_client::spans::time("tick_using", || self.tick_using()); horizon_client::spans::time("tick_hud", || self.tick_hud()); @@ -3943,7 +4192,7 @@ impl Game<'_> { let (stack, capped) = match drag.and_then(|d| d.slots.get(&slot)) { Some(None) => return, Some(Some((count, capped))) => { - batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); let carried = self .carried .clone() @@ -4022,7 +4271,7 @@ impl Game<'_> { // moved to (x, y). Horizon tracks no item cooldowns to shade yet. let max_damage = self .res - .items + .items() .get(&stack.item) .map_or(0, |info| info.max_damage as i32); let decorations = hud_overlays::ItemDecorations { @@ -4038,10 +4287,10 @@ impl Game<'_> { 0, 0, &decorations, - &self.atlas.font, + &self.gui.atlas.font, )); draws.push(hud_layout::GuiDraw::Pop); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } fn hud(&mut self, size: [u32; 2]) -> HudBatch { let mut batch = self.hud_layers(size); @@ -4049,7 +4298,7 @@ impl Game<'_> { // and the toasts, so it is over everything, menus included. self.draw_debug_overlay(&mut batch, size); self.frame_graph - .draw(self.settings.horizon.overlay, &mut batch, &self.atlas); + .draw(self.settings.horizon.overlay, &mut batch, &self.gui.atlas); self.draw_pad_cursor(&mut batch); batch } @@ -4070,12 +4319,12 @@ impl Game<'_> { if horizon_client::ui_theme::horizon() { let fade = self.backdrop_fade(); let mut ui = - horizon_client::ui_theme::Ui::new(&self.atlas, &mut batch, self.cursor); + horizon_client::ui_theme::Ui::new(&self.gui.atlas, &mut batch, self.cursor); title.draw_horizon(&mut ui, fade); ui.finish(); } else { title.draw( - &self.atlas, + &self.gui.atlas, &mut batch, self.cursor, self.settings.file.bool("hideSplashTexts"), @@ -4083,7 +4332,7 @@ impl Game<'_> { } return batch; } - let atlas_ptr: *const HudAtlas = &self.atlas; + let atlas_ptr: *const HudAtlas = &self.gui.atlas; let _ = atlas_ptr; if self.remote_overlay(&mut batch) { return batch; @@ -4114,7 +4363,7 @@ impl Game<'_> { hud_layout::full_attack_indicator(a, delay, self.crosshair_living()) }); let draws = hud_layout::crosshair(wi, hi, attack, full); - hud_layout::paint(&mut batch, &self.atlas, &draws); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); } if !spectator { let inputs = hud_layout::HotbarInputs { @@ -4126,7 +4375,7 @@ impl Game<'_> { attack: (indicator == 2).then_some(strength), }; let draws = hud_layout::hotbar(wi, hi, &inputs); - hud_layout::paint(&mut batch, &self.atlas, &draws); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); for d in &draws { if let hud_layout::GuiDraw::Item { slot, x, y, .. } = *d { let stack = if slot == 40 { @@ -4156,7 +4405,7 @@ impl Game<'_> { && !spectator && let Some(p) = &mut self.player { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let width = |s: &str| HudBatch::text_width(atlas, s) as i32; let draws = hud_layout::experience( wi, @@ -4180,7 +4429,7 @@ impl Game<'_> { let eye = p.position.y + f64::from(p.dimensions.eye_height); let under_water = self .res - .facts + .facts() .get(self.world.block( p.position.x.floor() as i32, eye.floor() as i32, @@ -4219,13 +4468,13 @@ impl Game<'_> { } // 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); + hud_layout::paint(&mut batch, &self.gui.atlas, &draws); if show_hud { self.draw_titles(&mut batch); self.draw_scoreboard(&mut batch); self.draw_subtitles(&mut batch); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if show_hud && let Some((text, at)) = &self.message && at.elapsed() < Duration::from_secs(3) @@ -4242,9 +4491,9 @@ impl Game<'_> { // PauseScreen(false): only its title, at the top. Screen::Paused => { let title = self.translate("menu.paused", "Game Paused"); - let tw = HudBatch::text_width(&self.atlas, &title); + let tw = HudBatch::text_width(&self.gui.atlas, &title); batch.text( - &self.atlas, + &self.gui.atlas, &title, ((batch.width / 2.0).floor() - (tw / 2.0).floor()).floor(), 10.0, @@ -4443,7 +4692,7 @@ impl Game<'_> { /// `RecipeCraftingHolder.awardUsedRecipes`: a crafted recipe becomes known /// (special ones never do). fn award_crafted(&mut self, recipes: &[String]) { - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let (_, unlocked) = self.level.recipe_book.add_recipes(index, recipes); self.recipe_unlocked(&unlocked); } @@ -4452,7 +4701,7 @@ impl Game<'_> { let grid: Vec> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect(); let scale = |id: i32| self.maps.data.get(&id).map(|m| m.scale); self.res - .recipes + .recipes() .find_with(&grid, n, &scale) .map(|(name, result)| (name.to_owned(), result)) } @@ -4462,7 +4711,7 @@ impl Game<'_> { let (sx, sy) = self.slot_position(i); if i == 504 && self.offhand.is_none() { batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/container/slot/shield", ox + sx, oy + sy, @@ -4471,7 +4720,7 @@ impl Game<'_> { if (500..504).contains(&i) && self.armor[i - 500].is_none() { let icon = ["helmet", "chestplate", "leggings", "boots"][i - 500]; batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -4487,7 +4736,7 @@ impl Game<'_> { } let (ox, oy) = self.inventory_origin(batch); { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -4611,7 +4860,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -4652,7 +4901,7 @@ impl Game<'_> { ); let name = self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name .clone(); @@ -4725,7 +4974,7 @@ impl Game<'_> { let items = self.creative_screen.items(&self.pack.names); let first = self.creative_screen.first_row(&self.pack.names); let shown = items.get(first * 9 + slot - Creative::DISPLAY); - let catalog = &self.res.items; + let catalog = self.res.items(); let max = |s: &ItemStack| catalog.get(&s.item).map_or(64, |i| i.max_stack); match click_display(&mut self.carried, shown, max, button, input) { DisplayClick::Hotbar(i, stack) => self.inventory[i] = Some(stack), @@ -4885,7 +5134,7 @@ impl Game<'_> { Some(BlockEntity::Chest(_)) => { let shulker = self.container.is_some_and(|k| { let id = self.world.block(k.0, k.1, k.2); - storage::is_shulker_box(&self.res.facts.get(id).name) + storage::is_shulker_box(&self.res.facts().get(id).name) }); let kind = match size { 5 => Kind::Hopper, @@ -4895,6 +5144,9 @@ impl Game<'_> { }; (kind, size) } + // A server's BrewingStandMenu; a local stand's clicks are the + // station screen's. + Some(BlockEntity::Brewing(_)) if self.remote.is_some() => (Kind::Brewing, 5), Some(BlockEntity::Furnace(f)) => ( Kind::Furnace( match f.kind.recipe_type().trim_start_matches("minecraft:") { @@ -4978,15 +5230,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let trade_env = horizon_client::merchant::TradeEnv { - trades: &self.res.stations.trades, - enchantments: &self.res.stations.enchantments, + trades: &self.res.stations().trades, + enchantments: &self.res.stations().enchantments, maps: Some(&maps), }; let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: Some(&trade_env), }; menu.creative = creative; @@ -5081,7 +5333,7 @@ impl Game<'_> { .and_then(|k| self.world.block_entities.get_mut(&k)) { // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. - f.input_clicked(&self.res.recipes, before[0].clone()); + f.input_clicked(self.res.recipes(), before[0].clone()); } self.apply_equipment(); true @@ -5484,7 +5736,7 @@ impl Game<'_> { None => self.carried = Some(result), Some(c) if c.item == result.item - && c.count + result.count <= max(&self.res.items, c) => + && c.count + result.count <= max(self.res.items(), c) => { c.count += result.count } @@ -5500,7 +5752,7 @@ impl Game<'_> { while let Some((recipe, result)) = self.craft_recipe() { let made = (result.item.clone(), result.count); let cells = self.craft_size * self.craft_size; - let remainders = self.res.recipes.remainders( + let remainders = self.res.recipes().remainders( &recipe, &self.craft_grid[..cells], self.craft_size, @@ -5514,7 +5766,7 @@ impl Game<'_> { None => self.carried = Some(result), Some(c) if c.item == result.item - && c.count + result.count <= max(&self.res.items, c) => + && c.count + result.count <= max(self.res.items(), c) => { c.count += result.count } @@ -5556,7 +5808,7 @@ impl Game<'_> { let wanted = ["head", "chest", "legs", "feet"][slot - 500]; let fits = self.carried.as_ref().is_none_or(|c| { self.res - .items + .items() .get(&c.item) .and_then(|i| i.equip_slot.as_deref()) == Some(wanted) @@ -5570,7 +5822,7 @@ impl Game<'_> { } let carried = self.carried.take(); let current = self.slot_mut(slot).take(); - let items = &self.res.items; + let items = self.res.items(); let (new_slot, new_carried) = match (carried, current) { (None, Some(mut s)) if right => { let half = s.count.div_ceil(2); @@ -5611,7 +5863,7 @@ impl Game<'_> { .container .and_then(|k| self.world.block_entities.get_mut(&k)) { - f.input_clicked(&self.res.recipes, before); + f.input_clicked(self.res.recipes(), before); } } /// `Camera.setRotation`: the camera's orientation, turned round in @@ -5652,7 +5904,7 @@ impl Game<'_> { m.height(), camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5674,7 +5926,7 @@ impl Game<'_> { p.dimensions.height, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( feet.x.floor() as i32, feet.y.floor() as i32, @@ -5687,7 +5939,7 @@ impl Game<'_> { if item.fire_ticks > 0 && !self .res - .items + .items() .resists_fire(&item.stack, "minecraft:in_fire") { let at = item.previous.lerp(item.position, alpha); @@ -5697,7 +5949,7 @@ impl Game<'_> { 0.25, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( at.x.floor() as i32, at.y.floor() as i32, @@ -5716,7 +5968,7 @@ impl Game<'_> { 1.975 * scale, camera, fire_yaw, - &self.atlas.sprites, + &self.gui.atlas.sprites, self.world.light( stand.position.x.floor() as i32, stand.position.y.floor() as i32, @@ -5741,7 +5993,7 @@ impl Game<'_> { self.name_tag_geometry(camera, alpha, &mut out, &mut see_through); self.see_through_vertices = see_through; // Entity shadows (EntityRenderer.extractShadow). - if let Some(sprite) = self.atlas.sprites.get("misc/shadow").copied() { + if let Some(sprite) = self.gui.atlas.sprites.get("misc/shadow").copied() { let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 }; let darken = self.sky_darken(); let a = alpha; @@ -5771,7 +6023,7 @@ impl Game<'_> { let (radius, strength) = horizon_client::shadows::shadow_params(id); horizon_client::shadows::shadow( &self.world, - &self.res.facts, + self.res.facts(), sprite, camera, pos, @@ -5796,7 +6048,7 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, nether: self.dim == Dim::Nether, lid: &lid, sign: &|p| match self.world.block_entities.get(&(p[0], p[1], p[2])) { @@ -5804,7 +6056,7 @@ impl Game<'_> { _ => None, }, banner: &|p| self.banner_layers_at(p), - glyph: &|c| self.atlas.glyph_cell(c), + glyph: &|c| self.gui.atlas.glyph_cell(c), }; // Block entities outside the view frustum are skipped (with a // block of margin for models larger than their block). @@ -5812,7 +6064,7 @@ impl Game<'_> { // Beams and structure outlines reach far outside their block // (BlockEntityRenderer.shouldRenderOffScreen): never culled. let off_screen = |state: u32| { - let name = &*self.res.facts.get(BlockStateId(state)).name; + let name = &*self.res.facts().get(BlockStateId(state)).name; matches!( name, "minecraft:beacon" @@ -5822,7 +6074,7 @@ impl Game<'_> { ) }; let visible = r.block_entities().filter(|(p, state)| { - if !self.res.block_entity_render.renders(*state) { + if !self.res.block_entity_render().renders(*state) { return false; } off_screen(*state) @@ -5838,7 +6090,7 @@ impl Game<'_> { for block in visible { let start = out.len(); self.res - .block_entity_render + .block_entity_render() .render(&scene, std::iter::once(block), &mut out); if !off_screen(block.1) { self.cull_entity_vertices(&mut out, start); @@ -5846,12 +6098,12 @@ impl Game<'_> { } } else { self.res - .block_entity_render + .block_entity_render() .render(&scene, visible, &mut out); } if let Some(mining) = &self.mining && mining.progress > 0.0 - && self.atlas.sprites.contains_key(&format!( + && self.gui.atlas.sprites.contains_key(&format!( "block/destroy_stage_{}", ((mining.progress * 10.0) as u32).min(9) )) @@ -5860,12 +6112,13 @@ impl Game<'_> { .world .block(mining.pos[0], mining.pos[1], mining.pos[2]); self.res - .block_entity_render + .block_entity_render() .render_breaking(&scene, mining.pos, state.0, &mut out); } } // Experience orbs (ExperienceOrbRenderer): pulsing billboards from a 4x4 icon sheet. if let Some(r) = self + .gui .atlas .sprites .get("entity/experience/experience_orb") @@ -5978,7 +6231,7 @@ impl Game<'_> { &|b| world.light(b[0], b[1], b[2]), &mut out, ); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; // Breaking progress overlay (destroy_stage_0..9). if let Some(m) = &self.mining && m.progress > 0.0 @@ -5995,11 +6248,11 @@ impl Game<'_> { ) - camera) .as_vec3(); let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - if self.res.facts.get(state).render_shape + if self.res.facts().get(state).render_shape == horizon_client::blocks::RenderShape::Model && let Ok(models) = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(m.pos[0], m.pos[1], m.pos[2])) { @@ -6029,7 +6282,7 @@ impl Game<'_> { if self.dim == Dim::End { let sky = self .res - .end_environment + .end_environment() .sample(self.world.day_time, None, None); return (15.0 - 15.0 * sky.sky_light_level).round() as i32; } @@ -6041,7 +6294,10 @@ impl Game<'_> { { return darken; } - let mut sky = self.res.environment.sample(self.world.day_time, None, None); + let mut sky = self + .res + .environment() + .sample(self.world.day_time, None, None); horizon_client::environment::apply_weather(&mut sky, rain, thunder); // Level.updateSkyBrightness: darkening from the sky light level. let darken = (15.0 - 15.0 * sky.sky_light_level).round() as i32; @@ -6073,7 +6329,7 @@ impl Game<'_> { let hand_damage = 1.0 + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_damage); let damage = hand_damage + self.effect_attack_bonus(); let scale = self.attack_strength_scale(); @@ -6096,7 +6352,7 @@ impl Game<'_> { fn attack_strength_scale(&self) -> f32 { let speed = self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_speed); let delay = 20.0 / (4.0 + speed).max(0.1); ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0) @@ -6106,7 +6362,7 @@ impl Game<'_> { let p = self.player.as_ref()?; let sword = self.held().is_some_and(|s| { self.res - .items + .items() .item_tags .get("minecraft:swords") .is_some_and(|tag| tag.contains(&*s.item)) @@ -6178,7 +6434,7 @@ impl Game<'_> { let hand_damage = 1.0 + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| i.attack_damage); if self.attack_frame() || self.attack_armor_stand() @@ -6331,7 +6587,7 @@ impl Game<'_> { /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) @@ -6428,6 +6684,16 @@ impl Game<'_> { creative: bool, create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { + if self.defer_world_entry(PendingWorldEntry::Local { + folder: folder.to_owned(), + name: name.map(str::to_owned), + seed, + creative, + create: create.cloned().map(Box::new), + })? { + return Ok(()); + } + self.join_world_rest()?; let save_root = std::env::current_dir()?.join("saves").join(folder); if integrated::wanted(&self.options, &save_root) { return self.open_integrated(folder, name, seed, creative, create); @@ -6489,7 +6755,7 @@ impl Game<'_> { let dim = Dim::from_id(&level.dimension); let (mut streaming, save) = self.make_streaming(&save_root, dim, level.seed)?; streaming.radius = self.settings.render_distance; - let mut world = World::new(self.res.facts.air, level.seed); + let mut world = World::new(self.res.facts().air, level.seed); world.fast_lava = dim == Dim::Nether; world.game_time = level.time; world.day_time = self.options.time.unwrap_or(level.day_time); @@ -6567,7 +6833,7 @@ impl Game<'_> { self.save = save; self.level = level; // ServerRecipeBook.loadUntrusted: recipes the manager does not have are dropped. - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let book = &mut self.level.recipe_book; book.recipes.retain(|r| index.contains(r)); book.to_be_displayed.retain(|r| index.contains(r)); @@ -6647,7 +6913,7 @@ impl Game<'_> { horizon_client::flatgen::FlatTerrain::from_settings( &s, pack.assets.registry, - &res.biomes, + res.biomes(), ) }); let mut streaming = if let Some(inner) = flat { @@ -6656,28 +6922,28 @@ impl Game<'_> { inner: Arc::new(inner), save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) } else if self.options.test_terrain && dim == Dim::Overworld { - let inner = Arc::new(TestTerrain::new(pack.assets.registry, &res.biomes)?); + let inner = Arc::new(TestTerrain::new(pack.assets.registry, res.biomes())?); Streaming::new( Arc::new(Persistent { inner, save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) } else { // 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| { + 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())); @@ -6686,10 +6952,10 @@ impl Game<'_> { inner, save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads, + res.threads(), ) }; streaming.radius = self.settings.render_distance; @@ -6727,7 +6993,7 @@ impl Game<'_> { 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(&chunks, self.pack.assets.registry, &self.res.biomes)?; + .save(&chunks, self.pack.assets.registry, self.res.biomes())?; self.save_dimension_entities()?; // Coordinates scale by 8 between the Overworld and the Nether. let scale = match (self.dim, target) { @@ -6743,7 +7009,7 @@ impl Game<'_> { )); let (streaming, save) = self.make_streaming(&self.world_root.clone(), target, self.level.seed)?; - let mut world = World::new(self.res.facts.air, self.level.seed); + let mut world = World::new(self.res.facts().air, self.level.seed); world.fast_lava = target == Dim::Nether; world.game_time = self.world.game_time; world.day_time = self.world.day_time; @@ -6779,7 +7045,7 @@ impl Game<'_> { fn portal_shape(&self, start: [i32; 3], x_axis: bool) -> Option<([i32; 3], i32, i32)> { let name = |p: [i32; 3]| { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -6941,7 +7207,7 @@ impl Game<'_> { horizon_client::crash::clear_detail("World"); self.debug_charts.reset(); self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.player = None; self.sleeping = None; self.sleep_timer = 0; @@ -7004,7 +7270,7 @@ impl Game<'_> { .collect(); equipped.push((self.inventory[self.selected].as_ref(), "mainhand")); for (stack, slot) in equipped { - let Some(info) = stack.and_then(|s| self.res.items.get(&s.item)) else { + let Some(info) = stack.and_then(|s| self.res.items().get(&s.item)) else { continue; }; for (attribute, id, amount, op, group) in &info.modifiers { @@ -7039,7 +7305,7 @@ impl Game<'_> { .collect(); for (slot, amount) in self.armor.iter_mut().zip(losses) { if let Some(stack) = slot.as_mut() - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 { stack.damage += amount; @@ -7076,7 +7342,7 @@ impl Game<'_> { let b = p.map(|v| v.floor() as i32); if b != last { let state = self.world.block(b[0], b[1], b[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let face = [last[0] - b[0], last[1] - b[1], last[2] - b[2]]; if f.fluid != Fluid::None && f.fluid_level == 8 @@ -7090,7 +7356,7 @@ impl Game<'_> { point: p, }); } - if !self.res.facts.is_air(state) && f.fluid == Fluid::None { + if !self.res.facts().is_air(state) && f.fluid == Fluid::None { return Some(Hit { pos: b, face, @@ -7147,7 +7413,7 @@ impl Game<'_> { let Some(held) = self.held() else { return Ok(false); }; - let removes_dye = cauldron::removes_dye(&self.res.items, &held.item); + let removes_dye = cauldron::removes_dye(self.res.items(), &held.item); let above = self.world.block(pos[0], pos[1] + 1, pos[2]); let under_water = registry .state(above) @@ -7203,7 +7469,7 @@ impl Game<'_> { } let Some(id) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.block_transformer.clone()) else { @@ -7214,7 +7480,7 @@ impl Game<'_> { let shield = self .offhand .as_ref() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .is_some_and(|i| i.blocks_attacks.is_some()); if shield && !self.keys.contains(&KeyCode::ShiftLeft) { return Ok(false); @@ -7236,8 +7502,8 @@ impl Game<'_> { }; let Some((_, t, state)) = self.res - .transformers - .apply(&self.res.items, registry, &id, face_name, &around) + .transformers() + .apply(self.res.items(), registry, &id, face_name, &around) else { return Ok(false); }; @@ -7308,7 +7574,7 @@ impl Game<'_> { }; let max = self .held() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .map_or(0, |i| i.max_damage); let cell = self.held_mut(); if let Some(stack) = cell.as_mut() @@ -7373,7 +7639,7 @@ impl Game<'_> { return Ok(UseResult::Pass); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - let f = self.res.facts.get(state).clone(); + let f = self.res.facts().get(state).clone(); if f.fluid == Fluid::None || f.fluid_level != 8 || f.fluid_falling { return Ok(UseResult::Pass); } @@ -7421,7 +7687,7 @@ impl Game<'_> { if !self.may_build() { return Ok(UseResult::Fail); } - let target = if self.res.facts.get(clicked).replaceable { + let target = if self.res.facts().get(clicked).replaceable { hit.pos } else { [ @@ -7463,7 +7729,7 @@ impl Game<'_> { if item == "honeycomb" { let registry = self.pack.assets.registry; let old = registry.state(clicked).cloned(); - if let Some(waxed) = old.and_then(|old| self.res.transformers.waxed(registry, &old)) + if let Some(waxed) = old.and_then(|old| self.res.transformers().waxed(registry, &old)) && let Ok(state) = registry.resolve(&waxed) { self.level_set(hit.pos, state)?; @@ -7484,7 +7750,7 @@ impl Game<'_> { if !self.may_build() { return Ok(UseResult::Fail); } - let name = self.res.facts.get(clicked).name.clone(); + let name = self.res.facts().get(clicked).name.clone(); if self.can_light(clicked, &name) { let registry = self.pack.assets.registry; let mut state = registry @@ -7668,7 +7934,7 @@ impl Game<'_> { .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) + o.tick(&self.world, self.res.facts(), self.collision, target) }); let mut gained = 0; let mut taken = Vec::new(); @@ -7869,10 +8135,16 @@ impl Game<'_> { if hand == Hand::Off { continue; } - let Some(arm) = self.res.player_arm.clone() else { + let Some(arm) = self.res.player_arm().clone() else { continue; }; - let Some(r) = self.atlas.sprites.get("entity/player/wide/steve").copied() else { + let Some(r) = self + .gui + .atlas + .sprites + .get("entity/player/wide/steve") + .copied() + else { continue; }; // renderPlayerArm (right arm) @@ -7996,22 +8268,22 @@ impl Game<'_> { } out } - /// The renderer for the window, with the current block sprites, shared + /// The renderer for the window, with the current block sprites, GUI /// atlas and world border texture. fn new_renderer(&self, window: Arc) -> Result { - self.renderer_for(window, &self.pack, &self.atlas) + self.renderer_for(window, &self.pack, &self.gui) } fn renderer_for( &self, window: Arc, pack: &PackResources, - atlas: &HudAtlas, + gui: &UiResources, ) -> Result { build_renderer( window, self.options.offscreen, pack, - atlas, + gui, self.renderer.as_ref(), ) } @@ -8061,7 +8333,7 @@ impl Game<'_> { /// base temperature lowered above y 80) or none (no precipitation). fn precipitation(&self, x: i32, y: i32, z: i32) -> Option { let chunk = self.world.chunks.get(&(x >> 4, z >> 4))?; - let b = self.res.biomes.get(chunk.biome(x, y, z)); + let b = self.res.biomes().get(chunk.biome(x, y, z)); if !b.precipitation { return None; } @@ -8077,7 +8349,7 @@ impl Game<'_> { let mut y = from; while y > MIN_Y { let s = self.world.block(x, y, z); - let f = self.res.facts.get(s); + let f = self.res.facts().get(s); if f.full_collision || f.fluid != Fluid::None || f.name.contains("leaves") { return y + 1; } @@ -8128,7 +8400,7 @@ impl Game<'_> { if intensity <= 0.0 { return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (Some(rain_tex), Some(snow_tex)) = ( atlas.sprites.get("environment/rain").copied(), atlas.sprites.get("environment/snow").copied(), @@ -8332,7 +8604,7 @@ impl Game<'_> { } /// Vanilla tooltip: dark box with a purple gradient border. fn tooltip(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = HudBatch::text_width(atlas, text); let (x, y) = (x + 12.0, y - 12.0); batch.fill(atlas, x - 3.0, y - 4.0, w + 6.0, 16.0, rgba(16, 0, 16, 240)); @@ -8354,7 +8626,7 @@ impl Game<'_> { ) }; batch.fill( - &self.atlas, + &self.gui.atlas, 0.0, 0.0, batch.width, @@ -8365,7 +8637,7 @@ impl Game<'_> { for (i, t) in tabs.iter().enumerate() { if i != selected { let (tx, ty) = Creative::tab_position(t); - batch.sprite(&self.atlas, &tab_sprite(t, false), ox + tx, oy + ty); + batch.sprite(&self.gui.atlas, &tab_sprite(t, false), ox + tx, oy + ty); } } let background = if tab.search { @@ -8375,13 +8647,13 @@ impl Game<'_> { } else { "gui/container/creative_inventory/tab_items" }; - if let Some(mut r) = self.atlas.sprites.get(background).copied() { + if let Some(mut r) = self.gui.atlas.sprites.get(background).copied() { r.u1 = r.u0 + (r.u1 - r.u0) * Creative::WIDTH / r.w as f32; r.v1 = r.v0 + (r.v1 - r.v0) * Creative::HEIGHT / r.h as f32; batch.rect_uv(ox, oy, Creative::WIDTH, Creative::HEIGHT, r, u32::MAX); } let (tx, ty) = Creative::tab_position(&tab); - batch.sprite(&self.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); + batch.sprite(&self.gui.atlas, &tab_sprite(&tab, true), ox + tx, oy + ty); for t in &tabs { let (tx, ty) = Creative::tab_position(t); let stack = ItemStack { @@ -8397,7 +8669,7 @@ impl Game<'_> { oy + ty + if t.top { 9.0 } else { 7.0 }, ); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if !tab.inventory { batch.text( atlas, @@ -8439,7 +8711,7 @@ impl Game<'_> { if Self::creative_trash_hovered(batch, self.cursor) { let (x, y) = Creative::TRASH_POSITION; batch.fill( - &self.atlas, + &self.gui.atlas, ox + x, oy + y, 16.0, @@ -8450,7 +8722,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (x, y) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + x, oy + y, 16.0, @@ -8473,7 +8745,7 @@ impl Game<'_> { && self.cursor.1 >= y && self.cursor.1 < y + 16.0 { - batch.fill(&self.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); + batch.fill(&self.gui.atlas, x, y, 16.0, 16.0, rgba(255, 255, 255, 128)); hovered = Some(stack.clone()); } } @@ -8499,7 +8771,7 @@ impl Game<'_> { "gui/sprites/container/creative_inventory/scroller_disabled" }; batch.sprite( - &self.atlas, + &self.gui.atlas, scroller, ox + Creative::SCROLL_X, oy + Creative::SCROLL_Y + self.creative_screen.scroller_offset(), @@ -8709,7 +8981,7 @@ impl Game<'_> { 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)?; + .save_later(&chunks, self.pack.assets.registry, self.res.biomes())?; if wait { self.save.flush(); } @@ -8718,6 +8990,19 @@ impl Game<'_> { Ok(()) } fn render(&mut self) -> Result { + if self.pending_entry.is_some() { + if let (Some(renderer), Some(loader)) = (&mut self.renderer, &self.rest_loader) { + let mut hud = HudBatch::new([renderer.config.width, renderer.config.height]); + horizon_client::level_loading::draw_progress( + &mut hud, + &self.gui.atlas, + loader.progress.line(), + loader.progress.fraction(), + ); + return renderer.render(&loading_frame(&hud)); + } + return Ok(false); + } self.poll_shader_pack(); let Some(size) = self .renderer @@ -8738,7 +9023,7 @@ impl Game<'_> { let s = self.world .block(c.x.floor() as i32, c.y.floor() as i32, c.z.floor() as i32); - (c, self.res.facts.get(s).fluid == Fluid::Water, yaw, pitch) + (c, self.res.facts().get(s).fluid == Fluid::Water, yaw, pitch) } None => ( glam::DVec3::new(0.5, 100.0, 0.5), @@ -8758,7 +9043,7 @@ impl Game<'_> { let cave_culling = self.settings.horizon.cave_culling && !self .res - .facts + .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. @@ -8776,7 +9061,7 @@ impl Game<'_> { .get(&(block[0] >> 4, block[2] >> 4)) .map(|c| c.biome(block[0], block[1], block[2])) .unwrap_or(0); - let info = self.res.biomes.get(biome).clone(); + let info = self.res.biomes().get(biome).clone(); let environment = self.dim_environment(); let mut sky = environment.sample(self.world.day_time, info.sky, info.fog); let (rain, thunder) = if self.dim == Dim::Overworld { @@ -8817,10 +9102,10 @@ impl Game<'_> { self.pick() .map(|h| { let state = self.world.block(h.pos[0], h.pos[1], h.pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); outline_after_terrain = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(h.pos[0], h.pos[1], h.pos[2])) .is_ok_and(|models| { @@ -8979,7 +9264,7 @@ impl Game<'_> { clouds: ((!title || live) && self.dim == Dim::Overworld && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) - .then(|| self.atlas.sprites.get("horizon/white")) + .then(|| self.gui.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { texture: &self.pack.clouds, @@ -9009,14 +9294,15 @@ impl Game<'_> { .mining .as_ref() .and_then(|m| { - self.atlas.sprites.get(&format!( + self.gui.atlas.sprites.get(&format!( "block/destroy_stage_{}", ((m.progress * 10.0) as u32).min(9) )) }) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]), end_portal_sprites: ["environment/end_sky", "entity/end_portal/end_portal"].map(|n| { - self.atlas + self.gui + .atlas .sprites .get(n) .map_or([0.0; 4], |r| [r.u0, r.v0, r.u1 - r.u0, r.v1 - r.v0]) @@ -9076,7 +9362,7 @@ impl Game<'_> { reason: horizon_client::level_loading::Reason, ) { use horizon_client::level_loading::{self, Reason, STATUS_RADIUS}; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); match reason { // The panorama and its blur are drawn by the renderer. @@ -9369,7 +9655,7 @@ impl Game<'_> { if !modified.is_empty() && let Err(e) = horizon_client::spans::time("save_chunks", || { self.save - .save_later(&modified, self.pack.assets.registry, &self.res.biomes) + .save_later(&modified, self.pack.assets.registry, self.res.biomes()) }) { log::warn!("Horizon: failed to save unloaded chunks: {e}"); @@ -9456,7 +9742,10 @@ impl ApplicationHandler for Game<'_> { } }; match self.new_renderer(window.clone()) { - Ok(r) => self.renderer = Some(r), + Ok(r) => { + self.renderer = Some(r); + self.world_renderer_ready = true; + } Err(e) => { self.error = Some(e); event_loop.exit(); @@ -9505,7 +9794,6 @@ impl ApplicationHandler for Game<'_> { event: key_event, .. } = &event && let PhysicalKey::Code(key) = key_event.physical_key - && self.title.is_none() { use horizon_client::debug_keys::KeyAction; let action = match (key_event.state, key_event.repeat) { @@ -9535,6 +9823,25 @@ impl ApplicationHandler for Game<'_> { // The press state of Horizon-style buttons. horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed); } + if self.pending_entry.is_some() + && matches!(&event, WindowEvent::KeyboardInput { event, .. } + if event.state == ElementState::Pressed + && event.physical_key == PhysicalKey::Code(KeyCode::Escape)) + { + self.pending_entry = None; + self.perf.cancel_world_opening(); + return; + } + if self.pending_entry.is_some() + && !matches!( + &event, + WindowEvent::CloseRequested + | WindowEvent::Resized(_) + | WindowEvent::RedrawRequested + ) + { + return; + } let result: Result<()> = (|| { match event { WindowEvent::CloseRequested => { @@ -9587,7 +9894,7 @@ impl ApplicationHandler for Game<'_> { && !horizon_client::ui_theme::horizon() { title.drag(self.cursor, (b.width, b.height)); - title.drag_field(&self.atlas, self.cursor.0); + title.drag_field(&self.gui.atlas, self.cursor.0); } if self.dragging && self.screen == Screen::Options { let _ = b; @@ -9626,15 +9933,25 @@ impl ApplicationHandler for Game<'_> { && self.sleeping.is_none() && self.player.is_some() && !self.extras_scroll(d) - && let Some((wheel, _)) = + && let Some((wheel, (_, vertical_steps))) = self.mouse .on_scroll(raw_x, raw_y, discrete, wheel_sensitivity) { - self.selected = horizon_client::mouse::ScrollWheelHandler::next_selection( - f64::from(wheel), - self.selected as i32, - 9, - ) as usize; + if self.spectator() { + if let Some(player) = &mut self.player { + player.flying_speed = horizon_client::mouse::spectator_flying_speed( + player.flying_speed, + vertical_steps, + ); + } + } else { + self.selected = + horizon_client::mouse::ScrollWheelHandler::next_selection( + f64::from(wheel), + self.selected as i32, + 9, + ) as usize; + } } if self.screen == Screen::Chat && d != 0.0 { self.chat_scroll(d); @@ -9692,7 +10009,7 @@ impl ApplicationHandler for Game<'_> { .map(|r| [r.config.width, r.config.height]) .unwrap_or([1, 1]); let mut b = HudBatch::new(size); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let shift = self.has_shift_down(); let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| { if horizon_client::ui_theme::horizon() { @@ -10181,6 +10498,11 @@ impl ApplicationHandler for Game<'_> { } } fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) { + if let Err(error) = self.resume_world_entry() { + self.error = Some(error); + event_loop.exit(); + return; + } self.poll_control(event_loop); self.poll_pads(event_loop); if self.options.frames.is_some() && self.started.elapsed() > self.options.timeout { @@ -10236,7 +10558,7 @@ impl<'a> Game<'a> { fn new( res: &'a Arc, pack: PackResources, - atlas: HudAtlas, + gui: UiResources, options: Options, settings: Settings, audio: Audio, @@ -10245,7 +10567,7 @@ impl<'a> Game<'a> { let registry = pack.assets.registry; // Until a world is opened the streamer is idle. let mut streaming = Streaming::new( - Arc::new(TestTerrain::new(registry, &res.biomes)?), + Arc::new(TestTerrain::new(registry, res.biomes())?), pack.context.clone(), 1, ); @@ -10265,18 +10587,22 @@ impl<'a> Game<'a> { minecarts::CartModels::load(document.as_ref()), ) }; - let world = World::new(res.facts.air, 0); + let world = World::new(res.facts().air, 0); let creative = options.creative; let inventory = vec![None; 36]; let now = Instant::now(); let look = options.look; - let particles = horizon_client::particles::ParticleEngine::new(&root, &atlas.sprites); + let particles = horizon_client::particles::ParticleEngine::new(&root, &gui.atlas.sprites); Ok(Game { res: res.clone(), - collision: &res.collision, - motion: &res.motion, + rest_loader: None, + pending_entry: None, + pending_pack_reload: false, + world_renderer_ready: false, + collision: res.collision(), + motion: res.motion(), pack, - atlas, + gui, fog: Default::default(), screen_fx: Default::default(), world, @@ -10431,6 +10757,7 @@ impl<'a> Game<'a> { end: Default::default(), block_ticks: Ticks::new(0), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -10561,23 +10888,146 @@ impl<'a> Game<'a> { struct Loaded { root: PathBuf, pack_error: Option, - resources: Resources, + resources: Arc, + rest_loader: Option, pack: PackResources, - atlas: HudAtlas, + /// The menu bundle, for the synchronous launch; the loading screen receives + /// it earlier through its own channel. + gui: Option, } -/// The loader's checkpoints, in order; the loading screen reports them. -const STAGES: u32 = 9; -const STAGE_LINES: [&str; 9] = [ +/// What the background loader publishes: the menu bundle as soon as it is +/// ready, then the core bundle with a handle to the rest worker. +enum LoaderMsg { + Ui(UiResources, PathBuf), + Done(std::result::Result), +} + +enum PendingWorldEntry { + Local { + folder: String, + name: Option, + seed: Option, + creative: bool, + create: Option>, + }, + Server { + address: String, + name: String, + }, +} + +struct WorldRestLoader { + progress: Progress, + handle: JoinHandle>, +} + +impl WorldRestLoader { + fn ready(&self) -> Result { + // No time limit: the title stays usable while this loads, and a slow + // disk or a debug build can take minutes. A failure ends the thread + // and is reported by `finish`. + Ok(self.handle.is_finished()) + } + + fn finish(self) -> Result<()> { + self.handle + .join() + .map_err(|_| "world resource loader panicked")? + .map_err(Into::into) + } +} + +impl Game<'_> { + fn defer_world_entry(&mut self, entry: PendingWorldEntry) -> Result { + self.poll_world_rest()?; + if self.rest_loader.is_none() { + return Ok(false); + } + self.perf.world_opening(); + if self.title.is_none() { + self.title = Some(Title::new( + std::env::current_dir()?.join("saves"), + &self.options.resources, + )); + } + self.pending_entry = Some(entry); + log::info!("Horizon: world entry waiting for world resources"); + Ok(true) + } + + fn resume_world_entry(&mut self) -> Result<()> { + self.poll_world_rest()?; + if self.rest_loader.is_some() { + return Ok(()); + } + if std::mem::take(&mut self.pending_pack_reload) { + self.reload_packs(); + } + match self.pending_entry.take() { + Some(PendingWorldEntry::Local { + folder, + name, + seed, + creative, + create, + }) => { + self.open_world(&folder, name.as_deref(), seed, creative, create.as_deref())?; + } + Some(PendingWorldEntry::Server { address, name }) => { + self.connect_server(&address, &name)?; + } + None => {} + } + Ok(()) + } + + fn poll_world_rest(&mut self) -> Result<()> { + if let Some(loader) = &self.rest_loader + && loader.ready()? + { + self.rest_loader + .take() + .ok_or("missing world loader")? + .finish()?; + } + Ok(()) + } + + fn join_world_rest(&mut self) -> Result<()> { + if self.rest_loader.is_some() { + let waited = Instant::now(); + log::info!("Horizon: waiting for world resources"); + while self.rest_loader.is_some() { + self.poll_world_rest()?; + if self.rest_loader.is_some() { + std::thread::sleep(Duration::from_millis(10)); + } + } + log::info!( + "Horizon: world resources joined after {} ms", + waited.elapsed().as_millis() + ); + } + if self.res.rest.get().is_none() { + return Err("world resources are unavailable".into()); + } + Ok(()) + } +} + +const STAGES: u32 = 10; +const STAGE_LINES: [&str; 10] = [ + "Loading menu", "Loading assets", "Loading block facts", - "Loading items", "Loading biomes", "Loading pack tables", - "Loading atlas", "Loading collision", - "Loading resources", - "Starting audio", + "Loading items", + "Loading recipes", + "Loading world resources", + "World resources ready", ]; /// The background loader's checkpoint, read by the loading screen each frame. @@ -10614,26 +11064,53 @@ fn synchronous_startup(options: &Options) -> bool { || 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. +/// The synchronous launch loads both phases; an ordinary launch returns the +/// core bundle while the rest worker keeps loading. fn load_resources( mut root: PathBuf, vanilla_root: &std::path::Path, settings: &Settings, started: Instant, - on_stage: &(dyn Fn(u32) + Sync), + menu: bool, + progress: &Progress, + publish: &mut dyn FnMut(UiResources, &std::path::Path), ) -> Result { + let requested_root = root.clone(); + let threads = settings.horizon.worker_threads(); + // Stage A: the menu bundle (atlas and panorama). With a loading screen it is + // published at once so the title backdrop can appear while the world bundle + // loads; the synchronous launch instead carries it in `Loaded`. + let mut loaded_gui = None; + let mut ui_ready = false; + if let Ok(ui) = UiResources::load(&root) { + if menu { + horizon_client::telemetry::mark_ui_ready(); + log::info!( + "Horizon: UI bundle ready after {} ms", + started.elapsed().as_millis() + ); + publish(ui, &root); + } else { + loaded_gui = Some(ui); + } + ui_ready = true; + } + progress.set(0); let mut pack_error = None; - let assets = match Assets::load(&root) { - Ok(assets) => assets, + let (assets, render) = match Assets::load(&root).and_then(|assets| { + let render = assets.reload(&root)?; + Ok((assets, render)) + }) { + Ok(bundle) => bundle, // Minecraft.rollbackResourcePacks: the packs break loading, start // with the game's own resources. 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()); root = vanilla_root.to_path_buf(); - Assets::load(vanilla_root)? + let assets = Assets::load(vanilla_root)?; + let render = assets.reload(vanilla_root)?; + (assets, render) } Err(e) => { return Err(format!( @@ -10643,38 +11120,68 @@ fn load_resources( } }; let assets = Arc::new(assets); + let render = Arc::new(render); + // The menu bundle must come from the same root as the world bundle. + if !ui_ready || root != requested_root { + let ui = UiResources::load(&root)?; + if menu { + horizon_client::telemetry::mark_ui_ready(); + log::info!( + "Horizon: UI bundle ready after {} ms", + started.elapsed().as_millis() + ); + publish(ui, &root); + } else { + loaded_gui = Some(ui); + } + } log::info!("load assets: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(0); + progress.set(1); let behaviour_json: serde_json::Value = serde_json::from_reader(std::io::BufReader::new( std::fs::File::open(root.join("block-behaviours.json"))?, ))?; + // The block facts, the biomes and the environment are independent reads: + // run them together, within the worker budget the settings allow. + let registry = assets.registry; + let load_facts = || { + BlockFacts::load_with_projection(&root, registry, &behaviour_json) + .map_err(|e| e.to_string()) + }; + let load_biomes = || Biomes::load(&root).map_err(|e| e.to_string()); + let load_environment = || Environment::load(&root).map_err(|e| e.to_string()); + let (facts, biomes, environment) = if threads > 1 { + std::thread::scope(|scope| { + let facts = scope.spawn(load_facts); + let biomes = scope.spawn(load_biomes); + let environment = scope.spawn(load_environment); + ( + facts.join().unwrap(), + biomes.join().unwrap(), + environment.join().unwrap(), + ) + }) + } else { + (load_facts(), load_biomes(), load_environment()) + }; let (facts, gameplay_projection) = - BlockFacts::load_with_projection(&root, assets.registry, &behaviour_json)?; - let mob_data = horizon_client::mobs::MobData::load(&root, &facts); - horizon_client::mobs::trial_spawner::load_registry(&root); + facts.map_err(|e| -> Box { e.into() })?; + let biomes = Arc::new(biomes.map_err(|e| -> Box { e.into() })?); + let environment = environment.map_err(|e| -> Box { e.into() })?; 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)?; + progress.set(2); log::info!("load biomes+env: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(3); + progress.set(3); let light = Arc::new(LightTables::load(&root, assets.registry, &facts)?); - let pack = PackResources::load(&root, assets.clone(), &facts, biomes.clone(), light)?; + let pack = PackResources::load(&root, assets.clone(), render, &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], - &settings.language, - )); - log::info!("load atlas: {:.2}s", started.elapsed().as_secs_f32()); - on_stage(5); + progress.set(4); + if !menu { + horizon_client::ui::load_metadata(&root); + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&root], + &settings.language, + )); + } let registry_owner = assets.clone(); let collision = collisions::load(&root, registry_owner.registry)?; let motion = MotionResources::load_with_facts(&root, ®istry_owner, &facts)?; @@ -10682,8 +11189,108 @@ fn load_resources( "load collision+motion: {:.2}s", started.elapsed().as_secs_f32() ); - on_stage(6); - let threads = settings.horizon.worker_threads(); + progress.set(5); + let resources = Resources { + core: WorldCore { + facts, + biomes: biomes.clone(), + environment, + collision, + motion, + threads, + }, + rest: std::sync::OnceLock::new(), + }; + let resources = Arc::new(resources); + if menu { + horizon_client::telemetry::mark_core_ready(); + log::info!( + "Horizon: core-ready after {} ms", + started.elapsed().as_millis() + ); + } + let rest_loader = if menu { + let resources = resources.clone(); + let root = root.clone(); + let rest_progress = progress.clone(); + let progress = progress.clone(); + let handle = std::thread::Builder::new() + .name("world-rest-loader".into()) + .spawn(move || { + let rest = load_world_rest( + &root, + &resources, + &assets, + &behaviour_json, + &gameplay_projection, + &progress, + started, + ) + .map_err(|error| error.to_string())?; + resources + .rest + .set(rest) + .map_err(|_| "world resources already loaded".to_owned())?; + progress.set(9); + horizon_client::telemetry::mark_rest_ready(); + log::info!( + "Horizon: rest-ready after {} ms", + started.elapsed().as_millis() + ); + Ok(()) + })?; + Some(WorldRestLoader { + progress: rest_progress, + handle, + }) + } else { + let rest = load_world_rest( + &root, + &resources, + &assets, + &behaviour_json, + &gameplay_projection, + progress, + started, + )?; + resources + .rest + .set(rest) + .map_err(|_| "world resources already loaded")?; + None + }; + Ok(Loaded { + root, + pack_error, + resources, + rest_loader, + pack, + gui: loaded_gui, + }) +} + +fn load_world_rest( + root: &std::path::Path, + resources: &Resources, + assets: &Assets, + behaviour_json: &serde_json::Value, + gameplay_projection: &[horizon_client::blocks::GameplayProjection], + progress: &Progress, + started: Instant, +) -> Result { + let facts = resources.facts(); + let biomes = resources.biomes(); + let threads = resources.threads(); + let registry_owner = assets; + progress.set(6); + let mob_data = horizon_client::mobs::MobData::load(root, facts); + horizon_client::mobs::trial_spawner::load_registry(root); + + let items = Items::load(root, assets.registry, facts)?; + log::info!("load items: {:.2}s", started.elapsed().as_secs_f32()); + progress.set(7); + let recipes = Recipes::load(root, &items)?; + let transformers = horizon_client::block_transform::Transformers::load(root, assets.registry)?; log::info!( "Horizon: resources loaded in {:.1}s; {} block states, {} items, {} biomes; {} worker threads", started.elapsed().as_secs_f32(), @@ -10692,59 +11299,42 @@ fn load_resources( biomes.list.len(), threads ); - let stations = horizon_client::stations::StationData::load(&root, &items); + progress.set(8); + 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 = Resources { + horizon_client::animate_tick::AnimateTables::load(root, registry_owner.registry, biomes)?; + let fog = horizon_client::fog::FogTables::load(root, biomes); + Ok(WorldRest { stations, - facts, items, recipes, transformers, - biomes, - environment, - collision, - motion, - providers: Providers::load(&root), + providers: Providers::load(root), block_entity_render: horizon_client::block_entity_render::BlockEntityRenderer::load( - &root, + root, registry_owner.registry, )?, animate, fog, - music: horizon_client::music::MusicTables::load(&root), - ambient: horizon_client::ambience::AmbientTables::load(&root), - nether_environment: Environment::load_dimension(&root, "the_nether", false)?, - end_environment: Environment::load_dimension(&root, "the_end", false)?, + music: horizon_client::music::MusicTables::load(root), + ambient: horizon_client::ambience::AmbientTables::load(root), + nether_environment: Environment::load_dimension(root, "the_nether", false)?, + end_environment: Environment::load_dimension(root, "the_end", false)?, behaviours: Behaviours::load_with_gameplay( registry_owner.registry, - &root, - &behaviour_json, - &gameplay_projection, + root, + behaviour_json, + gameplay_projection, )?, - mob_types: MobTypes::load(&root)? + mob_types: MobTypes::load(root)? .types .into_iter() .map(|(k, v)| (k, Arc::new(v))) .collect(), mob_data, - threads, - player_type: perspective::player_type(&root), - player_arm: horizon_client::mobs::load_model(&root, "minecraft:player#main") + 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, }) } @@ -10754,10 +11344,11 @@ fn build_renderer( window: Arc, offscreen: bool, pack: &PackResources, - atlas: &HudAtlas, + gui: &UiResources, previous: Option<&Renderer>, ) -> Result { - let assets = &pack.assets; + let assets = &pack.render; + let atlas = &gui.atlas; let mut renderer = pollster::block_on(Renderer::new( window, offscreen, @@ -10769,7 +11360,7 @@ fn build_renderer( &assets.animations, (&atlas.pixels, atlas.width, atlas.height), (&pack.forcefield.2, pack.forcefield.0), - &pack.panorama, + &gui.panorama, previous, ))?; renderer.hud.fire_animations = atlas @@ -10781,18 +11372,22 @@ fn build_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. +/// white block-sprite layer, an empty border texture and the title panorama +/// once the menu bundle is ready. fn loading_renderer( window: Arc, offscreen: bool, - atlas: Option<&HudAtlas>, + gui: Option<&UiResources>, + previous: Option<&Renderer>, ) -> Result { static FORCEFIELD: [u8; 4] = [0; 4]; static EMPTY_HUD: [u8; 4] = [0, 0, 0, 255]; - let panorama = horizon_client::gfx::panorama::Faces { + let empty_panorama = horizon_client::gfx::panorama::Faces { size: 1, pixels: [0u8; 4].repeat(6), }; + let panorama = gui.map_or(&empty_panorama, |gui| gui.panorama.as_ref()); + let atlas = gui.map(|gui| &gui.atlas); let (pixels, width, height) = match atlas { Some(atlas) => (atlas.pixels.as_slice(), atlas.width, atlas.height), None => (EMPTY_HUD.as_slice(), 1, 1), @@ -10808,8 +11403,8 @@ fn loading_renderer( &[], (pixels, width, height), (&FORCEFIELD[..], 1), - &panorama, - None, + panorama, + previous, ))?; if let Some(atlas) = atlas { renderer.hud.fire_animations = atlas @@ -10879,12 +11474,13 @@ fn loading_frame(hud: &HudBatch) -> Frame<'_> { fn start_game<'a>( res: &'a Arc, pack: PackResources, - atlas: HudAtlas, + gui: UiResources, options: Options, pack_error: Option, audio: Audio, vanilla_root: PathBuf, started: Instant, + rest_loader: Option, ) -> Result>> { let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); @@ -10898,7 +11494,8 @@ fn start_game<'a>( if let Some(d) = options.distance_override { settings.render_distance = d; } - let mut game = Game::new(res, pack, atlas, options, settings, audio)?; + let mut game = Game::new(res, pack, gui, options, settings, audio)?; + game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { game.open_options_at(true, horizon_client::options_ui::Page::Packs); @@ -11029,7 +11626,7 @@ fn run_event_loop(mut game: Game<'_>) -> Result<()> { struct Loading { window: Option>, renderer: Option, - atlas: Option, + gui: Option, settings: Settings, fullscreen: horizon_client::window::FullscreenState, options: Option, @@ -11037,10 +11634,11 @@ struct Loading { pack_error: Option, started: Instant, progress: Progress, - receiver: Receiver>, + receiver: Receiver, loaded: Option>, handle: Option>, shown: bool, + menu: startup_menu::StartupMenu, error: Option>, } impl Loading { @@ -11072,7 +11670,7 @@ impl Loading { } }; let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); - match loading_renderer(window.clone(), offscreen, self.atlas.as_ref()) { + match loading_renderer(window.clone(), offscreen, self.gui.as_ref(), None) { Ok(r) => self.renderer = Some(r), Err(e) => { self.error = Some(e); @@ -11091,31 +11689,44 @@ impl Loading { 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); - } + if let Err(error) = self.menu_event(event_loop, event) { + self.error = Some(error); + event_loop.exit(); + } + } + /// The menu bundle arrived: rebuild the loading screen with the real atlas + /// and title panorama. + fn set_ui(&mut self, gui: UiResources, root: PathBuf) { + log::info!( + "Horizon: loading the title artwork after {} ms", + self.started.elapsed().as_millis() + ); + self.menu.set_root(root, &self.settings); + self.gui = Some(gui); + horizon_client::ui_theme::reset_atlas(); + self.apply_menu_settings(); + let Some(window) = self.window.clone() else { + return; + }; + let offscreen = self.options.as_ref().is_some_and(|o| o.offscreen); + if let Some(renderer) = &mut self.renderer { + renderer.release_surface(); + } + match loading_renderer(window, offscreen, self.gui.as_ref(), self.renderer.as_ref()) { + Ok(r) => { + 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.renderer = Some(r); } - WindowEvent::RedrawRequested => self.draw(), - _ => {} + Err(e) => self.error = Some(e), } } 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 Err(error) = self.poll_menu_resources() { + self.error = Some(error); + event_loop.exit(); + return; } if let Some(w) = &self.window { if self.options.as_ref().is_some_and(|o| o.offscreen) { @@ -11127,22 +11738,24 @@ impl Loading { event_loop.set_control_flow(ControlFlow::Poll); } fn draw(&mut self) { - let Some(renderer) = self.renderer.as_mut() else { + let Some(size) = self + .renderer + .as_ref() + .map(|r| [r.config.width, r.config.height]) + 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(), - ); - } + self.draw_menu(&mut batch); let frame = loading_frame(&batch); - if let Err(e) = renderer.render(&frame) { - log::warn!("Horizon: loading screen frame failed: {e}"); + if let Some(renderer) = &mut self.renderer { + match renderer.render(&frame) { + Ok(true) if self.gui.is_some() && self.menu.pending.is_none() => { + self.menu.perf.title_shown() + } + Ok(_) => {} + Err(e) => log::warn!("Horizon: loading screen frame failed: {e}"), + } } if !self.shown { self.shown = true; @@ -11155,13 +11768,10 @@ impl Loading { 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) - }; + // StartupMenu owns world selection until it can hand it to Game. + options.world = None; + options.server = None; + let gui = self.gui.take().ok_or("missing menu bundle")?; 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 { @@ -11171,29 +11781,43 @@ impl Loading { window.clone(), options.offscreen, &loaded.pack, - &loaded.atlas, + &gui, self.renderer.as_ref(), )?; + log::info!( + "Horizon: world renderer ready after {} ms", + self.started.elapsed().as_millis() + ); + // Audio is created on the main thread, after the core is ready. + let audio = if options.dedicated.is_some() { + Audio::silent(&options.resources) + } else { + Audio::new(&options.resources) + }; 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 res: &'static Arc = Box::leak(Box::new(loaded.resources)); let Some(mut game) = start_game( res, loaded.pack, - loaded.atlas, + gui, options, pack_error, audio, self.vanilla_root.clone(), self.started, + loaded.rest_loader, )? else { return Ok(None); }; game.window = Some(window); game.renderer = Some(renderer); + game.world_renderer_ready = true; game.fullscreen = self.fullscreen; + self.menu.handoff(&mut game); + game.settings = self.settings.clone(); game.apply_settings(); game.previous = Instant::now(); Ok(Some(game)) @@ -11242,7 +11866,11 @@ impl ApplicationHandler for App { event_loop.exit(); return; } - match loading.loaded.take() { + match if loading.menu.reload_packs { + None + } else { + loading.loaded.take() + } { None => Step::Waiting, Some(Err(e)) => Step::Failed(e.into()), Some(Ok(loaded)) => match loading.finish(loaded) { @@ -11281,28 +11909,15 @@ fn run_loading( pack_error: Option, started: Instant, ) -> Result<()> { + horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); 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 (receiver, loader) = + startup_menu::spawn_loader(&options, &settings, &vanilla_root, started, &progress)?; + let menu = startup_menu::StartupMenu::new(&options, pack_error.as_deref())?; let loading = Loading { window: None, renderer: None, - atlas, + gui: None, settings, fullscreen: horizon_client::window::FullscreenState::new(false), options: Some(options), @@ -11314,6 +11929,7 @@ fn run_loading( loaded: None, handle: Some(loader), shown: false, + menu, error: None, }; let mut app = App::Loading(Box::new(loading)); @@ -11348,6 +11964,9 @@ pub fn run() -> Result<()> { // 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")); + if !synchronous_startup(&options) { + return run_loading(options, early_settings, vanilla_root, None, started); + } let mut pack_error = None; options.resources = packs::startup_root(&vanilla_root, &early_settings.resource_packs) .unwrap_or_else(|e| { @@ -11360,34 +11979,33 @@ pub fn run() -> Result<()> { &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, - &|_| {}, + false, + &Progress::new(), + &mut |_, _| {}, )?; + let gui = loaded.gui.ok_or("missing menu bundle")?; 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 resources = loaded.resources; let game = start_game( &resources, loaded.pack, - loaded.atlas, + gui, options, loaded.pack_error.or(pack_error), audio, vanilla_root, started, + loaded.rest_loader, )?; if let Some(game) = game { run_event_loop(game)?; @@ -11469,6 +12087,64 @@ mod tests { assert!(hud_overlays::sleep_overlay(320, 240, timer as i32).is_empty()); } + #[test] + fn world_rest_poll_does_not_wait_for_a_blocked_worker() { + let (release, wait) = std::sync::mpsc::channel(); + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(move || { + wait.recv().unwrap(); + Ok(()) + }), + }; + assert!(!loader.ready().unwrap()); + release.send(()).unwrap(); + loader.finish().unwrap(); + } + + #[test] + fn world_rest_poll_waits_for_a_slow_worker() { + let (release, wait) = std::sync::mpsc::channel(); + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(move || { + wait.recv().unwrap(); + Ok(()) + }), + }; + // However long it takes, a worker still loading is not an error. + assert!(!loader.ready().unwrap()); + release.send(()).unwrap(); + while !loader.ready().unwrap() { + std::thread::sleep(Duration::from_millis(1)); + } + loader.finish().unwrap(); + } + + #[test] + fn world_rest_worker_failure_reaches_the_client() { + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(|| Err("missing world table".to_owned())), + }; + assert_eq!( + loader.finish().unwrap_err().to_string(), + "missing world table" + ); + } + + #[test] + fn world_rest_worker_panic_reaches_the_client() { + let loader = WorldRestLoader { + progress: Progress::new(), + handle: std::thread::spawn(|| panic!("broken loader")), + }; + assert_eq!( + loader.finish().unwrap_err().to_string(), + "world resource loader panicked" + ); + } + /// 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 882b5cc93..d13ed6b13 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -106,7 +106,7 @@ impl adv::World for View<'_, '_> { .map(|c| { self.0 .res - .biomes + .biomes() .get(c.biome(p[0], p[1], p[2])) .name .clone() @@ -118,7 +118,7 @@ impl adv::World for View<'_, '_> { } fn block(&self, p: [i32; 3]) -> (String, BTreeMap) { let state = self.0.world.block(p[0], p[1], p[2]); - let name = self.0.res.facts.get(state).name.to_string(); + let name = self.0.res.facts().get(state).name.to_string(); let props = self .0 .pack @@ -138,7 +138,7 @@ impl adv::World for View<'_, '_> { match self .0 .res - .facts + .facts() .get(self.0.world.block(p[0], p[1], p[2])) .fluid { @@ -152,7 +152,7 @@ impl adv::World for View<'_, '_> { !self .0 .res - .facts + .facts() .get(self.0.world.block(p[0], y, p[2])) .full_collision }) @@ -165,19 +165,19 @@ impl adv::World for View<'_, '_> { (1..=5).any(|d| { self.0 .res - .facts + .facts() .get(self.0.world.block(p[0], p[1] - d, p[2])) .name .ends_with("campfire") }) } fn in_tag(&self, registry: &str, tag: &str, id: &str) -> bool { - let items = &self.0.res.items; + let items = &self.0.res.items(); match registry { "item" => items.item_tags.get(tag).is_some_and(|t| t.contains(id)), "block" => items.block_tags.get(tag).is_some_and(|t| t.contains(id)), - "entity_type" => self.0.res.mob_data.entity_has(tag, id), - "worldgen/biome" => self.0.res.mob_data.biome_has(tag, id), + "entity_type" => self.0.res.mob_data().entity_has(tag, id), + "worldgen/biome" => self.0.res.mob_data().biome_has(tag, id), _ => false, } } @@ -408,6 +408,9 @@ impl Game<'_> { } } } + if hits.is_empty() { + return; + } let date = now_text(); for (ai, ci) in hits { let a = &tree.list[ai]; @@ -454,17 +457,17 @@ impl Game<'_> { .rewards .recipes .iter() - .filter(|r| self.res.stations.recipe_index.contains(r)) + .filter(|r| self.res.stations().recipe_index.contains(r)) .cloned() .collect(); let (_, unlocked) = self .level .recipe_book - .add_recipes(&self.res.stations.recipe_index, &rewards); + .add_recipes(&self.res.stations().recipe_index, &rewards); for table in &a.rewards.loot { let items = self .res - .items + .items() .loot_table(table, false, None, &mut self.world.random); for s in items { if let Some(rest) = self.give(s) @@ -497,10 +500,13 @@ impl Game<'_> { // PlayerList.broadcastSystemMessage: everyone hears of a // network player's advancement. match self.lan_acting_name.clone() { - Some(player) => self - .adv - .announced - .push(Text::translate(key, &[Text::literal(&player), name])), + // Player.getDisplayName. + Some(_) => { + let player = self.target_name(super::commands::Target::Player); + self.adv + .announced + .push(Text::translate(key, &[player, name])); + } None => self.system_message(Text::translate( key, &[Text::literal(super::chat::PLAYER_NAME), name], @@ -549,7 +555,7 @@ impl Game<'_> { .filter_map(|s| s.as_ref()) .filter(|s| { self.res - .items + .items() .get(&s.item) .is_some_and(|i| s.count >= i.max_stack) }) @@ -790,11 +796,11 @@ impl Game<'_> { if let Some((station, item)) = recipe { // RecipeToast: black description under a purple title, the // station at 0.6 scale in the corner over the cycling result. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0); let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!"); let description = self.translate("recipe.toast.description", "Check your recipe book"); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false); batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false); let start = batch.vertices.len(); @@ -803,7 +809,7 @@ impl Game<'_> { self.draw_item_model(batch, &item, x + 8.0, 8.0); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0); let (key, color) = match frame { Frame::Task => ("advancements.toast.task", 0xFF00_FFFF), @@ -832,18 +838,25 @@ pub(super) fn adv_name(a: &adv::Advancement) -> Text { Frame::Challenge => text::DARK_PURPLE, _ => text::GREEN, }; - let tooltip = text_of(&d.title) - .with_color(color) + // Advancement.decorateName: the title in the frame's colour (styles + // merged into it), a new line and the description. + let coloured = text_of(&d.title).with_color(color); + let mut component = coloured.component(); + if let Some(o) = component.as_object_mut() { + o.insert( + "extra".into(), + serde_json::json!(["\n", text_of(&d.description).component()]), + ); + } + let tooltip = coloured .append("\n") - .append(text_of(&d.description)); + .append(text_of(&d.description)) + .with_component(component); let title = text_of(&d.title).with_style(&Style { hover: Some(Box::new(tooltip)), ..Style::default() }); - Text::literal("[") - .append(title) - .append("]") - .with_color(color) + Text::translate("chat.square_brackets", &[title]).with_color(color) } impl Game<'_> { /// `AdvancementCommands.Action.GRANT` on one advancement (or one of diff --git a/crates/horizon-client/src/game/advancements_screen.rs b/crates/horizon-client/src/game/advancements_screen.rs index 759588887..211bab362 100644 --- a/crates/horizon-client/src/game/advancements_screen.rs +++ b/crates/horizon-client/src/game/advancements_screen.rs @@ -269,7 +269,7 @@ impl Game<'_> { } /// `AdvancementWidget`'s title lines, description lines and width. fn adv_widget_text(&self, i: usize) -> (Vec, Vec, f32) { - let font = &self.atlas.font; + let font = &self.gui.atlas.font; let a = &self.adv.tree.list[i]; let Some(d) = &a.display else { return (Vec::new(), Vec::new(), 0.0); @@ -332,7 +332,7 @@ impl Game<'_> { let (sx, sy) = self.adv_ui.scroll.unwrap_or_default(); let (sx, sy) = (sx.floor() as i32, sy.floor() as i32); self.adv_tick_hover(&view, sx, sy, left, top); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("gui.advancements", &[]); let tw = atlas.font.width_text(&title); @@ -444,7 +444,7 @@ impl Game<'_> { } let (x, y) = pos(i); let (x, y) = ((ox + x) as f32, (oy + y) as f32); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_scaled( atlas, frame_sprite(d.frame, done), @@ -461,7 +461,7 @@ impl Game<'_> { } } // The window, tabs and title. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/advancements/window", @@ -475,7 +475,7 @@ impl Game<'_> { let (x, y) = tab_pos(ty, i); let sprite = tab_sprite(ty, i, ty.3, Some(t) == tab); batch.sprite_scaled( - &self.atlas, + &self.gui.atlas, &sprite, left + x, top + y, @@ -494,7 +494,7 @@ impl Game<'_> { } } } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let title = tab.and_then(|t| tree.list[t].display.as_ref()).map_or_else( || Text::translate("gui.advancements", &[]), |d| text_of(&d.title), @@ -509,7 +509,7 @@ impl Game<'_> { } } // Done. - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( @@ -532,7 +532,7 @@ impl Game<'_> { let (cx, cy) = self.cursor; if cx > x && cx < x + ty.1 && cy > y && cy < y + ty.2 { if let Some(d) = &tree.list[t].display { - ui::tooltip(batch, &self.atlas, &[text_of(&d.title)], self.cursor); + ui::tooltip(batch, &self.gui.atlas, &[text_of(&d.title)], self.cursor); } break; } @@ -616,7 +616,7 @@ impl Game<'_> { ], ) }); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let progress_w = progress.as_ref().map_or(0.0, |t| atlas.font.width_text(t)) as i32; let top_side = title_bottom + desc_h >= INSIDE_H; let amount = if a.criteria.is_empty() || total == 0 { diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index b11fdd552..5d7d294dd 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -325,7 +325,7 @@ impl Game<'_> { let state = self.world.block(pos[0], pos[1], pos[2]); let mut v = json!({ "pos": pos, - "block": &*self.res.facts.get(state).name, + "block": &*self.res.facts().get(state).name, "state": self.state_string(state), "loaded": self.world.chunks.contains_key(&(pos[0] >> 4, pos[2] >> 4)), }); @@ -477,6 +477,8 @@ impl Game<'_> { "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 })), + // The arm swings started (LivingEntity.swing). + "swings": self.swings_started, "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, @@ -579,7 +581,7 @@ impl Game<'_> { push( [m.position.x, m.position.y, m.position.z], m.kind.id.as_ref(), - json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby() }), + json!({ "id": m.id, "kind": "mob", "health": m.health, "baby": m.is_baby(), "hurt_time": m.hurt_time }), ); } for item in &self.dropped { @@ -677,17 +679,25 @@ impl Game<'_> { /// Whether a block stops movement, for the path finder. fn blocks_motion(&self, pos: [i32; 3]) -> bool { - let f = self.res.facts.get(self.world.block(pos[0], pos[1], pos[2])); + let f = self + .res + .facts() + .get(self.world.block(pos[0], pos[1], pos[2])); f.full_collision || f.legacy_solid } fn walkable(&self, n: Node) -> bool { let below = self.world.block(n[0], n[1] - 1, n[2]); let lava = |p: [i32; 3]| { - &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name == "minecraft:lava" + &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name + == "minecraft:lava" }; self.world.chunks.contains_key(&(n[0] >> 4, n[2] >> 4)) && (self.blocks_motion([n[0], n[1] - 1, n[2]]) - || self.res.facts.get(below).fluid != horizon_client::blocks::Fluid::None) + || self.res.facts().get(below).fluid != horizon_client::blocks::Fluid::None) && !self.blocks_motion(n) && !self.blocks_motion([n[0], n[1] + 1, n[2]]) && !lava(n) @@ -748,7 +758,11 @@ impl Game<'_> { if !clear || !self.walkable(m) { continue; } - let water = self.res.facts.get(self.world.block(m[0], m[1], m[2])).fluid + let water = self + .res + .facts() + .get(self.world.block(m[0], m[1], m[2])) + .fluid != horizon_client::blocks::Fluid::None; let step = 10 + if dy != 0 { 5 } else { 0 } + if water { 30 } else { 0 }; let c = base + step; @@ -958,10 +972,10 @@ impl Game<'_> { for z in lo[2]..=hi[2] { for x in lo[0]..=hi[0] { let state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } - let name = self.res.facts.get(state).name.to_string(); + let name = self.res.facts().get(state).name.to_string(); *census.entry(name).or_insert(0) += 1; list.push(json!([x, y, z, self.state_string(state)])); } @@ -1013,7 +1027,7 @@ impl Game<'_> { for z in c[2] - radius..=c[2] + radius { for x in c[0] - radius..=c[0] + radius { let state = self.world.block(x, y, z); - if *self.res.facts.get(state).name == *want { + if *self.res.facts().get(state).name == *want { let d = dist(eye, [x, y, z].map(|v| f64::from(v) + 0.5)); found.push((d, [x, y, z])); } @@ -1221,7 +1235,7 @@ impl Game<'_> { self.playing()?; let pos = a.block_pos(0)?; let before = self.world.block(pos[0], pos[1], pos[2]); - if self.res.facts.is_air(before) { + if self.res.facts().is_air(before) { return Err(format!("there is no block at {pos:?}").into()); } self.aim_block(pos, None)?; @@ -1250,24 +1264,24 @@ impl Game<'_> { .ok_or("nothing in hand to place; select an item")?; let held = held.item.clone(); let before = self.world.block(pos[0], pos[1], pos[2]); - if !self.res.facts.get(before).replaceable && !self.res.facts.is_air(before) { + if !self.res.facts().get(before).replaceable && !self.res.facts().is_air(before) { return Err(format!( "{pos:?} holds {}; break it first", - self.res.facts.get(before).name + self.res.facts().get(before).name ) .into()); } // A replaceable block there (grass, snow) is clicked itself, as // a player would; otherwise the face of a neighbour touching it. - let mut aimed = !self.res.facts.is_air(before) - && !self.res.facts.get(before).outline.is_empty() + let mut aimed = !self.res.facts().is_air(before) + && !self.res.facts().get(before).outline.is_empty() && self.aim_block(pos, None).is_ok(); for (_, d) in FACES.iter().filter(|_| !aimed) { let d = *d; let support = add(pos, d); let state = self.world.block(support[0], support[1], support[2]); - let f = self.res.facts.get(state); - if self.res.facts.is_air(state) + let f = self.res.facts().get(state); + if self.res.facts().is_air(state) || f.replaceable || f.fluid != horizon_client::blocks::Fluid::None && !f.waterlogged { @@ -1534,6 +1548,13 @@ impl Game<'_> { return Err("command TEXT".into()); } let command = format!("/{text}"); + // Single player's console is its server thread's. + if let Some(server) = &self.integrated { + let chat = server + .call(move |g| g.owner_console_command(&command)) + .ok_or("the integrated server stopped")?; + return ok(json!({ "ok": true, "chat": chat })); + } if self.remote.is_some() { self.send_chat(&command); return ok(json!({ "ok": true })); @@ -1933,7 +1954,10 @@ impl Game<'_> { // Step up onto the next block, or out of water. let in_water = { let b = p.map(|v| v.floor() as i32); - self.res.facts.get(self.world.block(b[0], b[1], b[2])).fluid + self.res + .facts() + .get(self.world.block(b[0], b[1], b[2])) + .fluid != horizon_client::blocks::Fluid::None }; if aim[1] > p[1] + 0.5 && horizontal(p, aim) < 1.6 && on_ground { diff --git a/crates/horizon-client/src/game/allays.rs b/crates/horizon-client/src/game/allays.rs index a2a5842b5..52dfa7e1c 100644 --- a/crates/horizon-client/src/game/allays.rs +++ b/crates/horizon-client/src/game/allays.rs @@ -29,7 +29,11 @@ impl Game<'_> { continue; }; let carried = self.mobs[i].extra.ints[1]; - let max = self.res.items.get(&held).map_or(64, |i| i.max_stack as i32); + let max = self + .res + .items() + .get(&held) + .map_or(64, |i| i.max_stack as i32); // GoToWantedItem / wantsToPickUp: the same item within 32. let wanted = if griefing && carried < max && self.mobs[i].extra.ints[3] <= 0 { self.dropped diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 4ea8df359..58cd27494 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -111,7 +111,12 @@ impl Game<'_> { let Some(item) = item else { continue; }; - let Some(asset) = self.res.items.get(item).and_then(|i| i.equip_asset.clone()) else { + let Some(asset) = self + .res + .items() + .get(item) + .and_then(|i| i.equip_asset.clone()) + else { continue; }; let kind = if layer == "leggings" { @@ -124,7 +129,7 @@ impl Game<'_> { continue; }; let (Some(r), Some(part)) = ( - self.atlas.sprites.get(texture.as_str()), + self.gui.atlas.sprites.get(texture.as_str()), assets.player.get(layer), ) else { continue; @@ -144,7 +149,7 @@ impl Game<'_> { // BlockPlaceContext: a replaceable clicked block is replaced. let clicked = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); let pos = if clicked.replaceable { hit.pos @@ -230,7 +235,7 @@ impl Game<'_> { fn equipment_slot(&self, stack: &ItemStack) -> usize { match self .res - .items + .items() .get(&stack.item) .and_then(|i| i.equip_slot.as_deref()) { @@ -377,9 +382,14 @@ impl Game<'_> { subject: None, }; let mut dead = Vec::new(); + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); for (i, a) in self.armor_stands.iter_mut().enumerate() { + if !ticking(a.position.x.floor() as i32, a.position.z.floor() as i32) { + continue; + } a.tick(&mut scene); - if !a.environment_tick(&self.world, &self.res.facts, self.pack.assets.registry) { + if !a.environment_tick(&self.world, self.res.facts(), self.pack.assets.registry) { dead.push(i); } } @@ -403,7 +413,7 @@ impl Game<'_> { out: &mut Vec, ) { let assets = &self.armor_stand_assets; - let sprites = &self.atlas.sprites; + let sprites = &self.gui.atlas.sprites; let uv_of = |name: &str| sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let Some(wood) = uv_of("entity/armorstand/armorstand") else { return; @@ -516,7 +526,7 @@ impl Game<'_> { }; let Some(asset) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.equip_asset.clone()) else { @@ -568,7 +578,7 @@ impl Game<'_> { /// `Equippable.swapWithEquipmentSlot`: right-clicking armor swaps it into /// its slot (the worn piece comes back to the hand). pub(super) fn equip_from_hand(&mut self, stack: &ItemStack) -> bool { - let Some(info) = self.res.items.get(&stack.item) else { + let Some(info) = self.res.items().get(&stack.item) else { return false; }; let index = match info.equip_slot.as_deref() { @@ -699,7 +709,7 @@ impl Game<'_> { &serde_json::Value::Null, false, pose, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), &mut sink, ); @@ -709,7 +719,7 @@ impl Game<'_> { if let Some(stack) = &a.equipment[5] && self .res - .items + .items() .get(&stack.item) .is_none_or(|i| i.equip_asset.is_none()) && let Some(head) = part_matrix(model, base, poses, "head", 0.0) diff --git a/crates/horizon-client/src/game/backdrop.rs b/crates/horizon-client/src/game/backdrop.rs index 149cddefa..3a5ec81d6 100644 --- a/crates/horizon-client/src/game/backdrop.rs +++ b/crates/horizon-client/src/game/backdrop.rs @@ -71,8 +71,10 @@ impl Game<'_> { } /// Called every frame while the title is up. pub(super) fn update_backdrop(&mut self) -> Result<()> { - let wanted = self.title.is_some() + let wanted = self.pending_entry.is_none() + && self.title.is_some() && horizon_client::ui_theme::horizon() + && self.world_renderer_ready && self.renderer.is_some() && self.options.frames.is_none(); if !wanted { @@ -127,6 +129,10 @@ impl Game<'_> { .is_some_and(|r| r.section_count() > 40) { self.backdrop.ready = Some(Instant::now()); + log::info!( + "Horizon: title backdrop ready; world rest ready: {}", + self.res.rest.get().is_some() + ); } Ok(()) } @@ -139,10 +145,14 @@ impl Game<'_> { } } fn surface_y(&self, x: i32, z: i32) -> Option { - let air = self.res.facts.air; + let air = self.res.facts().air; (-60..320).rev().find(|&y| self.world.block(x, y, z) != air) } fn start_backdrop(&mut self) -> Result<()> { + log::info!( + "Horizon: starting title backdrop after {} ms", + self.started.elapsed().as_millis() + ); let seed = seed(); let root = std::env::current_dir()? .join("saves") @@ -155,7 +165,7 @@ impl Game<'_> { VanillaTerrain::new( &self.options.resources.join("worldgen"), pack.assets.registry, - &res.biomes, + res.biomes(), seed, ) .map_err(|e| format!("title backdrop: {e}"))?, @@ -165,10 +175,10 @@ impl Game<'_> { inner: inner.clone(), save: save.clone(), registry: pack.assets.clone(), - biomes: res.biomes.clone(), + biomes: res.biomes().clone(), }), pack.context.clone(), - res.threads.min(6), + res.threads().min(6), ); streaming.radius = self.settings.render_distance.clamp(4, 10); streaming.biome_blend = self.settings.biome_blend; @@ -179,7 +189,7 @@ impl Game<'_> { streaming.paused = true; self.streaming = streaming; self.save = save; - let mut world = World::new(self.res.facts.air, seed); + let mut world = World::new(self.res.facts().air, seed); world.day_time = DAY_TIME; world.game_time = 6000; // Light snow: the weather renders as snow in frozen biomes. @@ -237,7 +247,7 @@ impl Game<'_> { } fn stop_backdrop(&mut self) { self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); if let Some(r) = self.renderer.as_mut() { r.clear_sections(); } diff --git a/crates/horizon-client/src/game/banners.rs b/crates/horizon-client/src/game/banners.rs index 6875fcb7f..05beda3f8 100644 --- a/crates/horizon-client/src/game/banners.rs +++ b/crates/horizon-client/src/game/banners.rs @@ -14,7 +14,7 @@ impl Game<'_> { else { return Vec::new(); }; - layer_textures(&self.res.stations.banners, &b.layers) + layer_textures(&self.res.stations().banners, &b.layers) } } diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 73cdd15a4..79cf14541 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -99,11 +99,8 @@ impl Game<'_> { } /// `getHeight(WORLD_SURFACE)`: above the highest non-air block. pub(super) fn world_surface(&self, x: i32, z: i32) -> i32 { - let (min, max) = (super::MIN_Y, super::MIN_Y + super::HEIGHT); - (min..max) - .rev() - .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) - .map_or(min, |y| y + 1) + self.world + .world_surface(x, z, |id| self.res.facts().is_air(id)) } /// `BeaconBlockEntity.tick` of the beacon at `key`. pub(super) fn tick_beacon_at(&mut self, key: (i32, i32, i32)) { @@ -125,7 +122,7 @@ impl Game<'_> { let mut i = 0; while i < 10 && check <= surface { let state = self.world.block(x, check, z); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); if let Some(color) = self.beam_color(&f.name) { if b.checking.len() <= 1 { b.checking.push((color, 1)); @@ -186,7 +183,7 @@ impl Game<'_> { fn beacon_base(&self, x: i32, y: i32, z: i32) -> i32 { let base = self .res - .items + .items() .block_tags .get("minecraft:beacon_base_blocks"); let mut levels = 0; @@ -197,7 +194,7 @@ impl Game<'_> { } let ok = (x - step..=x + step).all(|lx| { (z - step..=z + step).all(|lz| { - let name = &self.res.facts.get(self.world.block(lx, ly, lz)).name; + let name = &self.res.facts().get(self.world.block(lx, ly, lz)).name; base.is_some_and(|t| t.contains(&**name)) }) }); @@ -378,7 +375,7 @@ impl Game<'_> { let levels = self.beacon_levels(); let sel = self.station.as_ref().map_or([None; 2], |s| s.beacon); let paid = self.station.as_ref().is_some_and(|s| s.inputs[0].is_some()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -399,7 +396,7 @@ impl Game<'_> { ("block.minecraft.beacon.secondary", "Secondary Power", 169.0), ] { let text = self.translate(key, fallback); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = HudBatch::text_width(atlas, &text); batch.text( atlas, @@ -414,7 +411,7 @@ impl Game<'_> { let x = [20.0, 41.0, 63.0, 86.0, 108.0][i]; self.draw_item(batch, &ItemStack::new(item, 1), bx + x, by + 109.0); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut tooltip = None; let button = |batch: &mut HudBatch, x: f32, y: f32, active: bool, selected: bool, icon: &str| { @@ -496,7 +493,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -517,7 +514,13 @@ impl Game<'_> { } /// `BeaconRenderer`: each section's rotating solid beam and its glow. pub(super) fn beacon_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let Some(s) = self.atlas.sprites.get("entity/beacon/beacon_beam").copied() else { + let Some(s) = self + .gui + .atlas + .sprites + .get("entity/beacon/beacon_beam") + .copied() + else { return; }; let time = (self.world.game_time.rem_euclid(40)) as f32 + alpha as f32; diff --git a/crates/horizon-client/src/game/beehives.rs b/crates/horizon-client/src/game/beehives.rs index 52fed3f3b..b7f7efb1a 100644 --- a/crates/horizon-client/src/game/beehives.rs +++ b/crates/horizon-client/src/game/beehives.rs @@ -41,7 +41,7 @@ impl HiveHost for GameHive<'_, '_> { if !self .game .res - .mob_data + .mob_data() .entity_has("minecraft:beehive_inhabitors", &kind) { return None; @@ -72,10 +72,10 @@ impl Game<'_> { /// The hive's honey level and front, from its block state. pub(super) fn hive_state(&self, at: [i32; 3]) -> Option<(Option, [i32; 2])> { let state = self.world.block(at[0], at[1], at[2]); - let name = &self.res.facts.get(state).name; + let name = &self.res.facts().get(state).name; if !self .res - .items + .items() .block_tags .get("minecraft:beehives") .is_some_and(|t| t.contains(&**name)) @@ -108,7 +108,7 @@ impl Game<'_> { .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" + &*self.res.facts().get(state).name == "minecraft:fire" }); let mut host = GameHive { game: self }; if fire && !hive.bees.is_empty() { diff --git a/crates/horizon-client/src/game/block_entity_anims.rs b/crates/horizon-client/src/game/block_entity_anims.rs index 102b46063..619fcd009 100644 --- a/crates/horizon-client/src/game/block_entity_anims.rs +++ b/crates/horizon-client/src/game/block_entity_anims.rs @@ -193,7 +193,7 @@ impl Game<'_> { }; let raiders = self .res - .stations + .stations() .enchantments .entity_tags .get("minecraft:raiders") @@ -201,7 +201,7 @@ impl Game<'_> { .unwrap_or_default(); let frames = self .res - .items + .items() .block_tags .get("minecraft:conduit_effect_block") .cloned() @@ -285,7 +285,7 @@ impl Game<'_> { } Ticker::Conduit => { let world = &self.world; - let facts = &self.res.facts; + let facts = self.res.facts(); let registry = self.pack.assets.registry; let is_water = |p: [i32; 3]| { facts.get(world.block(p[0], p[1], p[2])).fluid @@ -372,7 +372,7 @@ impl Game<'_> { /// pot's saved `sherds` (back, left, right, front). pub(super) fn block_anim(&self, pos: [i32; 3], partial: f32) -> BlockAnim { let state = self.world.block(pos[0], pos[1], pos[2]); - let sherds = if &*self.res.facts.get(state).name == "minecraft:decorated_pot" { + let sherds = if &*self.res.facts().get(state).name == "minecraft:decorated_pot" { let sherds = self.saved_tag(pos).and_then(|t| t.get("sherds")); ["back", "left", "right", "front"].map(|side| match sherds.and_then(|s| s.get(side)) { // An item id, or the item stack the processed templates hold. diff --git a/crates/horizon-client/src/game/block_entity_ticks.rs b/crates/horizon-client/src/game/block_entity_ticks.rs index f596f2d8b..bb1cadd15 100644 --- a/crates/horizon-client/src/game/block_entity_ticks.rs +++ b/crates/horizon-client/src/game/block_entity_ticks.rs @@ -76,7 +76,7 @@ impl Game<'_> { (0..registry.len()) .map(|i| { let state = BlockStateId(i as u32); - let name: &str = &self.res.facts.get(state).name; + let name: &str = &self.res.facts().get(state).name; match name { "minecraft:hopper" | "minecraft:crafter" @@ -101,27 +101,12 @@ impl Game<'_> { }) .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. + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk + /// (`LevelChunk.isTicking`, block coordinates), from every player's + /// tickets (`update_chunk_tickets`). 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) - } + let levels = self.tickets.levels(); + move |x, z| levels.block_ticking_at(x, z) } /// `AbstractFurnaceBlockEntity.serverTick` of the furnace at `pos`, and /// its block's `lit` following it. @@ -129,7 +114,7 @@ impl Game<'_> { 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 { + 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); diff --git a/crates/horizon-client/src/game/block_items.rs b/crates/horizon-client/src/game/block_items.rs index b8012cce1..199c39a78 100644 --- a/crates/horizon-client/src/game/block_items.rs +++ b/crates/horizon-client/src/game/block_items.rs @@ -22,7 +22,7 @@ impl Game<'_> { let entity = self.world.block_entities.get(&key)?; let block = &self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name; let mut tag = save::encode_block_entity(key, entity, block); @@ -37,7 +37,7 @@ impl Game<'_> { pub(super) fn picked_stack(&self, pos: [i32; 3], include_data: bool) -> Option { let key = (pos[0], pos[1], pos[2]); let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if &*facts.item == "minecraft:air" { return None; } diff --git a/crates/horizon-client/src/game/blockctl.rs b/crates/horizon-client/src/game/blockctl.rs index 993e0789e..719ce8dd2 100644 --- a/crates/horizon-client/src/game/blockctl.rs +++ b/crates/horizon-client/src/game/blockctl.rs @@ -47,7 +47,7 @@ impl Game<'_> { format!("{}[{}]", s.name, props.join(",")) } fn put_block(&mut self, pos: [i32; 3], state: BlockStateId) -> Result<()> { - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); self.world.block_entities.remove(&(pos[0], pos[1], pos[2])); self.level_set(pos, state)?; if let Some(entity) = BlockEntity::for_block(&name) { diff --git a/crates/horizon-client/src/game/boats.rs b/crates/horizon-client/src/game/boats.rs index 8f2cad5f5..f9740598e 100644 --- a/crates/horizon-client/src/game/boats.rs +++ b/crates/horizon-client/src/game/boats.rs @@ -180,11 +180,11 @@ impl BoatModels { } impl Game<'_> { fn fluid_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if f.fluid != Fluid::Water { return None; } - let above = self.res.facts.get(self.world.block(x, y + 1, z)); + let above = self.res.facts().get(self.world.block(x, y + 1, z)); // FluidState.getHeight: 1 under the same fluid, else amount / 9. let height = if above.fluid == Fluid::Water { 1.0 @@ -277,7 +277,7 @@ impl Game<'_> { && f64::from(x + 1) > lo.x && f64::from(z) < hi.z && f64::from(z + 1) > lo.z; - let f = self.res.facts.get(self.world.block(x, y0, z)); + let f = self.res.facts().get(self.world.block(x, y0, z)); if inside && (f.full_collision || f.legacy_solid) && !f.has_class("LilyPadBlock") { friction += f.friction; count += 1; @@ -443,8 +443,13 @@ impl Game<'_> { } /// Every boat but the ridden one (which ticks with its rider). pub(super) fn tick_boats(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); for i in 0..self.boats.len() { - if Some(self.boats[i].id) == self.riding { + let p = self.boats[i].position; + if Some(self.boats[i].id) == self.riding + || !ticking(p.x.floor() as i32, p.z.floor() as i32) + { continue; } let b = self.boats[i].clone(); @@ -495,8 +500,8 @@ impl Game<'_> { ); let top = b.bounds().max_position().y; let (bx, by, bz) = (x.floor() as i32, top.floor() as i32, z.floor() as i32); - let below = self.res.facts.get(self.world.block(bx, by - 1, bz)); - let here = self.res.facts.get(self.world.block(bx, by, bz)); + let below = self.res.facts().get(self.world.block(bx, by - 1, bz)); + let here = self.res.facts().get(self.world.block(bx, by, bz)); let target = if below.fluid != Fluid::Water && !here.full_collision && (below.full_collision || below.legacy_solid) @@ -723,6 +728,7 @@ impl Game<'_> { }; let folder = if b.chest { "chest_boat" } else { "boat" }; let Some(uv) = self + .gui .atlas .sprites .get(&format!("entity/{folder}/{}", b.wood)) diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 5603e8369..8745c6f35 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -45,7 +45,7 @@ pub(super) enum BookScreen { } impl Game<'_> { fn book_lines(&self, page: &str) -> Vec { - self.atlas.font.split(&Text::literal(page), 114.0) + self.gui.atlas.font.split(&Text::literal(page), 114.0) } /// `WritableBookItem.use` / `WrittenBookItem.use`. pub(super) fn use_book(&mut self, stack: &ItemStack) -> bool { @@ -242,7 +242,7 @@ impl Game<'_> { /// the page (`MultilineTextField.insertText`: line breaks kept, cut to /// the 1024 characters left, rejected when it overflows the 14 lines). fn book_shortcut(&mut self, shortcut: horizon_client::clipboard::EditShortcut) { - let font = &self.atlas.font; + let font = &self.gui.atlas.font; match self.book.as_mut() { Some(BookScreen::Edit { signing: true, @@ -397,7 +397,7 @@ impl Game<'_> { let key = (pos[0], pos[1], pos[2]); if &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name != "minecraft:lectern" @@ -549,7 +549,7 @@ impl Game<'_> { } pub(super) fn draw_book(&self, batch: &mut HudBatch) { let Some(book) = &self.book else { return }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); let (mx, my) = self.cursor; let hover = diff --git a/crates/horizon-client/src/game/breezes.rs b/crates/horizon-client/src/game/breezes.rs index 52e3b36a9..466469110 100644 --- a/crates/horizon-client/src/game/breezes.rs +++ b/crates/horizon-client/src/game/breezes.rs @@ -40,7 +40,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let mut state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { state = self.world.block(x, (m.position.y - 0.2).floor() as i32, z); } let Some((sprite, tint)) = self.particle_sprite(state) else { diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index 86d5d5395..4a5738f6e 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -89,17 +89,17 @@ impl Game<'_> { if is_locked { locked = true; if scaling || locking { - batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0); } } if scaling && scale >= 4 { locked = true; - batch.sprite(&self.atlas, error, ox + 35.0, oy + 31.0); + batch.sprite(&self.gui.atlas, error, ox + 35.0, oy + 31.0); } } let sprite = |batch: &mut HudBatch, game: &Self, name: &str, x: f32, y: f32| { batch.sprite( - &game.atlas, + &game.gui.atlas, &format!("gui/sprites/container/cartography_table/{name}"), ox + x, oy + y, diff --git a/crates/horizon-client/src/game/chat.rs b/crates/horizon-client/src/game/chat.rs index cb8a3a0b5..20aeeb7fd 100644 --- a/crates/horizon-client/src/game/chat.rs +++ b/crates/horizon-client/src/game/chat.rs @@ -219,12 +219,18 @@ impl Game<'_> { .map(|a| format!("minecraft:{a}")) .collect(); let reg = &mut self.ui.registries; - let mut items: Vec = self.res.items.order.iter().map(|s| s.to_string()).collect(); + let mut items: Vec = self + .res + .items() + .order + .iter() + .map(|s| s.to_string()) + .collect(); items.sort(); reg.items = items; reg.item_tags = self .res - .items + .items() .item_tags .keys() .map(|k| horizon_client::command::args::normalize(k)) @@ -232,7 +238,7 @@ impl Game<'_> { reg.item_tags.sort(); reg.block_tags = self .res - .items + .items() .block_tags .keys() .map(|k| horizon_client::command::args::normalize(k)) @@ -259,7 +265,7 @@ impl Game<'_> { .collect(); let mut summonable: Vec = self .res - .mob_types + .mob_types() .keys() .map(|k| horizon_client::command::args::normalize(k)) .collect(); @@ -405,7 +411,7 @@ impl Game<'_> { .as_ref() .map_or([1280, 720], |r| [r.config.width, r.config.height]); let b = HudBatch::new(size); - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -450,7 +456,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; let heard = self.mods.mods.is_running().then(|| text.plain()); self.ui.chat.add( - &self.atlas, + &self.gui.atlas, text, Some(SYSTEM_INDICATOR), self.ticks, @@ -463,7 +469,7 @@ impl Game<'_> { /// Keys while the chat screen is open. pub(super) fn chat_key(&mut self, event: &KeyEvent) { if let Some(shortcut) = self.edit_shortcut(event) { - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -509,7 +515,7 @@ impl Game<'_> { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -541,7 +547,7 @@ impl Game<'_> { range: (usize, usize), list: Vec<(String, Option)>, ) { - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -552,7 +558,7 @@ impl Game<'_> { } /// 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 m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -580,7 +586,7 @@ impl Game<'_> { let heard = self.mods.mods.is_running().then(|| line.plain()); self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); if let Some(line) = heard { self.mods_chat(&line); } @@ -608,7 +614,7 @@ impl Game<'_> { let height = self.renderer.as_ref().map_or(720.0, |r| { HudBatch::new([r.config.width, r.config.height]).height }); - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -621,7 +627,7 @@ impl Game<'_> { return; } match self.ui.chat.click_at( - &self.atlas.font, + &self.gui.atlas.font, height as i32, cursor.0 as f64, cursor.1 as f64, @@ -647,13 +653,15 @@ impl Game<'_> { if self.ui.hide_gui && !focused { return; } - self.ui.chat.draw(batch, &self.atlas, self.ticks, focused); + self.ui + .chat + .draw(batch, &self.gui.atlas, self.ticks, focused); } pub(super) fn draw_chat_screen(&mut self, batch: &mut HudBatch) { let Some(mut screen) = self.ui.chat_screen.take() else { return; }; - let m = Measure(&self.atlas.font); + let m = Measure(&self.gui.atlas.font); let c = Commands { dispatcher: chat_tree(&self.remote, &self.mods), registries: &self.ui.registries, @@ -671,7 +679,7 @@ impl Game<'_> { .chat_opened .map_or(0, |t| t.elapsed().as_millis() as u64); let draws = screen.draw(&m, mouse, blink, background); - horizon_client::screen_draw::paint(batch, &self.atlas, &draws); + horizon_client::screen_draw::paint(batch, &self.gui.atlas, &draws); self.ui.chat_screen = Some(screen); } /// Advance the overworld clock (ServerClockManager.tick) when @@ -689,6 +697,16 @@ impl Game<'_> { c.partial -= whole; self.world.day_time += whole as i64; } + /// `ServerClockInstance.packNetworkState`: the rate players' clients + /// advance the overworld clock at, 0 while it is paused (`/time pause`) + /// or `advance_time` is off. + pub(super) fn network_clock_rate(&self) -> f32 { + if self.ui.rules.bool("advance_time") && !self.ui.clock.paused { + self.ui.clock.rate + } else { + 0.0 + } + } /// The engine-side rule values (block behaviour and health). pub(super) fn level_rules(&self) -> horizon_world::level::GameRules { let r = &self.ui.rules; @@ -863,11 +881,11 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, message, None, self.ticks, focused); + .add(&self.gui.atlas, message, None, self.ticks, focused); } #[allow(dead_code)] fn chat_debug_fill(&self, batch: &mut HudBatch) { - batch.fill(&self.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); + batch.fill(&self.gui.atlas, 0.0, 0.0, 1.0, 1.0, rgba(0, 0, 0, 0)); } } /// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time diff --git a/crates/horizon-client/src/game/combat.rs b/crates/horizon-client/src/game/combat.rs index abe67c6c6..da3851d9a 100644 --- a/crates/horizon-client/src/game/combat.rs +++ b/crates/horizon-client/src/game/combat.rs @@ -114,7 +114,7 @@ impl Game<'_> { let location = if let Some(c) = p.last_climbable { let name = self .res - .facts + .facts() .get(self.world.block(c.x, c.y, c.z)) .name .clone(); @@ -127,7 +127,7 @@ impl Game<'_> { _ => "other_climbable", }) } else { - let f = self.res.facts.get(self.world.block( + let f = self.res.facts().get(self.world.block( p.position.x.floor() as i32, (p.position.y + 0.1).floor() as i32, p.position.z.floor() as i32, diff --git a/crates/horizon-client/src/game/command_blocks.rs b/crates/horizon-client/src/game/command_blocks.rs index 717134515..76fc6d48c 100644 --- a/crates/horizon-client/src/game/command_blocks.rs +++ b/crates/horizon-client/src/game/command_blocks.rs @@ -356,7 +356,7 @@ impl Game<'_> { eyes: false, silent: false, store: None, - elsewhere: false, + dimension: self.dim, level: None, block: Some(pos), }; @@ -459,7 +459,7 @@ impl Game<'_> { self.close_command_block(); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); let mid = (w / 2.0).floor(); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); diff --git a/crates/horizon-client/src/game/command_harness.rs b/crates/horizon-client/src/game/command_harness.rs index ed3f8b336..096ba1c74 100644 --- a/crates/horizon-client/src/game/command_harness.rs +++ b/crates/horizon-client/src/game/command_harness.rs @@ -4,7 +4,8 @@ //! command as the player (Commands.performPrefixedCommand) and records every //! system message it produced, as styled spans, with the results reported to //! the player's `CommandResultCallback`; `tick` advances the game; `settle` -//! waits until the terrain around the player is loaded. +//! waits until the terrain and entities around the player are loaded; +//! `portal` sends the player through the nether portal it stands in. use super::Game; use horizon_client::{Result, text::Text}; use serde_json::{Value, json}; @@ -40,6 +41,19 @@ pub(super) fn spans(text: &Text) -> Value { } impl Game<'_> { + /// The player's portal process finished in the nether portal it stands + /// in (the oracle's player is not ticked, so neither is the wait). + fn harness_portal(&mut self) -> Result<()> { + let Some(p) = &self.player else { + return Err("command harness: portal without a player".into()); + }; + let entry = horizon_core::position::BlockPos::containing(p.position); + let block = self.world.block(entry.x, entry.y, entry.z); + if &*self.res.facts().get(block).name != "minecraft:nether_portal" { + return Err("command harness: the player is not in a nether portal".into()); + } + self.player_through_nether_portal(entry) + } /// Load terrain until the player stands in lit chunks. fn harness_settle(&mut self, deadline: Instant) -> Result<()> { loop { @@ -51,6 +65,10 @@ impl Game<'_> { (p.position.z.floor() as i32) >> 4, ); if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) { + // The oracle's settle also waits for the entities saved + // in those chunks (areEntitiesActuallyLoadedAndTicking): + // after a dimension change they come back from the save. + self.spawn_loaded_entities(); return Ok(()); } } @@ -130,6 +148,7 @@ impl Game<'_> { } } "settle" => self.harness_settle(deadline)?, + "portal" => self.harness_portal()?, other => return Err(format!("command harness: unknown op {other}").into()), } } diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 575f5c93e..b970414a6 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -9,6 +9,7 @@ pub(super) mod extra; mod items; mod misc; mod place; +mod players; mod raid; mod terrain_cmds; mod text_commands; @@ -33,7 +34,11 @@ pub(super) type R = Result; /// An entity a selector found. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub(super) enum Target { + /// The player in place: the host's, or the guest whose turn it is. Player, + /// Another player of a hosted world or server: a guest by connection + /// (game/commands/players.rs). + Guest(u32), Mob(u32), Item(u32), Orb(usize), @@ -232,9 +237,16 @@ impl Game<'_> { } match &self.player { Some(p) => [p.position.x, p.position.y, p.position.z], - None => self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]), + None => self.server_position(), } } + /// MinecraftServer.createCommandSourceStack's position: the corner of + /// the respawn block (`Vec3.atLowerCornerOf`). + pub(super) fn server_position(&self) -> [f64; 3] { + self.spawn.map_or([0.0, 64.0, 0.0], |s| { + [s.x.floor(), s.y.floor(), s.z.floor()] + }) + } fn source_rotation(&self) -> [f32; 2] { self.command_source .map_or([self.yaw, self.pitch], |s| s.rot) @@ -263,8 +275,8 @@ impl Game<'_> { .ok_or_else(|| err("argument.pos.missing.int", &[]))?; // BlockPos.containing(getPosition) let p = self.resolve_coords(&c).map(|v| v.floor() as i32); - let elsewhere = self.command_source.is_some_and(|s| s.elsewhere); - if elsewhere || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { + let dimension = self.command_source.map_or(self.dim, |s| s.dimension); + if dimension != self.dim || !self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) { return Err(err("argument.pos.unloaded", &[])); } if p[1] < horizon_client::chunk::MIN_Y @@ -288,6 +300,7 @@ impl Game<'_> { .player .as_ref() .map(|p| [p.position.x, p.position.y, p.position.z]), + Target::Guest(conn) => self.command_guest(conn).map(|g| g.position), Target::Mob(id) => self .mobs .iter() @@ -347,7 +360,7 @@ impl Game<'_> { } pub(super) fn target_type(&self, t: Target) -> String { match t { - Target::Player => "minecraft:player".into(), + Target::Player | Target::Guest(_) => "minecraft:player".into(), Target::Mob(id) => self .mobs .iter() @@ -394,12 +407,19 @@ impl Game<'_> { match t { Target::Player => { let name = self.acting_player_name(); + if let Some(uuid) = self.lan_acting_uuid { + return self.player_text(name, uuid); + } match self.score.board.players_team(name) { // PlayerTeam.formatNameForTeam. Some(team) => team.formatted_name(Text::literal(name)), None => Text::literal(name), } } + Target::Guest(conn) => match self.command_guest(conn) { + Some(g) => self.player_text(&g.name, g.uuid), + None => Text::empty(), + }, Target::Item(id) => { let item = self .dropped @@ -446,11 +466,10 @@ impl Game<'_> { /// EntitySelector.findEntities. pub(super) fn select(&mut self, s: &Selector) -> Vec { if let Some(name) = &s.player_name { - return if name.eq_ignore_ascii_case(PLAYER_NAME) && self.player.is_some() { - vec![Target::Player] - } else { - Vec::new() - }; + return self.player_named(name).into_iter().collect(); + } + if let Some(uuid) = s.uuid { + return self.target_by_uuid(uuid).into_iter().collect(); } let origin = { let p = self.source_position(); @@ -464,10 +483,15 @@ impl Game<'_> { match (s.kind, self.command_source) { // @s: the executing entity (none for a server source). ('s', Some(source)) => candidates.extend(source.entity), - _ if self.player.is_some() => candidates.push(Target::Player), + ('s', None) => candidates.extend(self.source_entity()), + // A guest in place is among the players, in join order. + _ if self.player.is_some() && self.lan_acting.is_none() => { + candidates.push(Target::Player); + } _ => {} } if s.kind != 's' { + candidates.extend(self.player_candidates(s)); candidates.extend( self.mobs .iter() @@ -511,7 +535,7 @@ impl Game<'_> { } } if !s.include_entities - && t != Target::Player + && !t.is_player() && s.types.iter().all(|(w, n)| *n || w != &ty) && s.kind != 'e' && s.kind != 'n' @@ -527,16 +551,20 @@ impl Game<'_> { if !passing.contains(&t) { return None; } + let player = match t { + Target::Player => Some((level, if creative { "creative" } else { "survival" })), + Target::Guest(conn) => self.guest_level_and_mode(conn), + _ => None, + }; if let Some((lo, hi)) = s.level - && (t != Target::Player - || lo.is_some_and(|l| level < l) - || hi.is_some_and(|h| level > h)) + && player.is_none_or(|(level, _)| { + lo.is_some_and(|l| level < l) || hi.is_some_and(|h| level > h) + }) { return None; } for (mode, neg) in &s.gamemodes { - let current = if creative { "creative" } else { "survival" }; - if t != Target::Player || (current == mode) == *neg { + if player.is_none_or(|(_, current)| (current == mode) == *neg) { return None; } } @@ -595,12 +623,12 @@ impl Game<'_> { /// EntityArgument.getEntities / getPlayers / getEntity / getPlayer. pub(super) fn entities(&mut self, ctx: &Context, name: &str, players: bool) -> R> { let Some(Arg::Entity(s)) = ctx.get(name).cloned() else { - return Ok(vec![Target::Player]); + return Ok(vec![self.implied_player()]); }; let found: Vec = self .select(&s) .into_iter() - .filter(|t| !players || *t == Target::Player) + .filter(|t| !players || t.is_player()) .collect(); if found.is_empty() { return Err(err( @@ -806,63 +834,63 @@ impl Game<'_> { let targets = if ctx.get("target").is_some() { self.entities(ctx, "target", true)? } else { - vec![Target::Player] + vec![self.implied_player()] }; let mut count = 0; for t in targets { - if t != Target::Player || !self.set_game_mode(mode) { + let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); + // GameModeCommand.logGamemodeChange: the source's own entity. + let own = self.source_entity() == Some(t); + let told = !own && self.ui.rules.bool("send_command_feedback"); + let changed = self.for_player(t, |g| { + if !g.set_game_mode(mode) { + return false; + } + if told { + g.system_message(Text::translate( + "gameMode.changed", + std::slice::from_ref(&mode_name), + )); + } + true + }); + if changed != Some(true) { continue; } count += 1; - let mode_name = Text::translate(&format!("gameMode.{}", mode.name()), &[]); - // GameModeCommand.logGamemodeChange: the source's own entity. - let own = match self.command_source { - None => true, - Some(s) => s.entity == Some(t), - }; if own { self.feedback(Text::translate( "commands.gamemode.success.self", &[mode_name], )); } else { - if self.ui.rules.bool("send_command_feedback") { - self.system_message(Text::translate( - "gameMode.changed", - std::slice::from_ref(&mode_name), - )); - } self.feedback(Text::translate( "commands.gamemode.success.other", - &[Text::literal(self.acting_player_name()), mode_name], + &[self.target_name(t), mode_name], )); } } Ok(count) } - /// ItemStack.getDisplayName: "[Name]" in the rarity colour. + /// ItemStack.getDisplayName of one `item` with no components. pub(super) fn item_display_name(&self, item: &str) -> Text { - let rarity = self.item_rarity(item); - let color = match rarity.as_str() { - "uncommon" => text::YELLOW, - "rare" => text::AQUA, - "epic" => text::LIGHT_PURPLE, - _ => text::WHITE, - }; - Text::literal("[") - .append(Text::literal(self.pack.names.item(item))) - .append("]") - .with_color(color) + self.stack_display_name(&ItemStack { + item: item.into(), + count: 1, + damage: 0, + extra: None, + }) } /// `ItemStack.getDisplayName`: the hover name (custom name in italics, - /// a written book's title, a potion's effect name...) in brackets, in the - /// rarity colour unless the stack is empty. + /// a written book's title, a potion's effect name, else the item's + /// translated name) in brackets, in the rarity colour and showing the + /// stack on hover unless it is empty. pub(super) fn stack_display_name(&self, s: &ItemStack) -> Text { let item = &*s.item; let empty = item == "minecraft:air" || s.count == 0; let custom = s.custom_name(); let hover = if let Some(c) = custom { - Text::literal(c).italic() + Text::literal(c) } else if let Some(title) = s .data() .and_then(|d| d.written.as_ref()) @@ -883,9 +911,22 @@ impl Game<'_> { &[], ) } else { - Text::literal(self.pack.names.item(item)) + // Item.getDescriptionId: a block item's is the block's. + let (namespace, path) = item.split_once(':').unwrap_or(("minecraft", item)); + let key = format!("item.{namespace}.{path}"); + let key = if self.pack.names.get(&key).is_some() { + key + } else { + format!("block.{namespace}.{path}") + }; + Text::translate(&key, &[]) }; - let wrapped = Text::translate("chat.square_brackets", &[hover]); + // Component.empty().append(getHoverName()), italic for a custom name. + let mut name = Text::empty().append(hover); + if custom.is_some() { + name = name.italic(); + } + let wrapped = Text::translate("chat.square_brackets", &[name]); if empty { return wrapped; } @@ -903,7 +944,14 @@ impl Game<'_> { "epic" => text::LIGHT_PURPLE, _ => text::WHITE, }; - wrapped.with_color(color) + // HoverEvent.ShowItem: the count only when it is not one. + let mut shown = serde_json::json!({"action": "show_item", "id": item}); + if s.count != 1 { + shown["count"] = s.count.into(); + } + wrapped + .with_color(color) + .with_component_fields(vec![("hover_event".into(), shown)]) } pub(super) fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = @@ -941,7 +989,7 @@ impl Game<'_> { }; let count = Self::int(ctx, "count").unwrap_or(1); let targets = self.entities(ctx, "targets", true)?; - let max_stack = self.res.items.get(&id).map_or(64, |i| i.max_stack) as i32; + let max_stack = self.res.items().get(&id).map_or(64, |i| i.max_stack) as i32; if count > max_stack * 100 { return Err(CommandError::new(Text::translate( "commands.give.failed.toomanyitems", @@ -953,33 +1001,38 @@ impl Game<'_> { } // An air stack is empty: nothing is given (but the message still is). let empty = id == "minecraft:air"; - for _ in targets.iter().filter(|_| !empty) { - let mut remaining = count; - while remaining > 0 { - let size = remaining.min(max_stack); - remaining -= size; - let left = self.give(ItemStack { - item: id.as_str().into(), - count: size as u32, - damage, - extra: extra.clone(), - }); - if let Some(rest) = left { - // Inventory full: drop the rest at the player's feet without pickup delay. - let p = self.source_position(); - self.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); - } else { - let r = &mut self.world.random; - let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; - let p = self.source_position(); - self.audio - .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + for &t in targets.iter().filter(|_| !empty) { + self.for_player(t, |g| { + let mut remaining = count; + while remaining > 0 { + let size = remaining.min(max_stack); + remaining -= size; + let left = g.give(ItemStack { + item: id.as_str().into(), + count: size as u32, + damage, + extra: extra.clone(), + }); + // At the player who gets them. + let p = g + .target_position(Target::Player) + .unwrap_or(g.source_position()); + if let Some(rest) = left { + // Inventory full: drop the rest at the player's feet without pickup delay. + g.spawn_item(rest, [p[0], p[1] + 1.32, p[2]], [0.0, 0.0, 0.0], 0); + } else { + let r = &mut g.world.random; + let pitch = ((r.next_float() - r.next_float()) * 0.7 + 1.0) * 2.0; + g.audio + .play("minecraft:entity.item.pickup", Some(p), 0.2, pitch); + } } - } + }); } + // The prototype stack: one item. let name = self.stack_display_name(&ItemStack { item: id.as_str().into(), - count: count.max(1) as u32, + count: 1, damage, extra: extra.clone(), }); @@ -989,7 +1042,7 @@ impl Game<'_> { &[ Text::literal(count.to_string()), name, - Text::literal(self.acting_player_name()), + self.target_name(targets[0]), ], ) } else { @@ -1008,6 +1061,9 @@ impl Game<'_> { fn teleport_to(&mut self, t: Target, pos: [f64; 3], rotation: Option<[f32; 2]>) { let v = Vec3::new(pos[0], pos[1], pos[2]); match t { + Target::Guest(_) => { + self.for_player(t, |g| g.teleport_to(Target::Player, pos, rotation)); + } Target::Player => { if let Some(p) = self.player.as_mut() { p.position = v; @@ -1088,17 +1144,96 @@ impl Game<'_> { Target::Frame(_) | Target::Painting(_) => {} } } + /// Teleport the local player into the command source's dimension. Unlike + /// portal travel, `/tp` keeps the coordinates given by the command. + fn teleport_player_to_dimension( + &mut self, + dimension: Dim, + pos: [f64; 3], + rotation: Option<[f32; 2]>, + ) -> R<()> { + let Some(mut player) = self.player.take() else { + return Ok(()); + }; + let from = self.dim; + if self.switch_level(dimension, player.position).is_err() { + self.player = Some(player); + return Err(err("command.failed", &[])); + } + self.trigger_dimension(from, dimension); + let target = Vec3::new(pos[0], pos[1], pos[2]); + player.position = target; + player.velocity = Vec3::ZERO; + player.fall_distance = 0.0; + player.ground.on_ground = false; + if let Some([yaw, pitch]) = rotation { + let pitch = pitch.clamp(-90.0, 90.0); + self.yaw = yaw; + self.pitch = pitch; + player.yaw = yaw; + player.head_yaw = yaw; + player.pitch = pitch; + } + self.travelling = Some((player, target)); + self.portals.travel = None; + self.end_travel = false; + self.end_portal_travel = false; + Ok(()) + } + + /// A server's player teleported into another level than theirs + /// (ServerPlayer.teleport): queued to move after the command. False + /// when `t` is not a player in another level. + fn teleport_across( + &mut self, + t: Target, + level: super::Dim, + pos: [f64; 3], + rotation: Option<[f32; 2]>, + ) -> bool { + let (conn, at) = match t { + Target::Player => (self.lan_acting, self.dim), + Target::Guest(conn) => ( + Some(conn), + self.command_guest(conn) + .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), + ), + _ => (None, self.dim), + }; + let Some(conn) = conn.filter(|_| at != level && self.options.dedicated.is_some()) else { + return false; + }; + self.level_teleports + .push(super::server_travel::LevelTeleport { + conn, + dim: level, + at: pos, + rotation, + }); + true + } fn cmd_teleport(&mut self, id: &str, ctx: &Context) -> R { let targets = if id.starts_with("teleport.targets") { self.entities(ctx, "targets", false)? } else { - vec![Target::Player] + vec![self.implied_player()] }; if id.ends_with("destination") { let dest = self.entities(ctx, "destination", false)?[0]; let pos = self.target_position(dest).unwrap_or(self.source_position()); + // Into the destination's level. + let level = match dest { + Target::Guest(conn) => self + .command_guest(conn) + .map_or(self.dim, |g| super::Dim::from_id(&g.dimension)), + _ => self.dim, + }; + // TeleportCommand.teleportToEntity: the destination's rotation too. + let rotation = Some(self.target_rotation(dest)); for &t in &targets { - self.teleport_to(t, pos, None); + if !self.teleport_across(t, level, pos, rotation) { + self.teleport_to(t, pos, rotation); + } } let message = if targets.len() == 1 { Text::translate( @@ -1156,24 +1291,24 @@ 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()); + // A server's player in another level than the source's (`execute + // in`, the console's Overworld) moves there (ServerPlayer.teleport + // into another level), after the command. + let source_level = match self.command_source.and_then(|s| s.level) { + Some(level) => level, + None if self.source_entity().is_none() => super::Dim::Overworld, + None => self.dim, + }; 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, - }); + if self.teleport_across(t, source_level, pos, rotation) { continue; } - self.teleport_to(t, pos, rotation); + let dimension = self.command_source.map_or(self.dim, |s| s.dimension); + if t == Target::Player && dimension != self.dim { + self.teleport_player_to_dimension(dimension, pos, rotation)?; + } else { + self.teleport_to(t, pos, rotation); + } } let [x, y, z] = pos.map(|v| Text::literal(format_double(v))); let message = if targets.len() == 1 { @@ -1373,6 +1508,9 @@ impl Game<'_> { } fn kill_target(&mut self, t: Target) { match t { + Target::Guest(_) => { + self.for_player(t, |g| g.kill_target(Target::Player)); + } Target::Player => { if let Some(p) = self.player.as_mut() { let _ = p.set_health(0.0, false); @@ -1415,7 +1553,7 @@ impl Game<'_> { let targets = if ctx.get("targets").is_some() { self.entities(ctx, "targets", false)? } else { - vec![Target::Player] + vec![self.implied_player()] }; let names: Vec = targets.iter().map(|&t| self.target_name(t)).collect(); // Remove indexed entities from the back so earlier indices stay valid. @@ -1468,7 +1606,7 @@ impl Game<'_> { if self.ui.difficulty == 0 && self .res - .mob_types + .mob_types() .get(&format!("minecraft:{short}")) .is_some_and(|t| t.category == "monster") { @@ -1485,7 +1623,7 @@ impl Game<'_> { let name; if let Some(t) = self .res - .mob_types + .mob_types() .get(&format!("minecraft:{short}")) .cloned() { @@ -1561,10 +1699,10 @@ impl Game<'_> { let name_ok = if b.tag { let tag = b.id.trim_start_matches("minecraft:"); self.res - .items + .items() .block_tags .get(tag) - .or_else(|| self.res.items.block_tags.get(&b.id)) + .or_else(|| self.res.items().block_tags.get(&b.id)) .is_some_and(|set| { set.contains(&s.name) || set.contains(s.name.trim_start_matches("minecraft:")) }) @@ -1589,8 +1727,8 @@ impl Game<'_> { } // A different block replaces the block entity (Level.setBlock). let (old, new) = ( - self.res.facts.get(previous).name.clone(), - self.res.facts.get(state).name.clone(), + self.res.facts().get(previous).name.clone(), + self.res.facts().get(state).name.clone(), ); // The command clears the old block entity without its side effects // (UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS); the new block gets a fresh one. @@ -2184,10 +2322,10 @@ impl Game<'_> { let tag = predicate.id.trim_start_matches("minecraft:"); return self .res - .items + .items() .item_tags .get(tag) - .or_else(|| self.res.items.item_tags.get(&predicate.id)) + .or_else(|| self.res.items().item_tags.get(&predicate.id)) .is_some_and(|s| { s.contains(item) || s.contains(item.trim_start_matches("minecraft:")) }); @@ -2633,7 +2771,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); Ok(1) } /// MessageArgument: `@p`-style selectors in a message become names. diff --git a/crates/horizon-client/src/game/commands/compute.rs b/crates/horizon-client/src/game/commands/compute.rs index 24552011d..c7b2355e3 100644 --- a/crates/horizon-client/src/game/commands/compute.rs +++ b/crates/horizon-client/src/game/commands/compute.rs @@ -502,7 +502,7 @@ impl Game<'_> { Some(Value::String(b)) => match b.strip_prefix('#') { Some(tag) => self .res - .items + .items() .block_tags .get(tag.trim_start_matches("minecraft:")) .is_some_and(|set| { diff --git a/crates/horizon-client/src/game/commands/data.rs b/crates/horizon-client/src/game/commands/data.rs index 1d2321a1a..89e3d6397 100644 --- a/crates/horizon-client/src/game/commands/data.rs +++ b/crates/horizon-client/src/game/commands/data.rs @@ -35,6 +35,11 @@ impl Game<'_> { pub(in crate::game) fn entity_nbt(&mut self, t: Target) -> Option { let player_uuid = self.level.player_uuid; Some(match t { + Target::Guest(_) => { + return self + .for_player(t, |g| g.entity_nbt(Target::Player)) + .flatten(); + } Target::Player => { self.player.as_ref()?; self.sync_level(); @@ -142,7 +147,7 @@ impl Game<'_> { set_key(&mut tag, "id", Tag::String(k.as_str().into())); } let new = - entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, id).ok_or_else(stale)?; + entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), id).ok_or_else(stale)?; if let Some(slot) = self.mobs.iter_mut().find(|m| m.id == id) { // Runtime-only state (AI, animation) carries over. let old = std::mem::replace(slot, new); @@ -661,13 +666,20 @@ impl Game<'_> { /// Spawn an entity from its compound (`EntityType.loadEntityRecursive`); /// returns what was created. pub(super) fn spawn_entity_from_nbt(&mut self, tag: Tag) -> Option { - let before = self.next_entity; let key = { let p = entity_nbt::position(&tag)?; ((p.x.floor() as i32) >> 4, (p.z.floor() as i32) >> 4) }; + // Only this stack spawns now: the entities of chunks that finished + // loading wait for the level's entity tick, as in vanilla + // (PersistentEntitySectionManager.processPendingLoads), and must not + // take the ids counted as this stack's. + let mut waiting = std::mem::take(&mut self.world.loaded_entities); + let before = self.next_entity; self.world.loaded_entities.push((key, vec![tag])); self.spawn_loaded_entities(); + waiting.append(&mut self.world.loaded_entities); + self.world.loaded_entities = waiting; if self.next_entity == before { return None; } diff --git a/crates/horizon-client/src/game/commands/effects.rs b/crates/horizon-client/src/game/commands/effects.rs index 86726fed9..65d6592f7 100644 --- a/crates/horizon-client/src/game/commands/effects.rs +++ b/crates/horizon-client/src/game/commands/effects.rs @@ -59,7 +59,7 @@ impl Game<'_> { if ctx.get("targets").is_some() { self.entities(ctx, "targets", false) } else { - Ok(vec![Target::Player]) + Ok(vec![self.implied_player()]) } } /// `EffectCommands.giveEffect`. @@ -83,10 +83,11 @@ impl Game<'_> { let mut tracker = Tracker::default(); for t in self.living_targets(ctx)? { let changed = match t { - Target::Player => { + Target::Player | Target::Guest(_) => { let mut instance = EffectInstance::new(effect.id, duration, amplifier); instance.visible = particles; - self.add_player_effect(instance) + self.for_player(t, |g| g.add_player_effect(instance)) + .unwrap_or(false) } Target::Mob(id) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { @@ -131,18 +132,22 @@ impl Game<'_> { let mut tracker = Tracker::default(); for t in self.living_targets(ctx)? { let changed = match (t, effect) { - (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::Player | Target::Guest(_), None) => self + .for_player(t, |g| { + let any = !g.potions.effects.list.is_empty(); + g.potions.effects.clear(); + g.apply_effect_status(); + any + }) + .unwrap_or(false), + (Target::Player | Target::Guest(_), Some(e)) => self + .for_player(t, |g| { + let before = g.potions.effects.list.len(); + g.potions.effects.list.retain(|x| x.id != e.id); + g.apply_effect_status(); + g.potions.effects.list.len() != before + }) + .unwrap_or(false), (Target::Mob(id), e) => match self.mobs.iter_mut().find(|m| m.id == id) { Some(m) => { let before = m.extra.effects.len(); @@ -187,7 +192,7 @@ impl Game<'_> { return Ok(0); }; let level = Self::int(ctx, "level").unwrap_or(1); - let enchantments = &self.res.stations.enchantments; + let enchantments = &self.res.stations().enchantments; let Some(def) = enchantments.get(&id) else { return Err(err( "argument.resource.not_found", @@ -213,8 +218,8 @@ impl Game<'_> { } continue; }; - let e = &self.res.stations.enchantments; - let compatible = e.can_enchant(&self.res.items, &id, &stack.item) + let e = &self.res.stations().enchantments; + let compatible = e.can_enchant(self.res.items(), &id, &stack.item) && stack .crafting_enchantments() .iter() @@ -265,7 +270,7 @@ impl Game<'_> { } let (name, curse) = self .res - .stations + .stations() .enchantments .full_name(&id, level.max(0) as u32); let style = Style { diff --git a/crates/horizon-client/src/game/commands/execute.rs b/crates/horizon-client/src/game/commands/execute.rs index 01488db2c..221ebb238 100644 --- a/crates/horizon-client/src/game/commands/execute.rs +++ b/crates/horizon-client/src/game/commands/execute.rs @@ -1,7 +1,7 @@ //! `/execute` (ExecuteCommand): walk the parsed redirect chain, forking and //! filtering command sources, then run the final command once per source, //! reporting each result to the `store` callbacks of its source. -use super::{Arg, Context, Game, R, Target, data::DataRef, err}; +use super::{Arg, Context, Dim, Game, R, Target, data::DataRef, err}; use horizon_client::{ command::{CommandError, vanilla}, nbt_path::NbtPath, @@ -23,9 +23,9 @@ pub(in crate::game) struct Source { pub silent: bool, /// Index of the newest `store` in `ExecState::stores`. pub store: Option, - /// `execute in` another dimension than the one Horizon has loaded: none - /// of its chunks are loaded. - pub elsewhere: bool, + /// The level this command source uses. Horizon has only this dimension's + /// chunks loaded in the single-player client. + pub dimension: Dim, /// The dimension `execute in` named, if any: a server teleports its /// players there (`TeleportCommand` into the source's level). pub level: Option, @@ -73,13 +73,14 @@ impl Game<'_> { /// The source a command typed by the player starts from. pub(in crate::game) fn player_source(&self) -> Source { Source { - entity: Some(Target::Player), + // The server console has no entity (CommandSourceStack of the server). + entity: self.player.is_some().then_some(Target::Player), pos: self.source_position(), rot: self.source_rotation(), eyes: false, silent: false, store: None, - elsewhere: false, + dimension: self.dim, level: None, block: None, } @@ -88,12 +89,12 @@ impl Game<'_> { pub(in crate::game) fn server_source(&self) -> Source { Source { entity: None, - pos: self.spawn.map_or([0.0, 64.0, 0.0], |s| [s.x, s.y, s.z]), + pos: self.server_position(), rot: [0.0, 0.0], eyes: false, silent: true, store: None, - elsewhere: false, + dimension: self.dim, level: None, block: None, } @@ -101,6 +102,9 @@ impl Game<'_> { pub(super) fn target_rotation(&self, t: Target) -> [f32; 2] { match t { Target::Player => [self.yaw, self.pitch], + Target::Guest(conn) => self + .command_guest(conn) + .map_or([0.0; 2], |g| [g.yaw, g.pitch]), Target::Mob(id) => self .mobs .iter() @@ -135,6 +139,7 @@ impl Game<'_> { .player .as_ref() .map_or(1.62, |p| f64::from(p.dimensions.eye_height)), + Target::Guest(conn) => self.command_guest(conn).map_or(1.62, |g| g.eye_height()), Target::Mob(id) => self .mobs .iter() @@ -445,7 +450,7 @@ impl Game<'_> { Some(Source { pos: self.target_position(t)?, rot: self.target_rotation(t), - elsewhere: false, + dimension: self.dim, level: None, ..s }) @@ -537,8 +542,8 @@ impl Game<'_> { ..s }], "in" => { - // Horizon keeps one dimension loaded: in another one, no - // chunk is loaded (as in vanilla without a player there). + // CommandSourceStack.withLevel scales the source position; + // absolute coordinates passed to /tp are unaffected. let Some(Arg::Resource(dim)) = c.get("dimension") else { return Ok(vec![s]); }; @@ -548,8 +553,12 @@ impl Game<'_> { ) { return Err(err("argument.dimension.invalid", &[dim])); } + let dimension = Dim::from_id(dim); + let coordinate_scale = |dim| if dim == Dim::Nether { 8.0 } else { 1.0 }; + let scale = coordinate_scale(s.dimension) / coordinate_scale(dimension); vec![Source { - elsewhere: dim != self.dim.id(), + pos: [s.pos[0] * scale, s.pos[1], s.pos[2] * scale], + dimension, level: Some(super::super::Dim::from_id(dim)), ..s }] @@ -633,7 +642,7 @@ impl Game<'_> { }) .collect() } - fn target_with_uuid(&self, uuid: [i32; 4]) -> Option { + pub(super) fn target_with_uuid(&self, uuid: [i32; 4]) -> Option { if Some(uuid) == self.level.player_uuid { return Some(Target::Player); } @@ -656,7 +665,7 @@ impl Game<'_> { if state == self.world.air { continue; } - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); let blocks = facts.legacy_solid || facts.fluid != horizon_client::blocks::Fluid::None; let leaves = self .pack @@ -792,14 +801,16 @@ impl Game<'_> { let p = self .coords(c, "pos") .map(|co| co.block(self.source_position(), self.source_rotation())); - return Ok(flag(p.is_some_and(|p| { - self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4)) - }))); + let dimension = self.command_source.map_or(self.dim, |s| s.dimension); + return Ok(flag( + dimension == self.dim + && p.is_some_and(|p| self.world.chunks.contains_key(&(p[0] >> 4, p[2] >> 4))), + )); } if c.has("dimension") { - return Ok(flag( - matches!(c.get("dimension"), Some(Arg::Resource(d)) if d == self.dim.id()), - )); + let dimension = self.command_source.map_or(self.dim, |s| s.dimension); + return Ok(flag(matches!(c.get("dimension"), Some(Arg::Resource(d)) + if d.as_str() == dimension.id()))); } if c.has("block") { let p = self.block_pos_arg(c, "pos")?; @@ -948,7 +959,7 @@ impl Game<'_> { let chunk = self.world.chunks.get(&(p[0] >> 4, p[2] >> 4))?; Some( self.res - .biomes + .biomes() .get(chunk.biome(p[0], p[1], p[2])) .name .clone(), @@ -971,7 +982,7 @@ impl Game<'_> { .resources .join(format!("data/{ns}/tags/worldgen/biome/{path}.json")); let Ok(bytes) = std::fs::read(file) else { - return self.res.mob_data.biome_has(tag, biome); + return self.res.mob_data().biome_has(tag, biome); }; let v: serde_json::Value = serde_json::from_slice(&bytes).unwrap_or_default(); v["values"].as_array().is_some_and(|a| { diff --git a/crates/horizon-client/src/game/commands/extra.rs b/crates/horizon-client/src/game/commands/extra.rs index a90648043..7a4accb0d 100644 --- a/crates/horizon-client/src/game/commands/extra.rs +++ b/crates/horizon-client/src/game/commands/extra.rs @@ -586,7 +586,7 @@ impl Game<'_> { ); let hit = traverse_blocks(eye, end, 256, |b: BlockPos| { let state = self.world.block(b.x, b.y, b.z); - (!self.res.facts.is_air(state)).then_some([b.x, b.y, b.z]) + (!self.res.facts().is_air(state)).then_some([b.x, b.y, b.z]) }); hit.ok().flatten().unwrap_or([ end.x.floor() as i32, diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index c71eebc68..fde97764d 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -375,7 +375,11 @@ impl Game<'_> { } else { 0 }; - let max = self.res.items.get(&stack.item).map_or(64, |i| i.max_stack); + let max = self + .res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack); stack.count = (base + n).clamp(0, max as i32) as u32; } "minecraft:limit_count" => { @@ -389,7 +393,11 @@ impl Game<'_> { } } "minecraft:set_damage" => { - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); if max > 0 { let f = match m["damage"].as_f64() { Some(f) => f as f32, @@ -587,7 +595,7 @@ impl Game<'_> { if let Some(Tag::Int(n)) = s.data().and_then(|d| d.other("minecraft:max_stack_size")) { return (*n).clamp(1, 99) as u32; } - self.res.items.get(&s.item).map_or(64, |i| i.max_stack) + self.res.items().get(&s.item).map_or(64, |i| i.max_stack) } /// `ResourceOrIdArgument.getItemModifier`: an inline modifier (SNBT) or /// a registered one. diff --git a/crates/horizon-client/src/game/commands/place.rs b/crates/horizon-client/src/game/commands/place.rs index 3e447a7fb..016f6e2fe 100644 --- a/crates/horizon-client/src/game/commands/place.rs +++ b/crates/horizon-client/src/game/commands/place.rs @@ -53,13 +53,7 @@ impl Game<'_> { let Ok(raw) = Compression::Gzip.decode(&bytes, 1 << 28) else { continue; }; - let Ok((named, _)) = nbt::read_named( - &raw, - Limits { - max_bytes: 1 << 28, - ..Limits::default() - }, - ) else { + let Ok((named, _)) = nbt::read_named(&raw, Limits::templates()) else { continue; }; return Some(Arc::new(StructureTemplate::from_nbt( @@ -79,10 +73,10 @@ impl Game<'_> { } /// `PlaceCommand.checkLoaded`: every chunk of the inclusive range. fn place_check_loaded(&self, min: [i32; 2], max: [i32; 2]) -> R<()> { - let elsewhere = self.command_source.is_some_and(|s| s.elsewhere); + let dimension = self.command_source.map_or(self.dim, |s| s.dimension); for cx in min[0]..=max[0] { for cz in min[1]..=max[1] { - if elsewhere || !self.world.chunks.contains_key(&(cx, cz)) { + if dimension != self.dim || !self.world.chunks.contains_key(&(cx, cz)) { return Err(err("argument.pos.unloaded", &[])); } } diff --git a/crates/horizon-client/src/game/commands/players.rs b/crates/horizon-client/src/game/commands/players.rs new file mode 100644 index 000000000..d71c219a8 --- /dev/null +++ b/crates/horizon-client/src/game/commands/players.rs @@ -0,0 +1,210 @@ +//! Commands acting on the other players of a hosted world or a server +//! (EntitySelector.findPlayers and EntityArgument's player targets). The +//! player in place (the host's, or the guest whose turn it is) is +//! `Target::Player`; every other guest is `Target::Guest`, found by name, +//! UUID or selector, and what a command does to them runs with their state +//! swapped in (`for_player`), as their own turn, what it tells them going to +//! their chat. +use super::{Game, Target}; +use horizon_client::{command::args::Selector, lan::guest::Guest, text::Text}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +impl Target { + /// A player, in place or not (`instanceof ServerPlayer`). + pub(in crate::game) fn is_player(self) -> bool { + matches!(self, Target::Player | Target::Guest(_)) + } +} + +/// GameType.getName for a guest's game mode id. +fn mode_name(id: i32) -> &'static str { + match id { + 1 => "creative", + 2 => "adventure", + 3 => "spectator", + _ => "survival", + } +} + +impl Game<'_> { + /// The guest `conn`, while the hub is in `self.lan`. + pub(in crate::game) fn command_guest(&self, conn: u32) -> Option<&Guest> { + self.lan.as_ref()?.hub.guest(conn) + } + + /// `PlayerList.getPlayers` but the player in place: the guests who + /// joined the world. + fn command_players(&self) -> impl Iterator { + let acting = self.lan_acting; + self.lan + .iter() + .flat_map(|h| h.hub.guests.iter()) + .filter(move |g| g.placed && Some(g.conn) != acting) + } + + /// The entity the command runs as (`CommandSourceStack.getEntity`): a + /// command typed by the player in place runs as them, the server + /// console's as nobody. + pub(in crate::game) fn source_entity(&self) -> Option { + match self.command_source { + Some(s) => s.entity, + None => self.player.is_some().then_some(Target::Player), + } + } + + /// `CommandSourceStack.getPlayerOrException` for the commands whose + /// player argument is optional: the source's player (the player in + /// place when it has none, as before). + pub(in crate::game) fn implied_player(&self) -> Target { + self.source_entity() + .filter(|t| t.is_player()) + .unwrap_or(Target::Player) + } + + /// `PlayerList.getPlayerByName`: names are not case sensitive. + pub(super) fn player_named(&self, name: &str) -> Option { + if self.player.is_some() && name.eq_ignore_ascii_case(self.acting_player_name()) { + return Some(Target::Player); + } + self.command_players() + .find(|g| g.name.eq_ignore_ascii_case(name)) + .map(|g| Target::Guest(g.conn)) + } + + /// `EntitySelector.findEntities` with a UUID: the player with it, else + /// the entity. + pub(super) fn target_by_uuid(&self, uuid: u128) -> Option { + let own = self.lan_acting_uuid.or_else(|| { + self.level.player_uuid.map(|[a, b, c, d]| { + (u128::from(a as u32) << 96) + | (u128::from(b as u32) << 64) + | (u128::from(c as u32) << 32) + | u128::from(d as u32) + }) + }); + if self.player.is_some() && own == Some(uuid) { + return Some(Target::Player); + } + if let Some(g) = self.command_players().find(|g| g.uuid == uuid) { + return Some(Target::Guest(g.conn)); + } + let words = [96, 64, 32, 0].map(|shift| (uuid >> shift) as u32 as i32); + self.target_with_uuid(words) + } + + /// The guests a selector looks at, in join order (`PlayerList.getPlayers`), + /// the one in place as `Target::Player`: all of them, or those in the + /// source's level when it limits the search to a place + /// (`isWorldLimited`); `@e` and `@n` skip the dead (`Entity::isAlive`). + pub(super) fn player_candidates(&self, s: &Selector) -> Vec { + let limited = s.distance.is_some() + || s.pos.iter().any(Option::is_some) + || s.delta.iter().any(Option::is_some); + let alive = matches!(s.kind, 'e' | 'n'); + let here = self.dim.id(); + let in_place = self.lan_acting.filter(|_| self.player.is_some()); + self.lan + .iter() + .flat_map(|h| h.hub.guests.iter()) + .filter(|g| g.placed) + .filter(|g| !limited || g.dimension == here || Some(g.conn) == in_place) + .filter(|g| !alive || (!g.dead && g.health > 0.0)) + .map(|g| { + if Some(g.conn) == in_place { + Target::Player + } else { + Target::Guest(g.conn) + } + }) + .collect() + } + + /// A guest's experience level and game mode, for `level=` and `gamemode=`. + pub(super) fn guest_level_and_mode(&self, conn: u32) -> Option<(i32, &'static str)> { + self.command_guest(conn) + .map(|g| (g.xp_level, mode_name(g.game_mode))) + } + + /// `Player.getDisplayName`: the name as its team shows it, suggesting a + /// `/tell`, showing the player on hover, inserting the name. + pub(in crate::game) fn player_text(&self, name: &str, uuid: u128) -> Text { + let shown = match self.score.board.players_team(name) { + Some(team) => team.formatted_name(Text::literal(name)), + None => Text::literal(name), + }; + shown.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()), + ]) + } + + /// Run `f` for the player `t` (None for anything else): in place, or + /// with the guest's state swapped in, in their level, as their own turn. + /// What `f` tells the player (`system_message`) goes to their chat; the + /// command's own feedback is the caller's to send. + pub(in crate::game) fn for_player( + &mut self, + t: Target, + f: impl FnOnce(&mut Self) -> T, + ) -> Option { + let conn = match t { + Target::Player => return Some(f(self)), + Target::Guest(conn) if self.lan_acting == Some(conn) => return Some(f(self)), + Target::Guest(conn) => conn, + _ => return None, + }; + let mut host = self.lan.take()?; + let back = self.dim; + let theirs = host + .hub + .guest(conn) + .map(|g| super::super::Dim::from_id(&g.dimension)); + if let Some(dim) = theirs.filter(|d| *d != back) + && let Err(e) = self.enter_level(Some(&mut host), dim) + { + log::error!("could not open {}: {e}", dim.id()); + } + let Some(swap) = self.enter_guest(&mut host, conn) else { + if self.dim != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + self.lan = Some(host); + return None; + }; + self.lan = Some(host); + let source = self.chat_capture.replace(Vec::new()); + let out = f(self); + let told = std::mem::replace(&mut self.chat_capture, source).unwrap_or_default(); + let mut host = self + .lan + .take() + .expect("the hub is back after a player's turn"); + self.leave_guest(&mut host, swap); + for line in told { + host.hub.send_to( + conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + if self.dim != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + self.lan = Some(host); + Some(out) + } +} diff --git a/crates/horizon-client/src/game/commands/terrain_cmds.rs b/crates/horizon-client/src/game/commands/terrain_cmds.rs index cee7a1d72..46df0ce7d 100644 --- a/crates/horizon-client/src/game/commands/terrain_cmds.rs +++ b/crates/horizon-client/src/game/commands/terrain_cmds.rs @@ -174,7 +174,7 @@ impl Game<'_> { if volume > i64::from(limit) { return Err(err("commands.fillbiome.toobig", &[&limit, &volume])); } - let Some(target) = self.res.biomes.list.iter().position(|b| b.name == biome) else { + let Some(target) = self.res.biomes().list.iter().position(|b| b.name == biome) else { return Err(err( "argument.resource.not_found", &[&biome, &"minecraft:worldgen/biome"], @@ -201,7 +201,7 @@ impl Game<'_> { continue; }; let current = chunk.biome(x, y, z); - let current_name = &self.res.biomes.list[usize::from(current)].name; + let current_name = &self.res.biomes().list[usize::from(current)].name; if let Some(f) = &filter && !self.biome_matches(f, current_name) { @@ -474,11 +474,11 @@ impl Game<'_> { let json = horizon_client::scoreboard::tag_to_json(&tag); let drops = self .res - .items + .items() .inline_loot_table(&json, &mut self.world.random); (drops, None) } else { - if !self.res.items.has_loot_table(&table) { + if !self.res.items().has_loot_table(&table) { return Err(err("argument.resource_or_id.failed_to_parse", &[&table])); } let held = if id == "loot.fish" { @@ -486,14 +486,14 @@ impl Game<'_> { } else { None }; - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res - .items + .items() .loot_table(&table, false, held.as_ref(), random) } - None => self.res.items.loot_table( + None => self.res.items().loot_table( &table, false, held.as_ref(), @@ -510,7 +510,7 @@ impl Game<'_> { }; let ty = self.target_type(t); let table = format!("minecraft:entities/{}", ty.trim_start_matches("minecraft:")); - if t == Target::Player || !self.res.items.has_loot_table(&table) { + if t == Target::Player || !self.res.items().has_loot_table(&table) { return Err(err( "commands.drop.no_loot_table.entity", &[&self.target_name(t).plain()], @@ -521,14 +521,14 @@ impl Game<'_> { None | Some(Some(Target::Player)) ); let held = self.slot_get(&super::items::Slot::Inv(self.selected)); - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); self.res - .items + .items() .entity_drops(&ty, by_player, held.as_ref(), random) } - None => self.res.items.entity_drops( + None => self.res.items().entity_drops( &ty, by_player, held.as_ref(), @@ -543,21 +543,21 @@ impl Game<'_> { let state = self.world.block(p[0], p[1], p[2]); let name = self.data_block_name(p); let table = format!("minecraft:blocks/{}", name.trim_start_matches("minecraft:")); - if !self.res.items.has_loot_table(&table) { + if !self.res.items().has_loot_table(&table) { return Err(err("commands.drop.no_loot_table.block", &[&name])); } let tool = self.tool_stack(ctx)?; - let drops = match self.res.items.loot_sequence(&table) { + let drops = match self.res.items().loot_sequence(&table) { Some(seq) => { let random = self.rand_sequences.get(&seq, self.level.seed); - self.res.items.block_drops( + self.res.items().block_drops( self.pack.assets.registry, state, tool.as_ref(), random, ) } - None => self.res.items.block_drops( + None => self.res.items().block_drops( self.pack.assets.registry, state, tool.as_ref(), @@ -624,7 +624,7 @@ impl Game<'_> { && cur.damage == left.damage && cur.extra == left.extra => { - let max = self.res.items.get(&cur.item).map_or(64, |i| i.max_stack); + let max = self.res.items().get(&cur.item).map_or(64, |i| i.max_stack); let take = left.count.min(max.saturating_sub(cur.count)); if take > 0 { cur.count += take; diff --git a/crates/horizon-client/src/game/commands/world_cmds.rs b/crates/horizon-client/src/game/commands/world_cmds.rs index 2055798f4..ef2adf80c 100644 --- a/crates/horizon-client/src/game/commands/world_cmds.rs +++ b/crates/horizon-client/src/game/commands/world_cmds.rs @@ -31,7 +31,7 @@ impl Game<'_> { /// Every recipe id of the recipe manager (what `/recipe` resolves and suggests). pub(super) fn learnable_recipes(&self) -> Vec { - self.res.stations.recipe_index.ids().cloned().collect() + self.res.stations().recipe_index.ids().cloned().collect() } pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R { let targets = self.entities(ctx, "targets", true)?; @@ -52,7 +52,7 @@ impl Game<'_> { // displays (a transmute recipe has one per material count). let mut n = 0; // ServerPlayer.awardRecipes / resetRecipes: the displays changed. - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; n += if give { let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes); self.recipe_unlocked(&unlocked); @@ -1267,7 +1267,7 @@ impl Game<'_> { fn spread_spawn_y(&self, p: [f64; 2], max_y: i32) -> i32 { let (x, z) = (p[0].floor() as i32, p[1].floor() as i32); let air = |y: i32| { - let name: &str = &self.res.facts.get(self.world.block(x, y, z)).name; + let name: &str = &self.res.facts().get(self.world.block(x, y, z)).name; matches!( name, "minecraft:air" | "minecraft:cave_air" | "minecraft:void_air" @@ -1292,16 +1292,16 @@ impl Game<'_> { fn spread_safe(&self, p: [f64; 2], max_y: i32) -> bool { let y = self.spread_spawn_y(p, max_y) - 1; let (x, z) = (p[0].floor() as i32, p[1].floor() as i32); - let name = self.res.facts.get(self.world.block(x, y, z)).name.clone(); + let name = self.res.facts().get(self.world.block(x, y, z)).name.clone(); let liquid = matches!(&*name, "minecraft:water" | "minecraft:lava"); let teleportable = self .res - .items + .items() .block_tags .get("entities_can_teleport_to") .or_else(|| { self.res - .items + .items() .block_tags .get("minecraft:entities_can_teleport_to") }) diff --git a/crates/horizon-client/src/game/composter.rs b/crates/horizon-client/src/game/composter.rs index 3e4cb7169..3f57229ad 100644 --- a/crates/horizon-client/src/game/composter.rs +++ b/crates/horizon-client/src/game/composter.rs @@ -21,7 +21,7 @@ impl Game<'_> { } /// The item's `compostable` layers provider. fn compostable(&self, stack: &ItemStack) -> Option { - self.res.items.get(&stack.item)?.compostable.clone() + self.res.items().get(&stack.item)?.compostable.clone() } /// `ComposterBlock.addLayer` and level event 1500: the provider is /// evaluated in the composter's block-interaction loot context (its diff --git a/crates/horizon-client/src/game/consume.rs b/crates/horizon-client/src/game/consume.rs new file mode 100644 index 000000000..50b1fa814 --- /dev/null +++ b/crates/horizon-client/src/game/consume.rs @@ -0,0 +1,330 @@ +//! Finishing a consumable (`Consumable.onConsume` and the use remainder), +//! its particles and sounds, and `TeleportRandomlyConsumeEffect` (chorus +//! fruit) for the local player. The level random stands in for the player's +//! own, as for every other player draw. +use super::{Dim, Game}; +use horizon_client::{ + items::{ConsumeEffect, ItemInfo, ItemStack}, + mobs::Who, + particles::{ParticleOptions, ParticleType}, +}; +use horizon_core::{ + geometry::Vec3, position::BlockPos, random::LegacyRandom, random::RandomSource, +}; +use horizon_world::{ + consumable::{Consumable, EmissionWorld, UseAnimation}, + teleport_consume::{TeleportConsume, TeleportConsumeWorld}, +}; +use std::convert::Infallible; + +type ItemConsumable = Consumable; + +impl Game<'_> { + /// `Consumable.emitParticlesAndSounds(user.getRandom(), user, stack, count)`. + pub(super) fn emit_consume( + &mut self, + consumable: &ItemConsumable, + stack: &ItemStack, + count: i32, + ) { + let Ok(()) = consumable.emit(&mut Emitter(self), (), stack.clone(), count); + } + /// `LivingEntity.completeUsingItem` for a consumable: `Consumable.onConsume`, + /// then `ItemStack.applyAfterUseComponentSideEffects`' use remainder. + pub(super) fn finish_consuming( + &mut self, + info: &ItemInfo, + consumable: &ItemConsumable, + stack: &ItemStack, + ) { + self.emit_consume(consumable, stack, 16); + // ServerPlayer: the used statistic and the consume_item trigger. + self.stats.add("used", &stack.item, 1); + self.trigger_item("minecraft:consume_item", stack); + // FoodProperties.onConsume, the player's one ConsumableListener. + if let Some((nutrition, saturation)) = info.food { + let at = self.feet(); + let pitch = self.world.random.triangle_float(1.0, 0.4); + self.audio.play(&consumable.sound, at, 1.0, pitch); + 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); + } + // Mth.randomBetween(random, 0.9, 1.0) + let pitch = self.world.random.next_float() * (1.0f32 - 0.9f32) + 0.9; + self.audio + .play("minecraft:entity.player.burp", self.feet(), 0.5, pitch); + } + for effect in &consumable.effects { + self.apply_consume_effect(effect); + } + let event = if consumable.animation == UseAnimation::Drink { + "minecraft:drink" + } else { + "minecraft:eat" + }; + self.post_entity_event(event, Who::Player); + // ItemStack.consume, then UseRemainder.convertIntoRemainder: nothing + // with infinite materials, the hand when emptied, else the inventory + // (ServerPlayer.handleExtraItemsCreatedOnUse) or a drop. + self.consume_held(); + if let Some(remainder) = &info.use_remainder + && !self.creative + { + let remainder = ItemStack::new(remainder, 1); + if self.held().is_none() { + *self.held_mut() = Some(remainder); + } else if let Some(rest) = self.give(remainder) { + self.player_drop(rest); + } + } + } + fn feet(&self) -> Option<[f64; 3]> { + self.player + .as_ref() + .map(|p| [p.position.x, p.position.y, p.position.z]) + } + /// `TeleportRandomlyConsumeEffect.apply` for the local player. + pub(super) fn teleport_randomly(&mut self, teleport: &TeleportConsume) { + if self.player.is_none() { + return; + } + let dim = self.dim; + let Ok(_) = teleport.apply(&mut Teleporter(self), dim); + } + /// `LivingEntity.randomTeleport(x, y, z, true, avoid)`: down to the first + /// block entities can teleport onto, inside the border, in a loaded chunk. + fn random_teleport(&mut self, target: Vec3, avoid: &str) -> bool { + let [min_x, min_z, max_x, max_z] = self.border.bounds(); + // WorldBorder.clampVec3ToBound (Mth.clamp, 1.0E-5F inside the far edge). + let clamp = |v: f64, low: f64, high: f64| if v < low { low } else { v.min(high) }; + let x = clamp(target.x, min_x, max_x - f64::from(1.0e-5_f32)); + let z = clamp(target.z, min_z, max_z - f64::from(1.0e-5_f32)); + let mut y = target.y; + let mut pos = BlockPos::containing(Vec3::new(x, y, z)); + if !self.world.loaded(pos.x, pos.z) { + return false; + } + while pos.y > self.dim.min_y() { + pos.y -= 1; + let state = self.world.block(pos.x, pos.y, pos.z); + if self.state_in_tag("minecraft:entities_can_teleport_to", state) { + return self.check_position_and_teleport(Vec3::new(x, y, z), state, avoid); + } + y -= 1.0; + } + false + } + /// `LivingEntity.checkPositionAndTeleport`, then `ServerPlayer.teleportTo` + /// (the motion and rotation kept) and entity event 46. + fn check_position_and_teleport( + &mut self, + at: Vec3, + ground: horizon_world::registry::BlockStateId, + avoid: &str, + ) -> bool { + if self.state_in_tag(avoid, ground) { + return false; + } + let entities = self.happy_ghast_player_collisions(); + let Some(player) = self.player.as_mut() else { + return false; + }; + let bounds = player.dimensions.bounds(at); + let free = horizon_client::motion::MotionWorld { + entities: &entities, + player, + scene: &mut self.world, + assets: &self.pack.assets, + collision_binding: self.collision, + resources: self.motion, + } + .no_player_collision(bounds) + .unwrap_or(false); + // LevelReader.containsAnyLiquid and findBlocksIn: the blocks from the + // box's minimum corner to the one holding its maximum corner. + let (lo, hi) = ( + BlockPos::containing(bounds.min_position()), + BlockPos::containing(bounds.max_position()), + ); + let blocks = (lo.x..=hi.x) + .flat_map(|x| (lo.y..=hi.y).flat_map(move |y| (lo.z..=hi.z).map(move |z| (x, y, z)))); + let states: Vec<_> = blocks.map(|(x, y, z)| self.world.block(x, y, z)).collect(); + let liquid = states + .iter() + .any(|&s| self.res.facts().get(s).fluid != horizon_client::blocks::Fluid::None); + if !free || liquid || states.iter().any(|&s| self.state_in_tag(avoid, s)) { + return false; + } + if let Some(p) = self.player.as_mut() { + p.position = at; + } + // The position packet moves the old position along (absolute xyz). + self.previous_position = at; + self.portal_particles(); + true + } + fn state_in_tag(&self, tag: &str, state: horizon_world::registry::BlockStateId) -> bool { + let name = &self.res.facts().get(state).name; + self.res + .items() + .block_tags + .get(tag) + .is_some_and(|s| s.contains(&**name)) + } + /// `LivingEntity.handleEntityEvent(46)`: 128 portal particles from the old + /// to the new position, from the client player's random (the particle + /// engine's here). + fn portal_particles(&mut self) { + let Some(p) = self.player.as_ref() else { + return; + }; + let (from, to) = (self.previous_position, p.position); + let (width, height) = ( + f64::from(p.dimensions.width), + f64::from(p.dimensions.height), + ); + let options = ParticleOptions::simple(ParticleType::Portal); + for i in 0..128 { + let d = f64::from(i) / 127.0; + let r = self.particles.random(); + let v = [0; 3].map(|_| f64::from((r.next_float() - 0.5) * 0.2)); + let x = from.x + d * (to.x - from.x) + (r.next_double() - 0.5) * width * 2.0; + let y = from.y + d * (to.y - from.y) + r.next_double() * height; + let z = from.z + d * (to.z - from.z) + (r.next_double() - 0.5) * width * 2.0; + self.particles.add(&options, [x, y, z], v); + } + } + /// `LivingEntity.stopRiding`. + pub(super) fn stop_riding(&mut self) { + let Some(id) = self.riding else { + return; + }; + if let Some(i) = self.boats.iter().position(|b| b.id == id) { + self.dismount(i); + } else if let Some(i) = self.carts.iter().position(|c| c.id == id) { + self.dismount_cart(i); + } else { + self.dismount_mount(); + } + } +} + +/// `Consumable.emitParticlesAndSounds` against the local player. +struct Emitter<'a, 'g>(&'a mut Game<'g>); +impl EmissionWorld for Emitter<'_, '_> { + type Error = Infallible; + type Stack = ItemStack; + type Sound = String; + type Random = (); + type Source = LegacyRandom; + fn random_source(&mut self, (): ()) -> &mut LegacyRandom { + &mut self.0.world.random + } + /// `LivingEntity.spawnItemParticles`. + fn spawn_item_particles(&mut self, stack: ItemStack, count: i32) -> Result<(), Infallible> { + self.0.eat_particles(&stack, count.max(0) as u32); + Ok(()) + } + fn overrides_consume_sound(&self) -> bool { + false + } + fn consume_sound(&mut self, _: ItemStack) -> Result { + unreachable!("players play the consumable's own sound") + } + /// `Entity.playSound`: at the player's position. + fn play_sound(&mut self, sound: String, volume: f32, pitch: f32) -> Result<(), Infallible> { + let at = self.0.feet(); + self.0.audio.play(&sound, at, volume, pitch); + Ok(()) + } +} + +/// The local player as `TeleportRandomlyConsumeEffect`'s user. +struct Teleporter<'a, 'g>(&'a mut Game<'g>); +impl Teleporter<'_, '_> { + fn at(&self) -> Vec3 { + self.0.player.as_ref().map_or(Vec3::ZERO, |p| p.position) + } +} +impl TeleportConsumeWorld for Teleporter<'_, '_> { + type Error = Infallible; + type Level = Dim; + type Random = (); + type Source = LegacyRandom; + fn position_field(&self) -> Vec3 { + self.at() + } + fn get_random(&mut self) -> Result<(), Infallible> { + Ok(()) + } + fn random_source(&mut self, (): ()) -> &mut LegacyRandom { + &mut self.0.world.random + } + fn min_y(&mut self, level: Dim) -> Result { + Ok(level.min_y()) + } + fn logical_height(&mut self, level: Dim) -> Result { + Ok(level.logical_height()) + } + fn is_passenger(&mut self) -> Result { + Ok(self.0.riding.is_some()) + } + fn stop_riding(&mut self) -> Result<(), Infallible> { + self.0.stop_riding(); + Ok(()) + } + fn position(&mut self) -> Result { + Ok(self.at()) + } + fn random_teleport(&mut self, target: Vec3) -> Result { + Ok(self + .0 + .random_teleport(target, "minecraft:consumable_does_not_teleport_to")) + } + fn teleport_event(&mut self, _: Dim, old: Vec3) -> Result<(), Infallible> { + let ctx = self.0.who_context(Some(Who::Player), None); + self.0 + .post_game_event("minecraft:teleport", [old.x, old.y, old.z], ctx); + Ok(()) + } + fn is_fox(&self) -> bool { + false + } + fn teleport_sound(&mut self, _: Dim, at: Vec3, _: bool) -> Result<(), Infallible> { + self.0.audio.play( + "minecraft:item.chorus_fruit.teleport", + Some([at.x, at.y, at.z]), + 1.0, + 1.0, + ); + Ok(()) + } + fn block_position(&mut self) -> Result { + Ok(BlockPos::containing(self.at())) + } + fn directional_particles( + &mut self, + _: Dim, + origin: BlockPos, + offset: i32, + ) -> Result<(), Infallible> { + self.0 + .level_event_at(2017, [origin.x, origin.y, origin.z], offset); + Ok(()) + } + fn reset_fall_distance(&mut self) -> Result<(), Infallible> { + if let Some(p) = self.0.player.as_mut() { + p.fall_distance = 0.0; + } + Ok(()) + } + fn reset_impulse(&mut self) -> Result<(), Infallible> { + if let Some(p) = self.0.player.as_mut() { + p.impulse.reset(); + } + Ok(()) + } +} diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 6827d49c9..3e0711aeb 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -54,12 +54,23 @@ pub struct Flight { /// Reply with every frame time too (`fly ... PITCH raw`). raw: bool, reply: Sender, + /// The world's smoothed tick time each frame (the F3 server line): the + /// server thread's when single player runs on one. + tick_ms: Vec, } impl Game<'_> { /// Move the camera along the running flight; reply when it ends. pub(super) fn advance_flight(&mut self) { - let Some(flight) = &self.flight else { return }; + let tick_ms = self + .integrated + .as_ref() + .map_or(self.debug_charts.smoothed_tick_ms, |s| s.smoothed_tick_ms()); + let Some(flight) = self.flight.as_mut() else { + return; + }; + flight.tick_ms.push(tick_ms); + let flight = &*flight; let t = (flight.started.elapsed().as_secs_f64() / flight.seconds).min(1.0); let (a, b) = (flight.from, flight.to); let d = [b.x - a.x, b.y - a.y, b.z - a.z]; @@ -79,6 +90,9 @@ impl Game<'_> { && let Some(flight) = self.flight.take() { let mut summary = self.frame_stats.summary(); + let n = flight.tick_ms.len().max(1) as f32; + summary["tick_ms"] = (flight.tick_ms.iter().sum::() / n).into(); + summary["tick_ms_max"] = flight.tick_ms.iter().copied().fold(0.0, f32::max).into(); if flight.raw { summary["frame_ms"] = self.frame_stats.frame_millis().into(); summary["cpu_ms"] = self.frame_stats.cpu_millis().into(); @@ -183,6 +197,16 @@ impl Game<'_> { } Ok(Some(json!({ "ok": true, "flat": r.flat_draws() }))) } + "section-cull" => { + let r = self.renderer.as_mut().ok_or("no renderer")?; + match words.get(1).copied() { + None => {} + Some("on") => r.set_section_cull(true)?, + Some("off") => r.set_section_cull(false)?, + Some(other) => return Err(format!("unknown section cull mode {other}").into()), + } + Ok(Some(json!({ "ok": true, "cull": r.section_cull() }))) + } "sculk" => Ok(Some(self.sculk_command(&words)?)), "status" => Ok(Some(self.control_status())), "pad" => Ok(Some(self.pad_command(&words)?)), @@ -345,10 +369,18 @@ impl Game<'_> { }; let info = self .res - .items + .items() .get(&item) .ok_or_else(|| format!("unknown item {item}"))?; let count: u32 = words.get(2).map_or(Ok(1), |c| c.parse())?; + // Single player's inventory is its server thread's player's. + if let Some(server) = &self.integrated { + let command = format!("give @s {item} {count}"); + server + .call(move |g| g.owner_console_command(&command)) + .ok_or("the integrated server stopped")?; + return Ok(Some(json!({ "ok": true, "given": count }))); + } let max = info.max_stack; let mut given = 0; // Stop once the inventory is full. @@ -379,7 +411,14 @@ impl Game<'_> { ok() } "time" => { - self.world.day_time = arg(1)?.parse()?; + let time: i64 = arg(1)?.parse()?; + self.world.day_time = time; + // Single player's clock is its server thread's. + if let Some(server) = &self.integrated { + server + .call(move |g| g.world.day_time = time) + .ok_or("the integrated server stopped")?; + } ok() } "summon" => { @@ -437,7 +476,7 @@ impl Game<'_> { match self.screen { Screen::Chat => self.chat_type(text), Screen::CommandBlock => self.command_block_type(text), - Screen::Options => self.ui.options.type_text(&self.atlas, text), + Screen::Options => self.ui.options.type_text(&self.gui.atlas, text), // The port, or the game rules' search and number boxes. Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions => self.world_options_text(Some(text)), @@ -527,6 +566,7 @@ impl Game<'_> { seconds: n(7)?.max(0.1), raw: words.get(9) == Some(&"raw"), reply: reply.clone(), + tick_ms: Vec::new(), }); Ok(None) } @@ -661,7 +701,7 @@ impl Game<'_> { }); let target = self.pick().map(|hit| { let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - json!({ "pos": hit.pos, "block": &*self.res.facts.get(state).name }) + json!({ "pos": hit.pos, "block": &*self.res.facts().get(state).name }) }); let renderer = self.renderer.as_ref().map(|r| { let [arena_bytes, section_vertex_bytes] = r.section_vertex_bytes(); @@ -684,6 +724,7 @@ impl Game<'_> { "drawn_sections": r.drawn_sections, "section_draws": r.section_draws, "section_draw_calls": r.section_draw_calls, + "culled_sections": r.culled_sections(), "uploaded_bytes": r.uploaded_bytes, "resident_sections": r.resident_sections(), "arena_bytes": arena_bytes, diff --git a/crates/horizon-client/src/game/copper_golems.rs b/crates/horizon-client/src/game/copper_golems.rs index a12fbd416..2f98e1c7e 100644 --- a/crates/horizon-client/src/game/copper_golems.rs +++ b/crates/horizon-client/src/game/copper_golems.rs @@ -106,7 +106,7 @@ impl Game<'_> { fn golem_chest_sound(&mut self, p: [i32; 3], open: bool) { let name = self .res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone(); @@ -292,7 +292,7 @@ impl Game<'_> { pub(super) fn golem_shearable(&self, index: usize) -> bool { self.mobs[index].saddle_item().is_some_and(|a| { self.res - .items + .items() .item_tags .get("minecraft:shearable_from_copper_golem") .is_some_and(|t| t.contains(&*a.item)) diff --git a/crates/horizon-client/src/game/creaking.rs b/crates/horizon-client/src/game/creaking.rs index 1df29a3e4..e7a1386f9 100644 --- a/crates/horizon-client/src/game/creaking.rs +++ b/crates/horizon-client/src/game/creaking.rs @@ -110,7 +110,7 @@ impl Game<'_> { let mut next_entity = self.next_entity; let mut random = self.world.random.clone(); let spawning = self.spawning_monsters(); - let creaking = self.res.mob_types.get("minecraft:creaking").cloned(); + let creaking = self.res.mob_types().get("minecraft:creaking").cloned(); let player_uuid = self.level.player_uuid; let snapshot: Vec<_> = mobs.iter().map(|m| seen(m, player_uuid)).collect(); let mut events = Vec::new(); @@ -220,6 +220,12 @@ 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]); + if !matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::CreakingHeart(_)) + ) { + return; + } let Some(BlockEntity::CreakingHeart(mut heart)) = self.world.block_entities.take(&key) else { return; @@ -259,7 +265,7 @@ impl Game<'_> { return Ok(()); }; let state = self.world.block(key.0, key.1, key.2); - if &*self.res.facts.get(state).name != "minecraft:creaking_heart" { + 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| { @@ -311,7 +317,7 @@ impl Game<'_> { if self.creaking.hearts.is_empty() { self.creaking.hearts = self .res - .facts + .facts() .states .iter() .map(|f| &*f.name == "minecraft:creaking_heart") diff --git a/crates/horizon-client/src/game/creatures.rs b/crates/horizon-client/src/game/creatures.rs index 3ef399e62..d82e8a5aa 100644 --- a/crates/horizon-client/src/game/creatures.rs +++ b/crates/horizon-client/src/game/creatures.rs @@ -204,8 +204,8 @@ impl Game<'_> { let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else { return BiomeFacts::default(); }; - let b = self.res.biomes.get(chunk.biome(x, y, z)); - let tags = &self.res.mob_data; + let b = self.res.biomes().get(chunk.biome(x, y, z)); + let tags = self.res.mob_data(); let has = |t: &str| tags.biome_has(t, &b.name); let climate = if has("minecraft:spawns_warm_variant_farm_animals") { Climate::Warm @@ -255,7 +255,7 @@ impl Game<'_> { } else { format!("minecraft:{kind}") }; - let t = self.res.mob_types.get(&kind).cloned()?; + let t = self.res.mob_types().get(&kind).cloned()?; self.next_entity += 1; let yaw = self.world.random.next_float() * 360.0; let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), yaw); @@ -368,7 +368,7 @@ impl Game<'_> { pub(super) fn motion_top(&self, x: i32, z: i32) -> i32 { let top = if self.dim == Dim::Nether { 127 } else { 319 }; for y in (horizon_client::chunk::MIN_Y..=top).rev() { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if (f.full_collision || f.fluid != Fluid::None) && !f.name.ends_with("leaves") { return y + 1; } @@ -377,14 +377,16 @@ impl Game<'_> { } pub(super) fn mob_world_base<'s>(&'s self, others: &'s [Seen]) -> MobWorld<'s> { let (rain, thunder) = self.world.weather.levels(1.0); + let player = self.player_view(); MobWorld { world: &self.world, registry: self.pack.assets.registry, - facts: &self.res.facts, + facts: self.res.facts(), movement: &self.motion.blocks, collision: self.collision, - data: &self.res.mob_data, - player: self.player_view(), + data: self.res.mob_data(), + nearest_player: player.as_ref().filter(|p| !p.spectator).map(|p| p.position), + player, others, others_grid: None, daylight: self.dim != Dim::Nether && self.sky_darken() < 4, @@ -393,14 +395,14 @@ impl Game<'_> { raining: rain > 0.2, thundering: thunder > 0.9, nether: self.dim == Dim::Nether, - block_tags: &self.res.items.block_tags, - biomes: &self.res.biomes, + block_tags: &self.res.items().block_tags, + biomes: self.res.biomes(), mob_griefing: self.ui.rules.bool("mob_griefing"), end: self.dim == Dim::End, world_seed: self.level.seed, sea_level: if self.dim == Dim::Nether { 32 } else { 63 }, teams: self.mob_teams(), - items: Some(&self.res.items), + items: Some(self.res.items()), difficulty: self.local_difficulty( self.player .as_ref() @@ -429,25 +431,6 @@ impl Game<'_> { }; spawning::LocalDifficulty::new(base, self.world.day_time, inhabited, moon) } - /// `ServerChunkCache.tickSpawningChunk`: chunks whose centre is within - /// 128 blocks of the player gain inhabited time. - fn tick_inhabited(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { - return; - }; - let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); - for dx in -8..=8 { - for dz in -8..=8 { - let key = (pcx + dx, pcz + dz); - let (cx, cz) = (f64::from(key.0 * 16 + 8), f64::from(key.1 * 16 + 8)); - if (cx - p.x).powi(2) + (cz - p.z).powi(2) < 128.0 * 128.0 - && self.world.chunks.contains_key(&key) - { - *self.world.inhabited.entry(key).or_insert(0) += 1; - } - } - } - } /// Advance every mob one tick, then apply their events. pub(super) fn tick_creatures(&mut self) -> Result<()> { self.attack_ticks = self.attack_ticks.saturating_add(1); @@ -464,7 +447,6 @@ impl Game<'_> { } self.spawn_generation_creatures(key.0, key.1); } - self.tick_inhabited(); self.tick_leads(); self.spawn_natural(); // ServerChunkCache.tickChunks: the custom spawners tick only with spawn_mobs. @@ -475,24 +457,11 @@ impl Game<'_> { self.tick_raids(); self.tick_creature_entities() } - /// `DistanceManager.inEntityTickingRange`: chunks within the simulation - /// distance (Chebyshev, in chunks) of the player or of a guest. + /// `DistanceManager.inEntityTickingRange` in an entity-ticking chunk + /// (block coordinates), from every player's tickets (`update_chunk_tickets`). pub(super) fn entity_ticking_area(&self) -> impl Fn(i32, i32) -> bool + use<> { - let d = self.settings.simulation_distance.max(2); - 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(); - move |x, z| { - everywhere - || centres - .iter() - .any(|&(cx, cz)| ((x >> 4) - cx).abs().max(((z >> 4) - cz).abs()) <= d) - } + let levels = self.tickets.levels(); + move |x, z| levels.entity_ticking_at(x, z) } /// The entity phase of `tick_creatures`: every mob's tick, deaths, and the /// projectiles and effects that follow from them. @@ -518,6 +487,7 @@ impl Game<'_> { let ticking = self.entity_ticking_area(); // With guests on, each mob sees its nearest player (game/lan_mobs.rs). let guests = self.lan_guest_views(); + let players = self.level_players(); let mut bindings = match self.lan.as_mut() { Some(host) if !guests.is_empty() => std::mem::take(&mut host.mob_players), _ => Default::default(), @@ -536,6 +506,13 @@ impl Game<'_> { let mut w = self.mob_world_base(&snapshot); w.others_grid = Some(&grid); let m = &mut mobs[i]; + w.nearest_player = super::natural_spawning::nearest_player( + &players, + m.position.x, + m.position.y, + m.position.z, + ) + .map(|p| p.position); let seen_guest = if guests.is_empty() { None } else { @@ -984,7 +961,7 @@ impl Game<'_> { if effect { let old = self.world.block(pos[0], pos[1], pos[2]); self.destroy_particles(pos, old); - let s = self.res.facts.get(old).sounds.break_sound.clone(); + let s = self.res.facts().get(old).sounds.break_sound.clone(); self.audio.play( &s, Some([ @@ -1004,7 +981,7 @@ impl Game<'_> { let old = self.world.block(pos[0], pos[1], pos[2]); self.destroy_particles(pos, old); if drop { - let drops = self.res.items.block_drops_in( + let drops = self.res.items().block_drops_in( self.pack.assets.registry, old, None, @@ -1158,7 +1135,7 @@ impl Game<'_> { MobEvent::GiftLoot { table, at } => { let drops = self.res - .items + .items() .loot_table(table, false, None, &mut self.world.random); for d in drops { self.spawn_item(d, at, [0.0, 0.2, 0.0], 10); @@ -1421,7 +1398,7 @@ impl Game<'_> { } let projectile = self .res - .stations + .stations() .enchantments .damage_tags .get("minecraft:is_projectile") @@ -1781,7 +1758,7 @@ impl Game<'_> { horizon_client::arrows::ArrowScene { world: &self.world, registry: self.pack.assets.registry, - facts: &self.res.facts, + facts: self.res.facts(), collision: self.collision, fluids: &self.motion.fluids, raining: rain, @@ -2033,7 +2010,7 @@ impl Game<'_> { let fire = [pos[0] + face[0], pos[1] + face[1], pos[2] + face[2]]; if self .res - .facts + .facts() .is_air(self.world.block(fire[0], fire[1], fire[2])) && let Some(state) = self.pack.assets.registry.default_state("minecraft:fire") @@ -2359,7 +2336,7 @@ impl Game<'_> { Species::Sheep if item == "minecraft:shears" && !m.extra.sheared && !m.is_baby() => { m.extra.sheared = true; let color = horizon_client::mobs::render::DYE_NAMES[m.extra.color as usize & 15]; - let stacks = self.res.items.loot_table( + let stacks = self.res.items().loot_table( &format!("minecraft:shearing/sheep/{color}"), false, None, @@ -2391,7 +2368,7 @@ impl Game<'_> { Species::Wolf if m.extra.tame && is_food && m.health < m.attrs.max_health => { let heal = self .res - .items + .items() .get(&item) .and_then(|i| i.food.as_ref()) .map_or(2.0, |f| f.0 as f32); @@ -2495,7 +2472,7 @@ impl Game<'_> { Species::Cat if m.extra.tame && is_food && m.health < m.attrs.max_health => { let heal = self .res - .items + .items() .get(&item) .and_then(|i| i.food.as_ref()) .map_or(1.0, |f| f.0 as f32); @@ -2662,7 +2639,7 @@ impl Game<'_> { return; } if let Some(stack) = self.inventory[self.selected].as_mut() - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 { stack.damage += 1; @@ -2735,7 +2712,7 @@ impl Game<'_> { // EntityType.canSpawn: no monsters in peaceful (FAIL ends the click). let id = format!("minecraft:{}", kind.trim_start_matches("minecraft:")); if self.ui.difficulty == 0 - && let Some(t) = self.res.mob_types.get(&id) + && let Some(t) = self.res.mob_types().get(&id) && !horizon_client::mobs::spawn_rules::allowed_in_peaceful(t.species) { return Ok(true); @@ -2799,7 +2776,7 @@ impl Game<'_> { } /// Mob models and projectiles for the entity pass. pub(super) fn mob_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let scale = f64::from(self.settings.entity_distance); for mob in &self.mobs { @@ -2857,7 +2834,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &armor, out, ); @@ -3016,7 +2993,7 @@ impl Game<'_> { } /// Mob.getBaseExperienceReward /// The damage type id of a Horizon damage kind. -fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { +pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static str { use horizon_client::mobs::DamageKind as K; match kind { K::PlayerAttack => "minecraft:player_attack", @@ -3101,13 +3078,17 @@ impl Game<'_> { return; } let mut y = pos[1]; - while &*self.res.facts.get(self.world.block(pos[0], y, pos[2])).name + while &*self + .res + .facts() + .get(self.world.block(pos[0], y, pos[2])) + .name == "minecraft:nether_portal" { y -= 1; } // isValidSpawn: a sturdy top face (portal frames emit no light). - let below = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + let below = self.res.facts().get(self.world.block(pos[0], y, pos[2])); if below.sturdy_full & (1 << 1) == 0 { return; } diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 1de6669e7..a2e1b0ce6 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -51,6 +51,9 @@ impl DebugHost for Host<'_, '_> { impl Game<'_> { fn open_screen(&self) -> OpenScreen { + if self.title.is_some() { + return OpenScreen::Other; + } match self.screen { Screen::GameModeSwitcher => OpenScreen::GameModeSwitcher, Screen::Playing if self.book.is_none() && self.sign_edit.is_none() => OpenScreen::None, @@ -437,7 +440,7 @@ impl Game<'_> { } } let (left, right) = d.columns(&self.debug_chart_lines()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut draws = debug_overlay::draw(&atlas.font, [&left, &right], scale, width); let charts = self.debug_charts.draw( &atlas.font, diff --git a/crates/horizon-client/src/game/decorated_pot.rs b/crates/horizon-client/src/game/decorated_pot.rs index 3ac43566a..af2eaacb2 100644 --- a/crates/horizon-client/src/game/decorated_pot.rs +++ b/crates/horizon-client/src/game/decorated_pot.rs @@ -63,7 +63,7 @@ impl Game<'_> { /// pot without), or None when no pot is there. fn pot_tag(&mut self, pos: [i32; 3]) -> Option { let state = self.world.block(pos[0], pos[1], pos[2]); - if &*self.res.facts.get(state).name != "minecraft:decorated_pot" { + if &*self.res.facts().get(state).name != "minecraft:decorated_pot" { return None; } let mut tag = spill::saved_entity(&self.world, pos).unwrap_or_else(|| { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index 8a8ed63f9..640318529 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -11,9 +11,7 @@ use horizon_client::{ Result, lan::{LoginGate, NetConfig, NetLog, OnlineMode, hub::HubConfig}, server::{ - eula, - java_properties::now_millis, - profiles, + eula, profiles, properties::{GAME_MODES, ServerProperties, SystemEntropy}, user_cache::UserCache, user_lists::{ @@ -84,18 +82,16 @@ fn log_from(thread: &str, level: &str, message: &str) { "ERROR" => ::log::Level::Error, _ => ::log::Level::Info, }; - horizon_client::logging::write_only(file_level, message); + horizon_client::logging::write_as(thread, file_level, message); CAPTURE.with_borrow_mut(|lines| { if let Some(lines) = lines { lines.push(message.to_owned()); } }); - let secs = now_millis().div_euclid(1000).rem_euclid(86_400); + // Log4j's %d{HH:mm:ss}: the local time, as in logs/latest.log. println!( - "[{:02}:{:02}:{:02}] [{thread}/{level}]: {message}", - secs / 3600, - secs / 60 % 60, - secs % 60 + "[{}] [{thread}/{level}]: {message}", + chrono::Local::now().format("%H:%M:%S") ); } @@ -340,7 +336,7 @@ impl Game<'_> { ); } let settings = if flat { - let biomes = &self.res.biomes; + 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(), @@ -431,6 +427,7 @@ const BROADCAST: &[&str] = &[ impl Game<'_> { /// DedicatedServer.initServer and MinecraftServer.runServer. pub(super) fn run_dedicated(&mut self) -> Result<()> { + self.join_world_rest()?; let Setup { props, universe, @@ -683,7 +680,7 @@ impl Game<'_> { self.ticks = self.ticks.max(1); } // MinecraftServer.tickServer: while paused only the connections run. - self.tick_server(paused)?; + self.tick_server_timed(paused)?; if idle_timeout > 0 { self.kick_idle(idle_timeout); } @@ -829,6 +826,7 @@ impl Game<'_> { self.console_command(state, line); self.console_broadcast = None; if let Some(mut host) = self.lan.take() { + self.run_level_teleports(&mut host); self.send_admin_feedback(&mut host, None); self.lan = Some(host); } diff --git a/crates/horizon-client/src/game/dispense_fixture.rs b/crates/horizon-client/src/game/dispense_fixture.rs index fbad3cfc7..ab7a6cf48 100644 --- a/crates/horizon-client/src/game/dispense_fixture.rs +++ b/crates/horizon-client/src/game/dispense_fixture.rs @@ -114,9 +114,9 @@ impl Game<'_> { } fn fixture_reset(&mut self, seed: i64) { - self.world = World::new(self.res.facts.air, seed); + self.world = World::new(self.res.facts().air, seed); // The oracle level is plains everywhere (bone meal's flowers, freezing). - let plains = u32::from(self.res.biomes.id("minecraft:plains")); + let plains = u32::from(self.res.biomes().id("minecraft:plains")); for cx in -2..=2 { for cz in -2..=2 { let mut chunk = Chunk::empty(cx, cz); @@ -198,7 +198,7 @@ impl Game<'_> { let state = BlockStateId(cell[3].as_u64().unwrap_or(0) as u32); self.world.set(p.0, p.1, p.2, state)?; before.insert(p, state.0); - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(p, entity); } } @@ -284,7 +284,7 @@ impl Game<'_> { let state = self.world.block(origin.x, origin.y, origin.z); let mut used = Vec::new(); if let Some(op) = case.get("remove") { - self.fixture_remove(origin, op)?; + used = self.fixture_remove(origin, op)?; } else if let Some(op) = case.get("use") { used = self.fixture_use(origin, op)?; } else if let Some(op) = case.get("use_item") { @@ -339,7 +339,7 @@ impl Game<'_> { changed.dedup(); for p in changed { let now = self.world.block(p.0, p.1, p.2).0; - if before.get(&p).copied().unwrap_or(self.res.facts.air.0) != now { + if before.get(&p).copied().unwrap_or(self.res.facts().air.0) != now { out.push(format!("set {},{},{} {now}", p.0, p.1, p.2)); } } @@ -706,7 +706,7 @@ impl Game<'_> { /// lectern's book, or the items of a block entity Horizon keeps as saved. fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option) { let jukebox = - &*self.res.facts.get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox"; + &*self.res.facts().get(self.world.block(p.0, p.1, p.2)).name == "minecraft:jukebox"; match self.world.block_entities.get_mut(&p) { Some(BlockEntity::Jukebox(j)) => j.record = stack, Some(BlockEntity::Lectern(l)) => l.book = stack, @@ -735,7 +735,7 @@ impl Game<'_> { use horizon_world::nbt::Tag; let name = self .res - .facts + .facts() .get(self.world.block(p.0, p.1, p.2)) .name .clone(); @@ -788,8 +788,9 @@ impl Game<'_> { other => *other = Tag::List(vec![item]), } } - /// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block. - fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result<()> { + /// `Level.setBlock`, `destroyBlock` or `removeBlock` on the case's block, or + /// a player mining it (`fixture_mine`). + fn fixture_remove(&mut self, origin: BlockPos, op: &Value) -> Result> { match op["op"].as_str().unwrap_or("") { "set" => { let state = BlockStateId(op["state"].as_u64().unwrap_or(0) as u32); @@ -803,9 +804,61 @@ impl Game<'_> { "remove" => { self.with_level(|b, level, ticks| b.remove_block(level, ticks, origin, false)); } + "mine" => return self.fixture_mine(origin, op), other => return Err(format!("unknown removal {other}").into()), } - self.process_level_events() + self.process_level_events()?; + Ok(Vec::new()) + } + + /// A survival player three blocks south of `pos` mines it holding the + /// case's item (`break_block`, which every player's mining goes through): + /// the statistics and the held stack, as `VanillaDispenserOracle.mine` + /// prints them. + fn fixture_mine(&mut self, pos: BlockPos, op: &Value) -> Result> { + let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?; + self.mode = GameMode::Survival; + self.creative = false; + self.player = Some(PlayerMotion::new( + self.motion, + horizon_core::geometry::Vec3::new( + f64::from(pos.x) + 0.5, + f64::from(pos.y) + 1.0, + f64::from(pos.z) + 3.5, + ), + )?); + self.yaw = 0.0; + self.pitch = 90.0; + self.keys.clear(); + self.inventory[self.selected] = stack.clone(); + self.offhand = None; + let state = self.world.block(pos.x, pos.y, pos.z); + let block = self.res.facts().get(state).name.clone(); + let item = stack.as_ref().map(|s| s.item.clone()); + let before = |game: &Self| { + let used = item.as_ref().map_or(0, |i| game.stats.get("used", i)); + (used, game.stats.get("mined", &block)) + }; + let (used, mined) = before(self); + self.break_block([pos.x, pos.y, pos.z])?; + let (used_after, mined_after) = before(self); + let mut out = Vec::new(); + if let Some(item) = &item + && used_after != used + { + out.push(format!("stat {item} minecraft:used {}", used_after - used)); + } + if mined_after != mined { + out.push(format!( + "stat {block} minecraft:mined {}", + mined_after - mined + )); + } + out.push(format!( + "mine held {}", + canon_stack(self.inventory[self.selected].as_ref()) + )); + Ok(out) } /// `EntityType.create` and `snapTo` for one target: no spawn finalization. @@ -829,7 +882,7 @@ impl Game<'_> { } let t = self .res - .mob_types + .mob_types() .get(kind) .cloned() .ok_or_else(|| format!("no mob type {kind}"))?; diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index cb28aa1cc..0f59e5300 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -328,18 +328,18 @@ impl Game<'_> { self.world.block(p.0, p.1, p.2) } fn dispenser_block_name(&self, p: Pos) -> std::sync::Arc { - self.res.facts.get(self.block_at(p)).name.clone() + self.res.facts().get(self.block_at(p)).name.clone() } fn in_block_tag(&self, tag: &str, block: &str) -> bool { self.res - .items + .items() .block_tags .get(tag) .is_some_and(|s| s.contains(block)) } fn water_at(&self, p: Pos) -> bool { matches!( - self.res.behaviours.fluid_kind(self.block_at(p)), + self.res.behaviours().fluid_kind(self.block_at(p)), FluidKind::Water | FluidKind::FlowingWater ) } @@ -520,7 +520,7 @@ impl Game<'_> { if let Some(entity) = self.world.block_entities.get_mut(&pos) { let max = self .res - .items + .items() .get(&rest.item) .map_or(64, |i| i.max_stack) .max(1); @@ -555,7 +555,11 @@ impl Game<'_> { } /// `ItemStack.hurtAndBreak(amount)` without an entity. fn hurt_and_break(&mut self, mut stack: ItemStack, amount: u32) -> Option { - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); if max == 0 { return Some(stack); } @@ -637,7 +641,7 @@ impl Game<'_> { ) -> Result { let equippable = self .res - .items + .items() .get(&stack.item) .is_some_and(|i| i.equip_slot.is_some()); if equippable { @@ -649,7 +653,7 @@ impl Game<'_> { } let swallowable = self .res - .items + .items() .item_tags .get("minecraft:sulfur_cube_swallowable") .is_some_and(|t| t.contains(&*stack.item)); @@ -748,7 +752,7 @@ impl Game<'_> { } else { format!("minecraft:{kind}") }; - let t = self.res.mob_types.get(&name)?.clone(); + let t = self.res.mob_types().get(&name)?.clone(); let y_off = if try_move_down { self.drop_offset(t.width, t.height, p) } else { @@ -768,7 +772,7 @@ impl Game<'_> { /// `EquipmentDispenseItemBehavior.dispenseEquipment`: the first living /// entity in front that `canEquipWithDispenser` gets one of the item. fn dispense_equipment(&mut self, pos: Pos, facing: Direction, stack: &mut ItemStack) -> bool { - let Some(info) = self.res.items.get(&stack.item) else { + let Some(info) = self.res.items().get(&stack.item) else { return false; }; let (Some(slot), true) = ( @@ -1078,7 +1082,7 @@ impl Game<'_> { let below = (front.0, front.1 - 1, front.2); let y_offset = if self.water_at(front) { 1.0 - } else if self.res.facts.is_air(self.block_at(front)) && self.water_at(below) { + } else if self.res.facts().is_air(self.block_at(front)) && self.water_at(below) { 0.0 } else { return (self.dispense_default(pos, facing, stack), CLICK); @@ -1116,7 +1120,7 @@ impl Game<'_> { let y_offset = if let Some(rail) = self.rail(front.0, front.1, front.2) { if rail.shape.is_slope() { 0.6 } else { 0.1 } } else { - if !self.res.facts.is_air(self.block_at(front)) { + if !self.res.facts().is_air(self.block_at(front)) { return (self.dispense_default(pos, facing, stack), CLICK); } let below = (front.0, front.1 - 1, front.2); @@ -1389,7 +1393,7 @@ impl Game<'_> { stack: ItemStack, ) -> Result { let target = offset(pos, facing); - let free = self.res.facts.is_air(self.block_at(target)) + let free = self.res.facts().is_air(self.block_at(target)) && target.1 >= horizon_client::chunk::MIN_Y + 2 && self.ui.difficulty != 0 && self.can_build_wither(target); @@ -1443,7 +1447,7 @@ impl Game<'_> { "minecraft:soul_sand" | "minecraft:soul_soil" ) }; - let air = |p: Pos| self.res.facts.is_air(self.block_at(p)); + let air = |p: Pos| self.res.facts().is_air(self.block_at(p)); for (ax, az) in [(1, 0), (0, 1)] { for col in 0..3 { let left = (head.0 - ax * col, head.1, head.2 - az * col); @@ -1466,7 +1470,7 @@ impl Game<'_> { stack: ItemStack, ) -> Result { let target = offset(pos, facing); - if self.res.facts.is_air(self.block_at(target)) + if self.res.facts().is_air(self.block_at(target)) && self.can_spawn_golem([target.0, target.1, target.2]) { if let Some(pumpkin) = self @@ -1511,7 +1515,7 @@ impl Game<'_> { let front = offset(pos, facing); let below_empty = self .res - .facts + .facts() .is_air(self.block_at((front.0, front.1 - 1, front.2))); let clicked_face = if below_empty { facing } else { Direction::Up }; let ctx = PlaceContext { @@ -1539,7 +1543,7 @@ impl Game<'_> { return Ok((Some(stack), FAIL)); }; let target = (placed.x, placed.y, placed.z); - if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) { + if let Some(entity) = BlockEntity::for_block(&self.res.facts().get(state).name) { self.world.block_entities.insert(target, entity); self.apply_placed_item([target.0, target.1, target.2], &stack, false); } @@ -1689,14 +1693,14 @@ impl Game<'_> { table: &str, held: Option<&ItemStack>, ) -> Vec { - match self.res.items.loot_sequence(parent) { + match self.res.items().loot_sequence(parent) { Some(sequence) => { let random = self.rand_sequences.get(&sequence, self.level.seed); - self.res.items.loot_table_from(table, false, held, random) + self.res.items().loot_table_from(table, false, held, random) } None => self .res - .items + .items() .loot_table(table, false, held, &mut self.world.random), } } @@ -1717,7 +1721,7 @@ impl Game<'_> { /// random draws) keeps the name, flags, persistence and age; the old one /// is discarded. pub(super) fn convert_mob(&mut self, index: usize, kind: &str) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; let old = &self.mobs[index]; self.next_entity += 1; let mut mob = Mob::new(self.next_entity, t, old.position, old.yaw); diff --git a/crates/horizon-client/src/game/dragon.rs b/crates/horizon-client/src/game/dragon.rs index e76eb16fb..cbfad527b 100644 --- a/crates/horizon-client/src/game/dragon.rs +++ b/crates/horizon-client/src/game/dragon.rs @@ -447,9 +447,9 @@ impl Game<'_> { } fn end_portal_active(&self) -> bool { (0..256).any(|y| { - &*self.res.facts.get(self.world.block(0, y, 0)).name == "minecraft:bedrock" + &*self.res.facts().get(self.world.block(0, y, 0)).name == "minecraft:bedrock" && (-3..=3).any(|d| { - &*self.res.facts.get(self.world.block(d, y, 0)).name == "minecraft:end_portal" + &*self.res.facts().get(self.world.block(d, y, 0)).name == "minecraft:end_portal" }) }) } @@ -591,7 +591,7 @@ impl Game<'_> { let p = self.crystals[i].position; let b = [p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32]; if let Some(fire) = fire - && self.res.facts.is_air(self.world.block(b[0], b[1], b[2])) + && self.res.facts().is_air(self.world.block(b[0], b[1], b[2])) && self.world.loaded(b[0], b[2]) { let _ = self.level_set(b, fire); @@ -764,7 +764,7 @@ impl Game<'_> { let held = self.held().cloned(); let modifiers = held .as_ref() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map(|i| (i.attack_damage, i.attack_speed)) .unwrap_or((0.0, 0.0)); let speed = (4.0 + modifiers.1).max(0.1); @@ -813,7 +813,7 @@ impl Game<'_> { (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); (f.full_collision || f.legacy_solid || f.fluid != horizon_client::blocks::Fluid::None) @@ -1257,7 +1257,7 @@ impl Game<'_> { let (x, z) = (head.x + look.x * 2.5, head.z + look.y * 2.5); let mut y = head.y + 0.5; while y > 0.0 - && self.res.facts.is_air(self.world.block( + && self.res.facts().is_air(self.world.block( x.floor() as i32, y.floor() as i32, z.floor() as i32, @@ -1594,7 +1594,7 @@ impl Game<'_> { return; }; let boxes = [d.part_box(0), d.part_box(1), d.part_box(2)]; - let tags = &self.res.items.block_tags; + let tags = &self.res.items().block_tags; let transparent = tags .get("minecraft:dragon_transparent") .cloned() @@ -1610,8 +1610,8 @@ impl Game<'_> { for y in lo.y.floor() as i32..=hi.y.floor() as i32 { for z in lo.z.floor() as i32..=hi.z.floor() as i32 { let state = self.world.block(x, y, z); - let name = &self.res.facts.get(state).name; - if self.res.facts.is_air(state) || transparent.contains(&**name) { + let name = &self.res.facts().get(state).name; + if self.res.facts().is_air(state) || transparent.contains(&**name) { continue; } if griefing && !immune.contains(&**name) { @@ -1713,7 +1713,7 @@ impl Game<'_> { let y = (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(0, y, 0)); + let f = self.res.facts().get(self.world.block(0, y, 0)); f.full_collision || f.legacy_solid }) .map_or(64, |y| y + 1); @@ -1767,7 +1767,7 @@ impl Game<'_> { next.y.floor() as i32, next.z.floor() as i32, ]; - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); f.full_collision || f.legacy_solid }; let hit_player = player.is_some_and(|pb| { @@ -1869,9 +1869,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, &bars, - &self.atlas.font, + &self.gui.atlas.font, ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`, /// with `setCreateWorldFog`). @@ -1909,7 +1909,13 @@ impl Game<'_> { return; }; let a = alpha as f32; - let sprite = |n: &str| self.atlas.sprites.get(n).map(|r| [r.u0, r.v0, r.u1, r.v1]); + let sprite = |n: &str| { + self.gui + .atlas + .sprites + .get(n) + .map(|r| [r.u0, r.v0, r.u1, r.v1]) + }; let (Some(skin), Some(eyes)) = ( sprite("entity/enderdragon/dragon"), sprite("entity/enderdragon/dragon_eyes"), @@ -2075,7 +2081,7 @@ impl Game<'_> { } /// `submitRays`: the death rays from a fixed seed, fading in white to magenta. fn dragon_rays(&self, base: glam::Mat4, t: f32, out: &mut Vec) { - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let uv = [white.u0, white.v0]; let over = if t > 0.8 { ((t - 0.8) / 0.2).min(1.0) @@ -2131,6 +2137,7 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self + .gui .atlas .sprites .get("entity/end_crystal/end_crystal_beam") @@ -2192,6 +2199,7 @@ impl Game<'_> { out: &mut Vec, ) { let Some(s) = self + .gui .atlas .sprites .get("entity/enderdragon/dragon_fireball") @@ -2381,7 +2389,7 @@ impl Game<'_> { } let name = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])) .name .clone(); @@ -2391,7 +2399,7 @@ impl Game<'_> { let above = [hit.pos[0], hit.pos[1] + 1, hit.pos[2]]; if !self .res - .facts + .facts() .is_air(self.world.block(above[0], above[1], above[2])) { return false; @@ -2512,7 +2520,7 @@ impl Game<'_> { } fn block_name_at(&self, p: [i32; 3]) -> std::sync::Arc { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -2614,7 +2622,7 @@ impl Game<'_> { for y in h - 10..=h + 10 { for z in cz - 10..=cz + 10 { for x in cx - 10..=cx + 10 { - if !self.res.facts.is_air(self.world.block(x, y, z)) { + if !self.res.facts().is_air(self.world.block(x, y, z)) { let _ = self.level_set([x, y, z], air); } } @@ -2636,7 +2644,7 @@ impl Game<'_> { if &*self.block_name_at([x, y, z]) != "minecraft:obsidian" { let _ = self.set_state_named([x, y, z], "minecraft:obsidian", &[]); } - } else if y > 65 && !self.res.facts.is_air(self.world.block(x, y, z)) { + } else if y > 65 && !self.res.facts().is_air(self.world.block(x, y, z)) { let _ = self.level_set([x, y, z], air); } } diff --git a/crates/horizon-client/src/game/enchant_effects.rs b/crates/horizon-client/src/game/enchant_effects.rs index 1e36b00f0..0aa3138f6 100644 --- a/crates/horizon-client/src/game/enchant_effects.rs +++ b/crates/horizon-client/src/game/enchant_effects.rs @@ -16,7 +16,7 @@ impl Game<'_> { let held = self.inventory[self.selected].as_ref(); speed += self .res - .stations + .stations() .enchantments .attribute_add(held, "minecraft:mining_efficiency") as f32; } @@ -26,7 +26,7 @@ impl Game<'_> { pub(super) fn submerged_mining_speed(&self) -> f32 { let mut total = 0.0; for stack in self.armor.iter().flatten() { - for (attr, _, amount, op) in self.res.stations.enchantments.attributes(stack) { + for (attr, _, amount, op) in self.res.stations().enchantments.attributes(stack) { if attr == "minecraft:submerged_mining_speed" && op == "add_multiplied_total" { total += amount; } @@ -36,13 +36,13 @@ impl Game<'_> { } /// `EnchantmentHelper.processDurabilityChange` (unbreaking) for `amount` points. pub(super) fn durability_loss(&mut self, stack: &ItemStack, amount: u32) -> u32 { - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; if !e.has_component(stack, "minecraft:item_damage") { return amount; } let ctx = EffectContext { tool: Some(&stack.item), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; e.modify_value( @@ -65,10 +65,10 @@ impl Game<'_> { direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:player_attack"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - self.res.stations.enchantments.modify_value( + self.res.stations().enchantments.modify_value( Some(&held), "minecraft:damage", &ctx, @@ -96,10 +96,10 @@ impl Game<'_> { attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let knockback = self.res.stations.enchantments.modify_value( + let knockback = self.res.stations().enchantments.modify_value( Some(&held), "minecraft:knockback", &ctx, @@ -130,7 +130,7 @@ impl Game<'_> { // minecraft:post_attack ignite effects of the attacker's weapon (fire aspect). let mut ignite = 0.0f32; for (id, level) in held.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:post_attack"] @@ -145,7 +145,7 @@ impl Game<'_> { let mut random = self.world.random.clone(); let ok = effect.get("requirements").is_none_or(|r| { self.res - .stations + .stations() .enchantments .condition(r, *level, &ctx, &mut random) }); @@ -182,13 +182,13 @@ impl Game<'_> { attacker: Some("minecraft:player"), direct_attacker: Some("minecraft:player"), is_direct: true, - items: Some(&self.res.items), + items: Some(self.res.items()), direct_motion: Some(motion), ..Default::default() }; let mut bursts = Vec::new(); for (id, level) in held.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:post_attack"] @@ -205,7 +205,7 @@ impl Game<'_> { continue; } let ok = effect.get("requirements").is_none_or(|r| { - self.res.stations.enchantments.condition( + self.res.stations().enchantments.condition( r, *level, &ctx, @@ -254,16 +254,16 @@ impl Game<'_> { if level == 0 { continue; } - let Some(def) = self.res.stations.enchantments.get("minecraft:thorns") else { + let Some(def) = self.res.stations().enchantments.get("minecraft:thorns") else { continue; }; let effect = def.effects["minecraft:post_attack"][0].clone(); let ctx = EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let mut random = self.world.random.clone(); - let ok = self.res.stations.enchantments.condition( + let ok = self.res.stations().enchantments.condition( &effect["requirements"], level, &ctx, @@ -286,7 +286,7 @@ impl Game<'_> { s.damage += 2; if self .res - .items + .items() .get(&s.item) .is_some_and(|i| s.damage >= i.max_damage) { @@ -330,10 +330,10 @@ impl Game<'_> { }; let Some(stack) = stack else { return amount }; let ctx = EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let to_repair_xp = self.res.stations.enchantments.modify_value( + let to_repair_xp = self.res.stations().enchantments.modify_value( Some(&stack), "minecraft:repair_with_xp", &ctx, @@ -364,11 +364,11 @@ impl Game<'_> { let Some(bow) = self.inventory[self.selected].clone() else { return (0.0, false); }; - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let ctx = EffectContext { direct_attacker: Some("minecraft:arrow"), attacker: Some("minecraft:player"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let power = e.modify_value( @@ -380,7 +380,7 @@ impl Game<'_> { ); let ammo_ctx = EffectContext { tool: Some("minecraft:arrow"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let infinity = e.has_component(&bow, "minecraft:ammo_use") @@ -399,12 +399,12 @@ impl Game<'_> { let bow = self.inventory[self.selected].clone()?; let ctx = EffectContext { this: Some("minecraft:arrow"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; let mut ignite: Option = None; for (id, level) in bow.enchantments() { - let Some(def) = self.res.stations.enchantments.get(id) else { + let Some(def) = self.res.stations().enchantments.get(id) else { continue; }; for effect in def.effects["minecraft:projectile_spawned"] @@ -416,7 +416,7 @@ impl Game<'_> { continue; } let ok = effect.get("requirements").is_none_or(|r| { - self.res.stations.enchantments.condition( + self.res.stations().enchantments.condition( r, *level, &ctx, @@ -436,7 +436,7 @@ impl Game<'_> { pub(super) fn apply_enchantment_attributes(&mut self) { let mut wanted: Vec<(String, String, f64, String)> = Vec::new(); for stack in self.armor.iter().flatten() { - wanted.extend(self.res.stations.enchantments.attributes(stack)); + wanted.extend(self.res.stations().enchantments.attributes(stack)); } let Some(p) = self.player.as_mut() else { return; diff --git a/crates/horizon-client/src/game/end.rs b/crates/horizon-client/src/game/end.rs index a80c51796..34026bb07 100644 --- a/crates/horizon-client/src/game/end.rs +++ b/crates/horizon-client/src/game/end.rs @@ -132,9 +132,9 @@ impl Game<'_> { /// The environment attributes of the current dimension. pub(super) fn dim_environment(&self) -> &Environment { match self.dim { - Dim::Overworld => &self.res.environment, - Dim::Nether => &self.res.nether_environment, - Dim::End => &self.res.end_environment, + Dim::Overworld => self.res.environment(), + Dim::Nether => self.res.nether_environment(), + Dim::End => self.res.end_environment(), } } @@ -142,7 +142,7 @@ impl Game<'_> { /// tinted 0x282828. The atlas does not wrap, so each face is 16×16 quads. pub(super) fn end_sky_geometry(&self) -> Vec { let mut out = Vec::with_capacity(6 * 256 * 4); - let Some(r) = self.atlas.sprites.get("environment/end_sky").copied() else { + let Some(r) = self.gui.atlas.sprites.get("environment/end_sky").copied() else { return out; }; use std::f32::consts::FRAC_PI_2; @@ -184,6 +184,7 @@ impl Game<'_> { let intensity = self.end.flash.intensity(self.clock.fraction() as f32); if intensity > 1e-5 && let Some(r) = self + .gui .atlas .sprites .get("environment/celestial/end_flash") @@ -224,7 +225,7 @@ impl Game<'_> { pub(super) fn block_name(&self, p: [i32; 3]) -> std::sync::Arc { self.res - .facts + .facts() .get(self.world.block(p[0], p[1], p[2])) .name .clone() @@ -561,7 +562,7 @@ impl Game<'_> { let mut y = (0..256) .rev() .find(|&y| { - let f = self.res.facts.get(self.world.block(0, y, 0)); + let f = self.res.facts().get(self.world.block(0, y, 0)); (f.full_collision || f.fluid != horizon_client::blocks::Fluid::None) && !f.name.ends_with("_leaves") }) @@ -783,7 +784,7 @@ impl Game<'_> { let mut y = 255; while y > floor { let p = [around[0] + xd, y, around[2] + zd]; - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); if f.full_collision && (allow_bedrock || &*f.name != "minecraft:bedrock") { tallest = Some(p); break; @@ -839,12 +840,12 @@ impl Game<'_> { if &*self.block_name([x, y, z]) != "minecraft:end_stone" || self .res - .facts + .facts() .get(self.world.block(x, y + 1, z)) .full_collision || self .res - .facts + .facts() .get(self.world.block(x, y + 2, z)) .full_collision { @@ -920,7 +921,8 @@ impl Game<'_> { fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec) { let (Some(model), Some(r)) = ( self.crystal_model.as_ref(), - self.atlas + self.gui + .atlas .sprites .get("entity/end_crystal/end_crystal") .copied(), @@ -1073,7 +1075,7 @@ impl Game<'_> { /// ThrownItemRenderer: the ender eye item facing the camera. fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let Some(r) = self.atlas.sprites.get("item/ender_eye").copied() else { + let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else { return; }; let alpha = self.clock.fraction(); diff --git a/crates/horizon-client/src/game/entity_culling.rs b/crates/horizon-client/src/game/entity_culling.rs index b710f4e73..3abf92835 100644 --- a/crates/horizon-client/src/game/entity_culling.rs +++ b/crates/horizon-client/src/game/entity_culling.rs @@ -21,7 +21,7 @@ impl Game<'_> { && self.settings.resource_packs.iter().all(|id| id == "vanilla") && self.player.is_some() && !self.spectator() - && !opaque(self.res.facts.get(self.world.block(at[0], at[1], at[2])))) + && !opaque(self.res.facts().get(self.world.block(at[0], at[1], at[2])))) .then(|| Culler::new(camera.to_array(), 8_192)); } @@ -31,7 +31,7 @@ impl Game<'_> { if let Some(culler) = &self.entity_culler { culler.cull_vertices(vertices, start, |pos| { let state = self.world.block(pos[0], pos[1], pos[2]); - if !opaque(self.res.facts.get(state)) { + if !opaque(self.res.facts().get(state)) { return false; } let Some(y) = pos[1].checked_sub(MIN_Y) else { diff --git a/crates/horizon-client/src/game/events.rs b/crates/horizon-client/src/game/events.rs index 0ffff1b59..8a4207a7f 100644 --- a/crates/horizon-client/src/game/events.rs +++ b/crates/horizon-client/src/game/events.rs @@ -167,7 +167,11 @@ impl Game<'_> { Snapshot { screen: self.screen_label(), dimension: self.dim.id().to_string(), - chat: self.ui.chat.received, + // A remote client counts the server's lines itself. + chat: self + .remote + .as_ref() + .map_or(self.ui.chat.received, |r| r.chat_received), counts: if world.is_some() { self.inventory_counts() } else { @@ -189,8 +193,19 @@ impl Game<'_> { if let Some(before) = &self.events.last && *before != now { - let new_chat = (now.chat - before.chat).min(100) as usize; - let lines = self.ui.chat.recent_lines(new_chat); + // Joining or leaving a server starts another count. + let new_chat = now.chat.saturating_sub(before.chat).min(100) as usize; + // Newest first; the remote client keeps its lines oldest first. + let lines = match &self.remote { + Some(r) => r + .chat + .iter() + .rev() + .take(new_chat) + .map(|(t, _)| t.clone()) + .collect(), + None => self.ui.chat.recent_lines(new_chat), + }; for event in diff(before, &now, &lines) { self.events.push(self.ticks, event); } diff --git a/crates/horizon-client/src/game/explosion.rs b/crates/horizon-client/src/game/explosion.rs index 4ed2772c7..c6df8d9e2 100644 --- a/crates/horizon-client/src/game/explosion.rs +++ b/crates/horizon-client/src/game/explosion.rs @@ -196,7 +196,7 @@ impl Game<'_> { break; } let state = self.world.block(pos[0], pos[1], pos[2]); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); let fluid = if f.fluid != Fluid::None { 100.0f32 } else { @@ -206,7 +206,7 @@ impl Game<'_> { Some((at, resistance)) if at == pos => { power -= (resistance + 0.3) * 0.3; } - _ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => { + _ if !self.res.facts().is_air(state) || f.fluid != Fluid::None => { power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3; } _ => {} @@ -450,11 +450,11 @@ impl Game<'_> { if self.world.random.next_int_bound(3).unwrap_or(1) == 0 && self .res - .facts + .facts() .is_air(self.world.block(pos[0], pos[1], pos[2])) && self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .solid_render { @@ -475,7 +475,7 @@ impl Game<'_> { } else { targets.len() }; - let (world, facts) = (&self.world, &self.res.facts); + let (world, facts) = (&self.world, self.res.facts()); self.particles.explosion(center, radius, block_count, &|b| { facts.is_air(world.block(b[0], b[1], b[2])) }); @@ -490,10 +490,10 @@ impl Game<'_> { stacks: &mut Vec<([i32; 3], ItemStack)>, ) -> Result<()> { let state = self.world.block(pos[0], pos[1], pos[2]); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { return Ok(()); } - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let is_tnt = &*name == "minecraft:tnt"; // Block.onExplosionHit: the drops copy from the block entity, which // then spills its contents as the block turns to air. @@ -510,7 +510,7 @@ impl Game<'_> { // tables' survives_explosion and explosion_decay draw from their // random sequence. let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius); - let drops = self.res.items.block_drops_exploded( + let drops = self.res.items().block_drops_exploded( self.pack.assets.registry, state, None, diff --git a/crates/horizon-client/src/game/extras.rs b/crates/horizon-client/src/game/extras.rs index 712796a81..c16c54447 100644 --- a/crates/horizon-client/src/game/extras.rs +++ b/crates/horizon-client/src/game/extras.rs @@ -188,7 +188,7 @@ impl Game<'_> { let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2)); self.extras.minimap.update( &self.world, - &self.res.facts, + self.res.facts(), (bx >> 4, bz >> 4), radius, layer, @@ -197,10 +197,10 @@ impl Game<'_> { if !self.extras.minimap.compose(view) { return; } - let Some(rect) = self.atlas.sprites.get(MINIMAP_SPRITE).copied() else { + let Some(rect) = self.gui.atlas.sprites.get(MINIMAP_SPRITE).copied() else { return; }; - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -246,7 +246,7 @@ impl Game<'_> { let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size)); let visible = |corner| !(self.debug && corner == Corner::TopLeft); let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height()); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; if let Some(view) = self.minimap_view() && visible(map_corner) && !self.extras.minimap.image.is_empty() @@ -290,7 +290,7 @@ impl Game<'_> { use_: self.extras.mouse[1], cps, }; - extras_hud::draw_keystrokes(batch, &self.atlas, &mut corners, keys_corner, &k); + extras_hud::draw_keystrokes(batch, &self.gui.atlas, &mut corners, keys_corner, &k); } if mod_panels { self.draw_mod_panels(batch, &mut corners); diff --git a/crates/horizon-client/src/game/falling_damage.rs b/crates/horizon-client/src/game/falling_damage.rs index f10a3b738..8eec28d1d 100644 --- a/crates/horizon-client/src/game/falling_damage.rs +++ b/crates/horizon-client/src/game/falling_damage.rs @@ -6,7 +6,7 @@ use horizon_world::level::LevelEvent; impl Game<'_> { pub(super) fn finish_falling_block(&mut self, mut block: FallingBlock, pos: [i32; 3]) { - let anvil = self.res.facts.get(block.state).name.ends_with("anvil"); + let anvil = self.res.facts().get(block.state).name.ends_with("anvil"); if let Some(impact) = block.damage.impact(block.fall_distance) { if impact.amount > 0.0 { falling_block::hurt_mobs(&mut self.mobs, block.position, impact.amount); @@ -80,7 +80,7 @@ impl Game<'_> { && block.drop_item && self.ui.rules.bool("entity_drops") { - let item = self.res.facts.get(block.state).item.clone(); + let item = self.res.facts().get(block.state).item.clone(); if &*item != "minecraft:air" { self.pop_resource( pos, diff --git a/crates/horizon-client/src/game/fangs.rs b/crates/horizon-client/src/game/fangs.rs index dd2b9bde6..0939f6490 100644 --- a/crates/horizon-client/src/game/fangs.rs +++ b/crates/horizon-client/src/game/fangs.rs @@ -108,6 +108,7 @@ impl Game<'_> { return; }; let Some(r) = self + .gui .atlas .sprites .get("entity/illager/evoker_fangs") diff --git a/crates/horizon-client/src/game/fishing.rs b/crates/horizon-client/src/game/fishing.rs index 8a63f2cfe..94067e7f9 100644 --- a/crates/horizon-client/src/game/fishing.rs +++ b/crates/horizon-client/src/game/fishing.rs @@ -226,14 +226,18 @@ impl Game<'_> { fn biome_name_at(&self, p: Vec3) -> Option { let (x, y, z) = (p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); let c = self.world.chunks.get(&(x >> 4, z >> 4))?; - Some(self.res.biomes.list[c.biome(x, y, z) as usize].name.clone()) + Some( + self.res.biomes().list[c.biome(x, y, z) as usize] + .name + .clone(), + ) } fn water_height(&self, x: i32, y: i32, z: i32) -> Option<(f32, bool)> { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if f.fluid != Fluid::Water { return None; } - let above = self.res.facts.get(self.world.block(x, y + 1, z)); + let above = self.res.facts().get(self.world.block(x, y + 1, z)); let h = if above.fluid == Fluid::Water { 1.0 } else { @@ -243,7 +247,7 @@ impl Game<'_> { } /// getOpenWaterTypeForBlock: 0 above water, 1 inside water, 2 invalid. fn open_water_type(&self, x: i32, y: i32, z: i32) -> u8 { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if self.world.is_air(self.world.block(x, y, z)) || &*f.name == "minecraft:lily_pad" { return 0; } @@ -390,7 +394,7 @@ impl Game<'_> { (fish[1] - 1.0).floor() as i32, fish[2].floor() as i32, ); - &*self.res.facts.get(state).name == "minecraft:water" + &*self.res.facts().get(state).name == "minecraft:water" } /// `ServerLevel.sendParticles` of a simple particle. fn send_particles( @@ -565,6 +569,7 @@ impl Game<'_> { return; }; let Some(r) = self + .gui .atlas .sprites .get("entity/fishing/fishing_hook") diff --git a/crates/horizon-client/src/game/fov.rs b/crates/horizon-client/src/game/fov.rs index 64047b4f7..37796c8c3 100644 --- a/crates/horizon-client/src/game/fov.rs +++ b/crates/horizon-client/src/game/fov.rs @@ -75,7 +75,7 @@ impl Game<'_> { } /// The fluid at the camera, as `Camera.getFluidInCamera` reports it. fn camera_fluid(&self, camera: [f64; 3]) -> CameraFluid { - match fog_type(&self.world, &self.res.facts, camera, self.forward()) { + match fog_type(&self.world, self.res.facts(), camera, self.forward()) { FogType::Water => CameraFluid::Water, FogType::Lava => CameraFluid::Lava, FogType::PowderSnow => CameraFluid::PowderSnow, @@ -177,6 +177,6 @@ impl Game<'_> { } let draws = hud_overlays::spyglass(batch.width as i32, batch.height as i32, self.scope_scale); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/frames.rs b/crates/horizon-client/src/game/frames.rs index 2977ad483..7f5e6c26a 100644 --- a/crates/horizon-client/src/game/frames.rs +++ b/crates/horizon-client/src/game/frames.rs @@ -110,7 +110,7 @@ impl Game<'_> { return false; } let s = f.step(); - let behind = self.res.facts.get(self.world.block( + let behind = self.res.facts().get(self.world.block( f.pos[0] - s[0], f.pos[1] - s[1], f.pos[2] - s[2], @@ -282,8 +282,15 @@ impl Game<'_> { } /// BlockAttachedEntity.tick for frames. pub(super) fn tick_item_frames(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); let mut i = 0; while i < self.item_frames.len() { + let at = center(&self.item_frames[i]); + if !ticking(at[0].floor() as i32, at[2].floor() as i32) { + i += 1; + continue; + } self.item_frames[i].check_interval += 1; if self.item_frames[i].check_interval >= 100 { self.item_frames[i].check_interval = 0; @@ -301,7 +308,7 @@ impl Game<'_> { } /// ItemFrameRenderer: the frame model, then the item half size on its face. pub(super) fn frame_geometry(&mut self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.atlas.sprites; + let sprites = &self.gui.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%. diff --git a/crates/horizon-client/src/game/gamemode_switcher.rs b/crates/horizon-client/src/game/gamemode_switcher.rs index 5f73080f4..db057ad25 100644 --- a/crates/horizon-client/src/game/gamemode_switcher.rs +++ b/crates/horizon-client/src/game/gamemode_switcher.rs @@ -39,7 +39,7 @@ impl Game<'_> { }; switcher.hover(w, h, (self.cursor.0 as i32, self.cursor.1 as i32)); let selected = switcher.selected; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/container/gamemode_switcher", @@ -62,14 +62,14 @@ impl Game<'_> { for (index, mode) in MODES.into_iter().enumerate() { let (x, y) = slot_origin(w, h, index); batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/gamemode_switcher/slot", x as f32, y as f32, ); if mode == selected { batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/gamemode_switcher/selection", x as f32, y as f32, diff --git a/crates/horizon-client/src/game/golems.rs b/crates/horizon-client/src/game/golems.rs index 2bfeda70d..da204eee6 100644 --- a/crates/horizon-client/src/game/golems.rs +++ b/crates/horizon-client/src/game/golems.rs @@ -8,7 +8,7 @@ use horizon_client::Result; impl Game<'_> { fn golem_block(&self, p: [i32; 3]) -> &str { let state = self.world.block(p[0], p[1], p[2]); - &self.res.facts.get(state).name + &self.res.facts().get(state).name } fn is_golem_head(&self, p: [i32; 3]) -> bool { matches!( @@ -33,7 +33,7 @@ impl Game<'_> { for (ax, az) in [(1, 0), (0, 1)] { let side = |s: i32, row: i32| [head[0] + ax * s, head[1] - row, head[2] + az * s]; let arms = (-1..=1).all(|s| self.golem_block(side(s, 1)) == "minecraft:iron_block"); - let air = |p: [i32; 3]| self.res.facts.is_air(self.world.block(p[0], p[1], p[2])); + let air = |p: [i32; 3]| self.res.facts().is_air(self.world.block(p[0], p[1], p[2])); if arms && self.golem_block(side(0, 2)) == "minecraft:iron_block" && [-1, 1].iter().all(|&s| air(side(s, 0)) && air(side(s, 2))) @@ -58,7 +58,7 @@ impl Game<'_> { let below = [head[0], head[1] - 1, head[2]]; let name = self.golem_block(below); self.res - .items + .items() .block_tags .get("minecraft:copper") .is_some_and(|t| t.contains(name)) @@ -88,7 +88,7 @@ impl Game<'_> { /// `EntityType.create(level, TRIGGERED)` and `snapTo`: a built golem or /// wither has no spawn finalization and draws nothing from the level. pub(super) fn create_triggered(&mut self, kind: &str, at: [f64; 3], yaw: f32) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; self.next_entity += 1; let mut mob = horizon_client::mobs::Mob::new( self.next_entity, @@ -181,9 +181,9 @@ impl Game<'_> { }); if let Some(chest) = chest { self.with_level(|b, level, ticks| b.set_block(level, ticks, pos, chest, 2)); - if let Some(entity) = - horizon_client::containers::BlockEntity::for_block(&self.res.facts.get(chest).name) - { + if let Some(entity) = horizon_client::containers::BlockEntity::for_block( + &self.res.facts().get(chest).name, + ) { self.world .block_entities .insert((below[0], below[1], below[2]), entity); diff --git a/crates/horizon-client/src/game/growth.rs b/crates/horizon-client/src/game/growth.rs index 18591b0fe..a6e062e24 100644 --- a/crates/horizon-client/src/game/growth.rs +++ b/crates/horizon-client/src/game/growth.rs @@ -10,7 +10,7 @@ impl Game<'_> { /// Load the configured/placed feature registry used by saplings, fungi /// and bone meal (once per process; shares the generator's bundle). pub(super) fn install_live_features(&self) { - if self.res.behaviours.live_features().is_some() { + if self.res.behaviours().live_features().is_some() { return; } let dir = self.options.resources.join("worldgen"); @@ -20,7 +20,7 @@ impl Game<'_> { .and_then(|data| LiveFeatures::new(&data).map_err(|e| e.to_string())); match features { Ok(Some(features)) => { - self.res.behaviours.set_live_features(Arc::new(features)); + self.res.behaviours().set_live_features(Arc::new(features)); log::info!("Horizon: live features ready in {:?}", started.elapsed()); } Ok(None) => { diff --git a/crates/horizon-client/src/game/hand.rs b/crates/horizon-client/src/game/hand.rs index 19e66174b..6e11febbd 100644 --- a/crates/horizon-client/src/game/hand.rs +++ b/crates/horizon-client/src/game/hand.rs @@ -39,7 +39,7 @@ impl Game<'_> { }); self.clicks.destroying = destroying; self.attack_clicks = 0; - self.stop_remote_mining(); + self.request_remote_mining_stop(); self.mining = None; } /// `LivingEntity.swing` with `getModifiedSwingDuration`. @@ -90,7 +90,7 @@ impl Game<'_> { let (pos, first) = (d.pos, (d.ticks as u32 - 1).is_multiple_of(4)); let state = self.world.block(pos[0], pos[1], pos[2]); if first { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); self.audio.play( &sounds.hit, Some(pos.map(|v| f64::from(v) + 0.5)), @@ -117,17 +117,17 @@ impl Game<'_> { /// `BlockBehaviour.getDestroyProgress` with `Player.getDestroySpeed`. pub(super) fn destroy_progress(&self, pos: [i32; 3]) -> f32 { let state = self.world.block(pos[0], pos[1], pos[2]); - let facts = self.res.facts.get(state); + let facts = self.res.facts().get(state); if facts.hardness == -1.0 { return 0.0; } let held = self.held(); - let mut speed = self.res.items.mining_speed(held, &facts.name); + let mut speed = self.res.items().mining_speed(held, &facts.name); speed = self.modify_destroy_speed(speed); if let Some(eye) = self.eye_position() && self .res - .facts + .facts() .get(self.world.block( eye[0].floor() as i32, eye[1].floor() as i32, @@ -141,7 +141,7 @@ impl Game<'_> { if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { speed /= 5.0; } - let harvest = !facts.requires_tool || self.res.items.correct_for_drops(held, &facts.name); + let harvest = !facts.requires_tool || self.res.items().correct_for_drops(held, &facts.name); speed / facts.hardness / if harvest { 30.0 } else { 100.0 } } /// Whether an attack would hit an entity rather than the block behind @@ -287,7 +287,7 @@ impl Game<'_> { horizon_client::attack_strength::BASE_ATTACK_SPEED + self .held() - .and_then(|h| self.res.items.get(&h.item)) + .and_then(|h| self.res.items().get(&h.item)) .map_or(0.0, |i| f64::from(i.attack_speed)) } /// `evaluateWhichHandsToRender`: which of the main and off hand show. @@ -351,7 +351,7 @@ impl HandWorld for GameHands<'_, '_> { } fn is_air(&mut self, pos: [i32; 3]) -> bool { let state = self.game.world.block(pos[0], pos[1], pos[2]); - self.game.res.facts.get(state).name.ends_with("air") + self.game.res.facts().get(state).name.ends_with("air") } fn creative(&self) -> bool { self.game.creative diff --git a/crates/horizon-client/src/game/initial_spawn.rs b/crates/horizon-client/src/game/initial_spawn.rs index 5fcd90517..3f7a071bb 100644 --- a/crates/horizon-client/src/game/initial_spawn.rs +++ b/crates/horizon-client/src/game/initial_spawn.rs @@ -83,7 +83,7 @@ impl Game<'_> { horizon_client::flatgen::FlatTerrain::from_settings( &s, self.pack.assets.registry, - &self.res.biomes, + self.res.biomes(), ) }) { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index b2c0a2e7f..2b8ffb166 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -10,7 +10,7 @@ //! player joins as a network player, and the server side of a network player //! does not do everything single player does yet. use super::{ - Game, Options, PackResources, Resources, + Game, Options, PackResources, Resources, UiResources, lan::{LanSettings, Owner}, }; use horizon_client::{ @@ -201,6 +201,7 @@ impl Game<'_> { options.server = None; options.world = None; options.dev_mods.clear(); + self.join_world_rest()?; let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone()); let flags = Arc::new(Flags::default()); flags @@ -316,6 +317,7 @@ impl Game<'_> { // The owner is an operator when the world allows commands // (`IntegratedPlayerList`, `MinecraftServer.getProfilePermissions`). host.hub.ops.insert(owner, if commands { 4 } else { 0 }); + host.hub.singleplayer_owner = Some(owner); host.owner = Some(Owner { uuid: owner, saved: Some(saved), @@ -335,11 +337,11 @@ impl Game<'_> { self.run_tasks(); if flags.paused.load(Ordering::Relaxed) { // Only the connections run. - self.tick_server(true)?; + self.tick_server_timed(true)?; } else { self.follow_distances(&flags); let started = Instant::now(); - self.tick_server(false)?; + self.tick_server_timed(false)?; self.debug_charts.log_tick(started, started.elapsed()); flags.smoothed_tick_ms.store( self.debug_charts.smoothed_tick_ms.to_bits(), @@ -409,6 +411,60 @@ impl Game<'_> { pub(super) fn serving(&self) -> bool { self.serving.is_some() } + /// The window's agent runs a command as single player's console does + /// (`as_console`, as without a server thread): as the world's owner, in + /// the owner's level, at the owner permission level. The feedback goes to + /// the owner's chat and is returned. + pub(super) fn owner_console_command(&mut self, command: &str) -> Vec { + let Some(owner) = self.serving.as_ref().map(|s| s.owner) else { + return Vec::new(); + }; + let Some(mut host) = self.lan.take() else { + return Vec::new(); + }; + let mut out = Vec::new(); + if let Some(g) = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed) { + let conn = g.conn; + // Commands.performCommand runs in the player's level. + let (back, theirs) = (self.dim, super::Dim::from_id(&g.dimension)); + let entered = theirs == back || self.enter_level(Some(&mut host), theirs).is_ok(); + if entered { + let command = command.trim_start_matches('/').to_owned(); + let lines = self.as_guest(&mut host, conn, |g| { + g.as_console(|g| { + g.chat_capture = Some(Vec::new()); + g.run_command(&command); + g.chat_capture.take().unwrap_or_default() + }) + }); + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(&mut host); + for line in lines.unwrap_or_default() { + out.push(line.plain()); + host.hub.send_to( + conn, + &horizon_protocol::packets::play::Clientbound::SystemChat( + horizon_protocol::packets::play::SystemChat { + content: horizon_client::lan::data::component_nbt( + &line.component(), + ), + overlay: false, + }, + ), + ); + } + self.send_admin_feedback(&mut host, Some(conn)); + } + if theirs != back + && let Err(e) = self.enter_level(Some(&mut host), back) + { + log::error!("could not reopen {}: {e}", back.id()); + } + } + self.lan = Some(host); + out + } + /// The window's requests, between two ticks. fn run_tasks(&mut self) { let tasks: Vec = match &self.serving { @@ -594,7 +650,14 @@ fn serve( ) -> Result<()> { // It draws nothing: only the font, which books and chat measure with. let atlas = HudAtlas::fonts(&options.resources)?; + let gui = UiResources { + atlas, + panorama: Arc::new(horizon_client::gfx::panorama::Faces { + size: 1, + pixels: [0u8; 4].repeat(6), + }), + }; let audio = Audio::silent(&options.resources); - let mut server = Game::new(res, pack, atlas, options, settings, audio)?; + let mut server = Game::new(res, pack, gui, options, settings, audio)?; server.run_integrated(launch, flags, tasks, ready) } diff --git a/crates/horizon-client/src/game/item_draw.rs b/crates/horizon-client/src/game/item_draw.rs index b05f4fbf5..8e7176a70 100644 --- a/crates/horizon-client/src/game/item_draw.rs +++ b/crates/horizon-client/src/game/item_draw.rs @@ -176,7 +176,7 @@ impl Game<'_> { } pub(super) fn item_host(&self) -> Host<'_> { Host { - banners: &self.res.stations.banners, + banners: &self.res.stations().banners, } } /// The client level as item models read it. @@ -255,7 +255,7 @@ impl Game<'_> { item_render::gui::draw( &state, &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), batch, x, @@ -279,7 +279,7 @@ impl Game<'_> { }; state.submit( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), pose, &mut sink, @@ -300,7 +300,7 @@ impl Game<'_> { }; state.submit( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, &self.item_host(), pose, &mut sink, diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index ba7d2b786..c3ed75ebb 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -51,7 +51,7 @@ impl Game<'_> { pub(super) fn use_jukebox(&mut self, pos: [i32; 3], held: Option<&ItemStack>) -> bool { if &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name != "minecraft:jukebox" @@ -65,7 +65,7 @@ impl Game<'_> { let Some(stack) = held else { return false }; let Some(song) = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.jukebox_song.clone()) else { @@ -95,7 +95,7 @@ impl Game<'_> { /// Level event 1010: the song from the jukebox, and the "Now Playing" overlay. fn start_song(&mut self, pos: [i32; 3], song: &str) { self.stop_song(pos); - let Some(s) = self.res.items.songs.get(song).cloned() else { + let Some(s) = self.res.items().songs.get(song).cloned() else { return; }; // LevelRenderer.playJukeboxSong: SimpleSoundInstance.forJukeboxSong. @@ -144,7 +144,7 @@ impl Game<'_> { 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()?; + let song = self.res.items().get(&r.item)?.jukebox_song.clone()?; Some((song, j.ticks)) }), _ => None, @@ -153,7 +153,7 @@ impl Game<'_> { return; }; let pos = [key.0, key.1, key.2]; - let Some(s) = self.res.items.songs.get(&song).cloned() else { + let Some(s) = self.res.items().songs.get(&song).cloned() else { return; }; if s.finished(ticks) { diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index d35bf787a..57c44cb07 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -2,7 +2,7 @@ //! server threads and the play-state hub, feeds it the world's entities each //! tick and turns what the guests do into gameplay. A world that is not open //! costs one `Option` check per tick. -use super::Game; +use super::{Game, shield::OFFHAND_SLOT}; use horizon_client::{ Result, items::ItemStack, @@ -42,6 +42,8 @@ pub(super) struct LanHost { pub hub: Hub, pub settings: LanSettings, pub host_entity: i32, + /// The host's swings the guests were told of (`Game::swings_started`). + pub host_swings: u32, pub host_uuid: u128, /// The host's profile name (the account's, or the offline name). pub host_name: String, @@ -61,6 +63,9 @@ pub(super) struct LanHost { /// are dead, whose respawn replaces their waypoint. pub waypoints: lan::waypoints::Waypoints, pub waypoint_dead: std::collections::HashSet, + /// Guests' commands waiting for the hub to be back in `self.lan`, where + /// a command can reach every player (game/lan_actions.rs). + pub commands: Vec, } /// The player who owns an integrated server's world: a guest whose state is @@ -395,6 +400,10 @@ impl Game<'_> { [&m.extra.head, &m.extra.chest, &m.extra.legs, &m.extra.feet] .map(|s| s.as_deref()) }), + // The host draws this guest's arm swinging. + "model_swinging": h.models.get(&g.conn).map(|m| m.ai.swinging), + // For how many ticks the host draws this guest using an item. + "model_using": h.models.get(&g.conn).map(|m| m.extra.using_item), })).collect::>(), }), _ => json!({ "open": false }), @@ -467,7 +476,7 @@ impl Game<'_> { .clone()?; let biome_names: Vec = self .res - .biomes + .biomes() .list .iter() .map(|b| b.name.clone()) @@ -480,7 +489,7 @@ impl Game<'_> { .unwrap_or_default(); let mut encoder = ChunkEncoder::new( self.res - .facts + .facts() .states .iter() .map(|s| (s.name.clone(), s.fluid_level > 0 || s.waterlogged)), @@ -509,6 +518,7 @@ impl Game<'_> { hub, settings: LanSettings { port, ..settings }, host_entity, + host_swings: self.swings_started, host_uuid, host_name: self.options.player_name(), models: HashMap::new(), @@ -520,6 +530,7 @@ impl Game<'_> { owner: None, waypoints: Default::default(), waypoint_dead: Default::default(), + commands: Vec::new(), }); self.audio.capture = Some(Vec::new()); Ok(()) @@ -722,6 +733,8 @@ impl Game<'_> { sprinting: p.sprinting, equipment, health: p.health.health(), + attributes: horizon_client::lan::attributes::syncable(&p.attributes), + living_flags: living_flags(self.using), }) } @@ -732,6 +745,7 @@ impl Game<'_> { let kind = m.kind.id.as_str(); let meta = mob_meta(m, hub); let equipment = mob_equipment(m, hub); + let attributes = self.mob_attributes(m); let (yaw, pitch) = (m.yaw, m.head_pitch); out.push(EntityState { id: m.id as i32, @@ -746,6 +760,7 @@ impl Game<'_> { data: 0, meta, equipment, + attributes, precise: false, }); } @@ -764,6 +779,7 @@ impl Game<'_> { data: 0, meta: vec![(8, serializer::ITEM_STACK, Value::Item(stack))], equipment: Vec::new(), + attributes: Vec::new(), precise: false, }); } @@ -782,6 +798,7 @@ impl Game<'_> { // ExperienceOrb.DATA_VALUE. meta: vec![(8, serializer::INT, Value::Int(o.value as i32))], equipment: Vec::new(), + attributes: Vec::new(), precise: false, }); } @@ -796,7 +813,11 @@ 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. + // The host's own commands' (and command blocks') players moving + // to another level, and their broadcastToAdmins lines. + if !self.level_teleports.is_empty() { + self.run_level_teleports(&mut host); + } if !self.admin_feedback.is_empty() { self.send_admin_feedback(&mut host, None); } @@ -814,6 +835,7 @@ impl Game<'_> { }; let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); let events = { + let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state.as_ref(), @@ -822,11 +844,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -918,12 +936,18 @@ impl Game<'_> { } HostEvent::Packet(conn, packet) => { self.lan_guest_packet(&mut host, conn, *packet); + if !host.commands.is_empty() { + self.lan = Some(host); + self.run_guest_commands(); + host = self.lan.take().expect("the hub is back after the commands"); + } } } } } self.lan_flush_effects(&mut host); self.tick_guests(&mut host); + self.lan_living_flags(&mut host); self.tick_server_travel(&mut host); self.lan_swings(&mut host); self.lan_update_streaming(&host); @@ -991,6 +1015,7 @@ impl Game<'_> { } else { entities }; + let clock_rate = self.network_clock_rate(); let mut ctx = TickCtx { world: &mut self.world, host: state, @@ -999,7 +1024,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: self.ui.clock.rate, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -1068,8 +1093,30 @@ impl Game<'_> { .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); + // LivingEntity.hurtServer: a hurt that restarted the hurt time. + if m.hurt_time > old.map_or(0, |o| o.0) + && !dead + && let Some((source, _)) = m.last_damage + { + use horizon_client::mobs::{DamageKind as K, Who}; + let player = source.attacker == Some(Who::Player); + let kind = super::creatures::damage_type(source.kind, player); + // The player a mob sees is the guest acting, else the host. + let cause = source.attacker.map(|who| match who { + Who::Player => host + .mob_players + .get(&m.id) + .and_then(|conn| host.hub.guest(*conn)) + .map_or(host.host_entity, |g| g.entity_id), + Who::Mob(id) => id as i32, + }); + // A projectile is the direct entity of its hit: not tracked here. + let melee = matches!( + source.kind, + K::PlayerAttack | K::MaceSmash | K::MobAttack | K::Sting | K::SonicBoom + ); + let direct = cause.filter(|_| melee); + host.hub.damage_event(m.id as i32, kind, cause, direct, at); } if dead && !old.is_some_and(|o| o.1) { host.hub.entity_event(m.id as i32, 3, at); @@ -1100,7 +1147,7 @@ impl Game<'_> { /// The guests' models, for the host to see them. fn lan_update_models(&mut self, host: &mut LanHost) { - let Some(kind) = self.res.player_type.clone() else { + let Some(kind) = self.res.player_type().clone() else { return; }; host.models @@ -1158,6 +1205,14 @@ impl Game<'_> { .each_ref() .map(|s| s.as_ref().map(|s| s.item.clone())); m.extra.crouching = g.sneaking; + // LivingEntity.updateSwingTime: the arm swing lan_swings started. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); + // LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): the + // item in use and its hand (the arm poses of a bow, a shield...). + let using = host.play.get(&g.conn).and_then(|p| p.using()); + m.extra.using_item = using.map_or(0, |(_, ticks)| ticks as i32 + 1); + m.extra.using_off_hand = using.is_some_and(|(slot, _)| slot == OFFHAND_SLOT); } } @@ -1171,7 +1226,7 @@ impl Game<'_> { let Some(host) = &self.lan else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for m in host.models.values() { let entity_start = out.len(); @@ -1187,7 +1242,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &self.worn_armor_layers(m), out, ); @@ -1226,3 +1281,9 @@ impl Game<'_> { } } } + +/// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` for an item in use: 1, and 2 when +/// it is the off hand's. +pub(super) fn living_flags(using: Option<(usize, u32)>) -> i8 { + using.map_or(0, |(slot, _)| if slot == OFFHAND_SLOT { 3 } else { 1 }) +} diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index ced435d8d..64ee29776 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -10,6 +10,7 @@ use horizon_client::{ command::vanilla, containers::BlockEntity, entities::Experience, + first_person::{Hand, SwingAnimation}, items::ItemStack, lan::{ guest::SPECTATOR, @@ -43,8 +44,9 @@ pub(super) struct GuestPlay { /// its progress since `dig_start` is complete (ServerPlayerGameMode.hasDelayedDestroy). delayed: Option<([i32; 3], u64)>, last_progress: i32, - /// Hand movements the client announced and the host animated. - swung: bool, + /// Swings the guest's actions started this tick, for the players around + /// (`LivingEntity.swing` sends ClientboundSwingAnimationPacket). + swings: u32, /// The trading screen the guest has open. pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. @@ -58,6 +60,78 @@ pub(super) struct GuestPlay { pub(super) portal: horizon_client::nether_portal::PortalState, /// `Player.takeXpDelay`: ticks until the next orb can be taken. xp_delay: u32, + /// What last killed the guest outright (`/kill`): the death message's key. + death_cause: Option, +} + +/// A guest's command waiting for the hub (`LanHost::commands`). +pub(super) struct GuestCommand { + conn: u32, + command: String, + permission: u8, + /// An integrated server's: no admin feedback or level teleports (yet). + integrated: bool, +} + +/// The game's own state while a guest's is swapped in (`enter_guest`), and +/// the guest's records that live outside `Guest`. +pub(super) struct GuestSwap { + conn: u32, + i: usize, + play: GuestPlay, + player: Option, + /// The guest's eye height and the game's. + eye: (f32, f32), + yaw: f32, + pitch: f32, + selected: usize, + mode: horizon_client::command::args::GameMode, + creative: bool, + xp: Experience, + host_keys: std::collections::HashSet, + screen: Screen, + host_sign: Option, + host_book: Option, + host_command_block: Option, + host_mount_menu: super::mount_menu::MountMenu, + craft_size: usize, + craft_grid: Vec>, + container: Option<(i32, i32, i32)>, + mining: Option, + destroy_delay: u32, + using: Option<(usize, u32)>, + use_delay: u32, + attack_ticks: u32, + swing: horizon_client::first_person::SwingState, + left: bool, + right: bool, + riding: Option, + host_station: Option, + sleeping: Option<[i32; 3]>, + sleep_timer: u32, + spawn: Option, + respawn: ( + Option, + Option<[f64; 3]>, + ), + message: Option<(String, std::time::Instant)>, + host_ender: Option<(i32, i32, i32)>, + adv_loaded: bool, + last_inventory: u64, + death_cause: Option, + /// The guest whose turn this one nests in, if any. + acting: (Option, Option, Option), + /// The packets queued for that guest. + packets: Vec, + /// The host's count of swings started, kept while the guest acts. + swings: u32, +} + +impl GuestPlay { + /// The item in use: its slot and for how many ticks. + pub(super) fn using(&self) -> Option<(usize, u32)> { + self.using + } } struct ItemRules<'a>(&'a horizon_client::items::Items); @@ -95,6 +169,24 @@ impl Game<'_> { conn: u32, f: impl FnOnce(&mut Self) -> R, ) -> Option { + let swap = self.enter_guest(host, conn)?; + let result = f(self); + self.leave_guest(host, swap); + Some(result) + } + + /// The first half of `as_guest`: the guest's state in place of the + /// game's, which the returned swap keeps until `leave_guest`. Between the + /// two the host may go back into `self.lan`, so that what the guest does + /// can reach the other players (their commands, `for_player`), and a + /// guest's turn can nest in another's: the acting guest and the packets + /// queued for them are kept and restored too. + pub(super) fn enter_guest(&mut self, host: &mut LanHost, conn: u32) -> Option { + // The guest whose turn it is is in place already (their record holds + // the game's state until their turn ends). + if self.lan_acting == Some(conn) { + return None; + } let i = host.hub.guests.iter().position(|g| g.conn == conn)?; if host.hub.guests[i].motion.is_none() { let p = Vec3::new( @@ -198,17 +290,115 @@ impl Game<'_> { std::mem::swap(&mut self.stats, &mut play.stats); let adv_loaded = std::mem::replace(&mut self.adv.loaded, true); let last_inventory = std::mem::replace(&mut self.adv.last_inventory, play.last_inventory); - self.lan_acting = Some(conn); - self.lan_acting_name = Some(g.name.clone()); - self.lan_acting_uuid = Some(g.uuid); + let death_cause = std::mem::replace(&mut self.ui.death_cause, play.death_cause.take()); + let acting = ( + self.lan_acting.replace(conn), + self.lan_acting_name.replace(g.name.clone()), + self.lan_acting_uuid.replace(g.uuid), + ); + let packets = std::mem::take(&mut self.guest_packets); + let swings = self.swings_started; + Some(GuestSwap { + conn, + i, + play, + player, + eye, + yaw, + pitch, + selected, + mode, + creative, + xp, + host_keys, + screen, + host_sign, + host_book, + host_command_block, + host_mount_menu, + craft_size, + craft_grid, + container, + mining, + destroy_delay, + using, + use_delay, + attack_ticks, + swing, + left, + right, + riding, + host_station, + sleeping, + sleep_timer, + spawn, + respawn, + message, + host_ender, + adv_loaded, + last_inventory, + death_cause, + acting, + packets, + swings, + }) + } - let result = f(self); - for packet in std::mem::take(&mut self.guest_packets) { + /// The second half of `as_guest`: the guest's state back into their + /// record, the game's back in place, and what the turn changed sent. + pub(super) fn leave_guest(&mut self, host: &mut LanHost, swap: GuestSwap) { + let GuestSwap { + conn, + i, + mut play, + mut player, + eye, + yaw, + pitch, + selected, + mode, + creative, + xp, + host_keys, + screen, + host_sign, + host_book, + host_command_block, + host_mount_menu, + craft_size, + craft_grid, + container, + mining, + destroy_delay, + using, + use_delay, + attack_ticks, + swing, + left, + right, + riding, + host_station, + sleeping, + sleep_timer, + spawn, + respawn, + message, + host_ender, + adv_loaded, + last_inventory, + death_cause, + acting, + packets, + swings, + } = swap; + // The guest's swings are theirs: the host's own count stays the host's. + play.swings += self.swings_started.wrapping_sub(swings); + self.swings_started = swings; + for packet in std::mem::replace(&mut self.guest_packets, packets) { host.hub.send_to(conn, &packet); } - self.lan_acting = None; - self.lan_acting_name = None; - self.lan_acting_uuid = None; + (self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting; + play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause); // An ender chest the guest opened: the menu shows their inventory // itself (lan_open_container), not a stand-in block entity. self.close_ender_chest(); @@ -281,6 +471,9 @@ impl Game<'_> { std::mem::swap(&mut self.armor, &mut g.armor); std::mem::swap(&mut self.offhand, &mut g.offhand); std::mem::swap(&mut self.carried, &mut g.carried); + // A teleport with a rotation (commands) turns the guest. + let turned = [self.yaw, self.pitch] != [g.yaw, g.pitch]; + [g.yaw, g.pitch] = [self.yaw, self.pitch]; self.yaw = yaw; self.pitch = pitch; self.eye = eye.1; @@ -294,7 +487,7 @@ impl Game<'_> { m.sprinting = false; let moved: f64 = (0..3).map(|k| (at[k] - g.position[k]).powi(2)).sum(); g.motion = Some(Box::new(m)); - if moved > 0.0001 { + if moved > 0.0001 || turned { host.hub.teleport(i, Some(at)); } } @@ -331,7 +524,6 @@ impl Game<'_> { if opened_table { self.lan_open_crafting(host, conn); } - Some(result) } /// `ServerLevel.players()` in turn: the host's own player, then each @@ -377,7 +569,7 @@ impl Game<'_> { fn lan_open_container(&mut self, host: &mut LanHost, conn: u32, pos: (i32, i32, i32)) -> bool { let name = &self .res - .facts + .facts() .get(self.world.block(pos.0, pos.1, pos.2)) .name; let (menu, title, slots) = if &**name == "minecraft:ender_chest" { @@ -395,6 +587,13 @@ impl Game<'_> { _ => ("minecraft:furnace", "container.furnace"), }; (menu, title, Slots::Block(pos)) + } else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) { + // BrewingStandBlock.useWithoutItem: BrewingStandMenu. + ( + "minecraft:brewing_stand", + "container.brewing", + Slots::Block(pos), + ) } else if let Some((other, right)) = self.chest_partner(pos) { // ChestBlock.combine: the right half's slots come first. let halves = if right { @@ -542,6 +741,16 @@ impl Game<'_> { } } } + // ServerGamePacketListenerImpl.handlePunch: the main hand swings + // with the held item's attack animation (mining, attacking, a + // click on nothing), seen by the players around, and the attack + // strength starts again. + S::Punch(_) => { + self.as_guest(host, conn, |g| { + g.swing_hand(Hand::Main, SwingAnimation::DEFAULT); + g.reset_attack_strength(); + }); + } S::UseItemOn(p) => { host.hub.ack(conn, p.sequence); if spectator { @@ -557,11 +766,14 @@ impl Game<'_> { f64::from(p.pos[2]) + f64::from(p.cursor[2]), ], }; - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { g.forced_hit = Some(hit); + let swings = g.swings_started; let _ = g.use_item(); g.forced_hit = None; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); // The client predicted a result: correct it with what really is. for pos in [ p.pos, @@ -579,20 +791,26 @@ impl Game<'_> { } // handleUseItem: the client's rotation, then the item alone. What it // looked at a moment ago (a block, a mob) is UseItemOn's or Interact's. - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { (g.yaw, g.pitch) = (p.yaw, p.pitch); g.lan_item_only = true; + let swings = g.swings_started; let _ = g.use_item(); g.lan_item_only = false; + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } S::Attack(p) => self.guest_attack(host, conn, p.id), S::Interact(p) => { if let Some((position, eye)) = self.look_at_entity(host, gi, p.id) { let _ = (position, eye); - self.as_guest(host, conn, |g| { + let swung = self.as_guest(host, conn, |g| { + let swings = g.swings_started; let _ = g.use_item(); + g.swings_started != swings }); + self.lan_swing_back(host, conn, swung); } } S::SetCreativeModeSlot(p) => { @@ -606,7 +824,7 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} - S::ContainerClick(p) if self.lan_furnace_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; @@ -621,7 +839,7 @@ impl Game<'_> { } } S::ContainerClick(p) => { - let rules = ItemRules(&self.res.items); + let rules = ItemRules(self.res.items()); let drops = host.hub.container_click(conn, &p, &mut self.world, &rules); self.drop_guest_items(host, gi, drops); } @@ -750,7 +968,7 @@ impl Game<'_> { } S::PickItemFromBlock(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let item = self.res.facts.get(state).item.clone(); + let item = self.res.facts().get(state).item.clone(); let g = &mut host.hub.guests[gi]; if g.creative() && &*item != "minecraft:air" { let slot = g.selected; @@ -884,34 +1102,12 @@ impl Game<'_> { return; } // An integrated server runs every player's commands at their own - // permission level (`CommandSourceStack.permissions`). - if host.hub.config.integrated { - let Some(level) = host.hub.guest(conn).map(|g| g.permission) else { - return; - }; - let command = command.trim_start_matches('/').to_owned(); - let lines = self.as_guest(host, conn, |g| { - let console = std::mem::replace(&mut g.ui.registries.permission, level); - g.chat_capture = Some(Vec::new()); - g.run_command(&command); - g.ui.registries.permission = console; - g.chat_capture.take().unwrap_or_default() - }); - for line in lines.unwrap_or_default() { - host.hub.send_to( - conn, - &C::SystemChat(play::SystemChat { - content: horizon_client::lan::data::component_nbt(&line.component()), - overlay: false, - }), - ); - } - return; - } - // A LAN world follows its Allow Commands; a dedicated server leaves - // it to the ops list (the guest's permission level). + // permission level (`CommandSourceStack.permissions`); a LAN world + // follows its Allow Commands, and a dedicated server leaves it to + // the ops list (the guest's permission level). + let integrated = host.hub.config.integrated; let allowed = self.options.dedicated.is_some() || self.allow_commands(); - if !host.settings.guest_commands || !allowed { + if !integrated && (!host.settings.guest_commands || !allowed) { host.hub.send_to( conn, &C::SystemChat(play::SystemChat { @@ -921,34 +1117,62 @@ impl Game<'_> { ); return; } - let command = command.trim_start_matches('/').to_owned(); - // The guest's own level (Commands.performCommand with the player's source): an - // operator's on a dedicated server, never the host's. - let permission = host.hub.guest(conn).map_or(0, |g| g.permission); - let lines = self.as_guest(host, conn, |g| { - g.chat_capture = Some(Vec::new()); - let level = std::mem::replace(&mut g.ui.registries.permission, permission); - g.run_command(&command); - g.ui.registries.permission = level; - g.chat_capture - .take() - .unwrap_or_default() - .iter() - .map(|t| horizon_client::lan::data::component_nbt(&t.component())) - .collect::>() + // The guest's own level (Commands.performCommand with the player's + // source): an operator's on a dedicated server, never the host's. + let Some(permission) = host.hub.guest(conn).map(|g| g.permission) else { + return; + }; + host.commands.push(GuestCommand { + conn, + command: command.trim_start_matches('/').to_owned(), + permission, + integrated, }); - // 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, - &C::SystemChat(play::SystemChat { - content, - overlay: false, - }), - ); + } + + /// The guests' queued commands, run with the hub in `self.lan` so that + /// they reach the other players too (`/give Bob`, `/tp Bob`, `/kick`). + pub(super) fn run_guest_commands(&mut self) { + loop { + let Some(host) = self.lan.as_mut() else { + return; + }; + if host.commands.is_empty() { + return; + } + let c = host.commands.remove(0); + let mut host = self.lan.take().expect("checked above"); + let Some(swap) = self.enter_guest(&mut host, c.conn) else { + self.lan = Some(host); + continue; + }; + self.lan = Some(host); + self.chat_capture = Some(Vec::new()); + let level = std::mem::replace(&mut self.ui.registries.permission, c.permission); + self.run_command(&c.command); + self.ui.registries.permission = level; + let lines = self.chat_capture.take().unwrap_or_default(); + let mut host = self.lan.take().expect("a command puts the hub back"); + self.leave_guest(&mut host, swap); + host.hub.sync_all_effects(); + if !c.integrated { + // A teleport into another level happens before its feedback is sent. + self.run_level_teleports(&mut host); + } + for line in lines { + host.hub.send_to( + c.conn, + &C::SystemChat(play::SystemChat { + content: horizon_client::lan::data::component_nbt(&line.component()), + overlay: false, + }), + ); + } + if !c.integrated { + self.send_admin_feedback(&mut host, Some(c.conn)); + } + self.lan = Some(host); } - self.send_admin_feedback(host, Some(conn)); } /// The `broadcastToAdmins` lines a command queued (`source`: the guest @@ -1072,6 +1296,7 @@ impl Game<'_> { if let Some(play) = host.play.get_mut(&conn) { play.potions = Default::default(); } + let clock_rate = self.network_clock_rate(); let ctx = TickCtx { world: &mut self.world, host: None, @@ -1080,11 +1305,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), @@ -1149,6 +1370,7 @@ impl Game<'_> { self.as_guest(host, conn, |g| { g.count_tick_stats(sleeping); g.tick_advancements(); + g.update_player_attributes(); }); host.hub.flush_progress(conn); self.guest_dig_feedback(host, conn); @@ -1165,7 +1387,34 @@ impl Game<'_> { total: g.xp_total, } .death_reward(self.ui.rules.bool("keep_inventory") || g.game_mode == SPECTATOR); - let message = literal(&format!("{} died", g.name)); + let (name, uuid) = (g.name.clone(), g.uuid); + let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take()); + let message = match cause { + // ServerPlayer.die: the death message, to everyone unless + // the player's team hides it. + Some(key) if self.ui.rules.bool("show_death_messages") => { + let text = horizon_client::text::Text::translate( + &key, + &[self.player_text(&name, uuid)], + ); + let message = horizon_client::lan::data::component_nbt(&text.component()); + let team = self.score.board.players_team(&name); + if horizon_client::scoreboard::own_death_message_shown(team) { + host.hub.system_message(message.clone()); + if self.options.dedicated.is_some() { + super::dedicated::log( + "INFO", + &format!("System chat: {}", text.plain()), + ); + } else if self.player.is_some() { + self.system_message(text); + } + } + message + } + Some(_) => literal(""), + None => literal(&format!("{name} died")), + }; host.hub.send_to( conn, &C::PlayerCombatKill(play::PlayerCombatKill { id, message }), @@ -1184,7 +1433,7 @@ impl Game<'_> { 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"); + let bed = self.res.facts().get(block).name.ends_with("_bed"); if g.dead || g.health <= 0.0 || !bed { host.hub.wake(gi); } @@ -1352,7 +1601,7 @@ impl Game<'_> { let range = |v: f64| (v - half).floor() as i32..=(v + half).floor() as i32; range(at[0]).any(|x| { range(at[2]).any(|z| { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); f.full_collision && f.solid_render }) }) @@ -1370,7 +1619,7 @@ impl Game<'_> { play.mining = None; let start = play.dig_start; let state = self.world.block(pos[0], pos[1], pos[2]); - if !dug || self.res.facts.is_air(state) { + if !dug || self.res.facts().is_air(state) { return; } let progress = self @@ -1394,7 +1643,7 @@ impl Game<'_> { }; let ticks = host.hub.ticks; let state = self.world.block(pos[0], pos[1], pos[2]); - let progress = if self.res.facts.is_air(state) { + let progress = if self.res.facts().is_air(state) { None } else { self.as_guest(host, conn, |g| g.destroy_progress(pos)) @@ -1619,23 +1868,72 @@ impl Game<'_> { } } - /// Guests' arm swings for everyone else. + /// The guests' items in use, for the players around (`LivingEntity.startUsingItem` + /// and `stopUsingItem` set DATA_LIVING_ENTITY_FLAGS). + pub(super) fn lan_living_flags(&mut self, host: &mut LanHost) { + for g in &mut host.hub.guests { + let using = host.play.get(&g.conn).and_then(GuestPlay::using); + g.living_flags = super::lan::living_flags(using); + } + } + + /// A use the server ran swung the guest's hand: their own client is told + /// too (`swing(hand, true)` for a SwingSource.SERVER result). Horizon's + /// client does not run uses itself, so it does not predict the swing; a + /// client that did (a block placed) is still in the first half of its + /// swing and ignores it (`SwingState.startIfAble`). + fn lan_swing_back(&mut self, host: &mut LanHost, conn: u32, swung: Option) { + if swung != Some(true) { + return; + } + let (Some(g), Some(play)) = (host.hub.guest(conn), host.play.get(&conn)) else { + return; + }; + if let Some(c) = play.swing.current { + host.hub + .send_to(conn, &swing_packet(g.entity_id, c.hand, c.animation)); + } + } + + /// The tick's arm swings for the players around (the guests' to everyone + /// else, the host's to the guests), and `LivingEntity.updateSwingTime` + /// for the guests' bodies here. pub(super) fn lan_swings(&mut self, host: &mut LanHost) { let conns: Vec = host.play.keys().copied().collect(); for conn in conns { 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 (id, at, here) = (g.entity_id, g.position, host.hub.here(g)); let play = host.play.get_mut(&conn).expect("play"); - let swinging = play.swing.swinging() && play.swing.ticks == 0; - if swinging && !play.swung { - host.hub.swing(id, 0, at, Some(conn)); + let swung = std::mem::take(&mut play.swings) > 0; + if let (true, true, Some(c)) = (swung, here, play.swing.current) { + let packet = swing_packet(id, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, Some(conn)); + if let Some(m) = host.models.get_mut(&conn) { + m.swing(); + } + } + play.swing.tick(); + } + if self.swings_started != host.host_swings { + host.host_swings = self.swings_started; + if let (Some(p), Some(c)) = (self.player.as_ref(), self.swing.current) { + let at = [p.position.x, p.position.y, p.position.z]; + let packet = swing_packet(host.host_entity, c.hand, c.animation); + host.hub.broadcast_near(at, 128.0, &packet, None); } - play.swung = swinging; } } } + +/// ClientboundSwingAnimationPacket: the hand and the animation (its type and +/// base duration; each client applies the swinger's haste and fatigue). +fn swing_packet(id: i32, hand: Hand, animation: SwingAnimation) -> C { + C::SwingAnimation(play::SwingAnimation { + id, + hand: i32::from(hand == Hand::Off), + kind: i32::from(animation.kind), + duration: animation.duration, + }) +} diff --git a/crates/horizon-client/src/game/lan_attributes.rs b/crates/horizon-client/src/game/lan_attributes.rs new file mode 100644 index 000000000..72d06c2ef --- /dev/null +++ b/crates/horizon-client/src/game/lan_attributes.rs @@ -0,0 +1,274 @@ +//! The attribute instances a server syncs for the living entities it tracks +//! (`ClientboundUpdateAttributesPacket`, lan/attributes.rs): the ones +//! vanilla's `AttributeMap` would have created by then, since only those are +//! sent, never the type's other defaults. +use super::Game; +use super::commands::Target; +use horizon_client::{ + effects, + lan::attributes::{add_modifier, generic_syncable, instance, operation_named}, + mobs::{ + Mob, + finalize::{self, Attr, Op}, + }, +}; +use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; +use std::sync::Arc; + +/// `EquipmentSlotGroup.test`: whether a modifier's slot group covers a slot. +fn slot_in_group(group: &str, slot: &str) -> bool { + group == slot + || group == "any" + || (group == "hand" && matches!(slot, "mainhand" | "offhand")) + || (group == "armor" && matches!(slot, "feet" | "legs" | "chest" | "head" | "body")) +} + +impl Game<'_> { + /// The registry id of a client-syncable attribute the entity type has + /// (`AttributeMap.getInstance` is null for the others), by name. + fn synced_attribute(&self, entity: &str, name: &str) -> Option { + let catalog = &self.motion.attributes; + let id = catalog.id(name)?; + (catalog.attribute(id).syncable && catalog.default_base(entity, id).is_some()) + .then(|| id.registry_id()) + } + + /// The type's base value of an attribute, as the instance starts. + fn attribute_default(&self, entity: &str, name: &str) -> f64 { + let catalog = &self.motion.attributes; + catalog + .id(name) + .and_then(|id| catalog.default_base(entity, id)) + .unwrap_or(0.0) + } + + /// `LivingEntity.collectEquipmentChanges`: each worn or held item's + /// attribute modifiers, slot by slot in `EquipmentSlot` order, create + /// their instances (an instance without a modifier keeps its base). + fn equipment_attributes<'a>( + &self, + entity: &str, + base: impl Fn(&str) -> Option, + slots: impl IntoIterator>)>, + out: &mut Vec, + ) { + for (slot, item) in slots { + let Some(info) = item.and_then(|i| self.res.items().get(i)) else { + continue; + }; + for (attribute, id, amount, op, group) in &info.modifiers { + if !slot_in_group(group, slot) { + continue; + } + let Some(a) = self.synced_attribute(entity, attribute) else { + continue; + }; + let start = + base(attribute).unwrap_or_else(|| self.attribute_default(entity, attribute)); + add_modifier( + out, + a, + start, + AttributeModifier { + id: id.clone(), + amount: *amount, + operation: operation_named(op), + }, + ); + } + } + } + + /// A mob's synced instances: movement speed (its first `aiStep` reads it, + /// `LivingEntity.removeFrost`), what finalizeSpawn set, the baby speed + /// modifier, its effects' modifiers, its equipment's, and what + /// `/attribute` changed. + pub(super) fn mob_attributes(&self, m: &Mob) -> Vec { + let kind = m.kind.id.as_str(); + let mut out = Vec::new(); + if let Some(a) = self.synced_attribute(kind, "minecraft:movement_speed") { + instance(&mut out, a, finalize::base_value(m, Attr::MovementSpeed)); + } + if let Some(s) = m.extra.attributes.as_deref() { + for (attr, v) in &s.bases { + if let Some(a) = self.synced_attribute(kind, &format!("minecraft:{}", attr.name())) + { + instance(&mut out, a, *v).base = *v; + } + } + for x in &s.modifiers { + if let Some(a) = + self.synced_attribute(kind, &format!("minecraft:{}", x.attr.name())) + { + add_modifier( + &mut out, + a, + finalize::base_value(m, x.attr), + AttributeModifier { + id: x.id.to_owned(), + amount: x.amount, + operation: match x.op { + Op::AddValue => 0, + Op::AddMultipliedBase => 1, + Op::AddMultipliedTotal => 2, + }, + }, + ); + } + } + } + if let (Some(a), Some((amount, Op::AddMultipliedBase))) = ( + self.synced_attribute(kind, "minecraft:movement_speed"), + finalize::transient(m, Attr::MovementSpeed), + ) { + add_modifier( + &mut out, + a, + finalize::base_value(m, Attr::MovementSpeed), + AttributeModifier { + id: "minecraft:baby".into(), + amount, + operation: 1, + }, + ); + } + let base = |name: &str| { + Attr::ALL + .into_iter() + .find(|a| name.strip_prefix("minecraft:") == Some(a.name())) + .map(|a| finalize::base_value(m, a)) + }; + // LivingEntity.onEffectAdded: MobEffect.addAttributeModifiers. + for &(effect, _, amplifier) in &m.extra.effects { + let Some((attribute, id, amount, op)) = + effects::effect_modifier(effect.trim_start_matches("minecraft:")) + else { + continue; + }; + let Some(a) = self.synced_attribute(kind, attribute) else { + continue; + }; + let start = base(attribute).unwrap_or_else(|| self.attribute_default(kind, attribute)); + add_modifier( + &mut out, + a, + start, + AttributeModifier { + id: id.to_owned(), + amount: amount * f64::from(amplifier + 1), + operation: operation_named(op), + }, + ); + } + let e = &m.extra; + self.equipment_attributes( + kind, + base, + [ + ("mainhand", e.main_hand.as_ref()), + ("offhand", e.off_hand.as_ref()), + ("feet", e.feet.as_ref()), + ("legs", e.legs.as_ref()), + ("chest", e.chest.as_ref()), + ("head", e.head.as_ref()), + ], + &mut out, + ); + self.generic_attributes_of(Target::Mob(m.id), &mut out); + out + } + + /// An armor stand's synced instances: movement speed (its first + /// `aiStep`), its equipment's modifiers and what `/attribute` changed. + pub(super) fn stand_attributes( + &self, + id: u32, + equipment: &[Option; 6], + ) -> Vec { + const KIND: &str = "minecraft:armor_stand"; + let mut out = Vec::new(); + if let Some(a) = self.synced_attribute(KIND, "minecraft:movement_speed") { + instance( + &mut out, + a, + self.attribute_default(KIND, "minecraft:movement_speed"), + ); + } + let slots = horizon_client::entities::ArmorStand::SLOTS + .into_iter() + .zip(equipment.iter().map(|s| s.as_ref().map(|s| &s.item))); + self.equipment_attributes(KIND, |_| None, slots, &mut out); + self.generic_attributes_of(Target::Stand(id), &mut out); + out + } + + /// The instances a server player's tick creates, and + /// `ServerPlayer.updatePlayerAttributes`: a creative player reaches 0.5 + /// further to blocks and 2 to entities. Its client reads the reach from + /// these synced modifiers. (The crouching player's waypoint range is + /// server-side only: lan_waypoints.rs hides it.) + pub(super) fn update_player_attributes(&mut self) { + let creative = self.mode_id() == 1; + let Some(p) = self.player.as_mut() else { + return; + }; + // LivingEntity.aiStep's removeFrost reads the movement speed instance + // every tick, which creates it (and its first sync). + if let Some(key) = p.attributes.key("minecraft:movement_speed") { + let _ = p.attributes.get_instance(Some(key)); + } + for (attribute, id, amount) in [ + ( + "minecraft:block_interaction_range", + "minecraft:creative_mode_block_range", + 0.5, + ), + ( + "minecraft:entity_interaction_range", + "minecraft:creative_mode_entity_range", + 2.0, + ), + ] { + let Some(key) = p.attributes.key(attribute) else { + continue; + }; + // getAttribute creates the instance, a creative player's or not. + if !matches!(p.attributes.get_instance(Some(key.clone())), Ok(Some(_))) { + continue; + } + // addOrUpdateTransientModifier with the same modifier and + // removeModifier of a missing one leave the instance clean. + let has = p.attributes.has_modifier(Some(key), id).unwrap_or(false); + if has != creative { + let _ = p.set_modifier(attribute, id, amount, "add_value", creative); + } + } + } + + /// The instances `/attribute` created in an entity's generic map + /// replace the ones derived from its state. + fn generic_attributes_of(&self, t: Target, out: &mut Vec) { + let Some(map) = self.cmds.attributes.get(&t) else { + return; + }; + for s in generic_syncable(map) { + let (attribute, base) = (s.attribute, s.base); + *instance(out, attribute, base) = s; + } + } +} + +#[cfg(test)] +mod tests { + use super::slot_in_group; + + #[test] + fn slot_groups_cover_their_slots() { + assert!(slot_in_group("head", "head")); + assert!(slot_in_group("armor", "chest")); + assert!(!slot_in_group("armor", "mainhand")); + assert!(slot_in_group("hand", "offhand")); + assert!(slot_in_group("any", "feet")); + assert!(!slot_in_group("mainhand", "offhand")); + } +} diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 1f16a9c74..de26e84aa 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -21,9 +21,10 @@ pub(super) struct GuestCrafting { inventory: Option>, /// The open crafting table: its window, state id and menu. table: Option<(i32, i32, Box)>, - /// The open furnace's window and menu (`AbstractFurnaceMenu`); its slots live in - /// the furnace block entity and the hub's container menu keeps the client in sync. - furnace: Option<(i32, Box)>, + /// The open furnace's or brewing stand's window and menu (`AbstractFurnaceMenu`, + /// `BrewingStandMenu`); its slots live in the block entity and the hub's + /// container menu keeps the client in sync. + machine: Option<(i32, Box)>, } /// ServerboundContainerClickPacket's input. @@ -84,10 +85,10 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { impl Game<'_> { fn menu_env(&self) -> Env<'_> { Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: None, } } @@ -157,10 +158,11 @@ impl Game<'_> { true } - /// A click on the guest's open furnace, blast furnace or smoker: the host's - /// `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by recipe and - /// fuel) over the block entity's slots. False for other windows. - pub(super) fn lan_furnace_click( + /// A click on the guest's open furnace, blast furnace, smoker or brewing stand: + /// the host's `AbstractFurnaceMenu` (fuel slot, take-only result, quick moves by + /// recipe and fuel) or `BrewingStandMenu` (one bottle per slot, ingredient and + /// blaze powder slots) over the block entity's slots. False for other windows. + pub(super) fn lan_machine_click( &mut self, host: &mut LanHost, conn: u32, @@ -180,15 +182,18 @@ impl Game<'_> { else { return false; }; - let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get(&pos) else { - return false; + let (kind, items) = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Furnace(f)) => { + let recipe = match f.kind.recipe_type() { + "minecraft:blasting" => "blasting", + "minecraft:smoking" => "smoking", + _ => "smelting", + }; + (Kind::Furnace(recipe), f.items.to_vec()) + } + Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()), + _ => return false, }; - let recipe = match f.kind.recipe_type() { - "minecraft:blasting" => "blasting", - "minecraft:smoking" => "smoking", - _ => "smelting", - }; - let items = f.items.clone(); if host.hub.guests[gi].spectator() { return true; } @@ -197,10 +202,10 @@ impl Game<'_> { .entry(conn) .or_default() .crafting - .furnace + .machine .take() .filter(|(window, _)| *window == p.container) - .map_or_else(|| Box::new(Menu::new(Kind::Furnace(recipe))), |(_, m)| m); + .map_or_else(|| Box::new(Menu::new(kind)), |(_, m)| m); let changed = self.guest_menu_op(host, gi, &mut menu, |menu, env| { for (k, s) in items.iter().enumerate() { menu.set_slot(env, k, s.clone()); @@ -213,14 +218,23 @@ impl Game<'_> { .filter(|&s| menu.slot(s) != before[s].as_ref()) .collect::>() }); - if let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&pos) { - for k in 0..3 { - f.items[k] = menu.slot(k).cloned(); + match self.world.block_entities.get_mut(&pos) { + Some(BlockEntity::Furnace(f)) => { + for k in 0..3 { + f.items[k] = menu.slot(k).cloned(); + } + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(self.res.recipes(), items[0].clone()); } - // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. - f.input_clicked(&self.res.recipes, items[0].clone()); + // BrewingStandBlockEntity.serverTick notices a new ingredient itself. + Some(BlockEntity::Brewing(b)) => { + for k in 0..5 { + b.items[k] = menu.slot(k).cloned(); + } + } + _ => {} } - host.play.entry(conn).or_default().crafting.furnace = Some((p.container, menu)); + host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); host.hub.inventory_clicked(conn, p, &self.world, &changed); true } @@ -245,7 +259,7 @@ impl Game<'_> { } let Some(id) = self .res - .stations + .stations() .recipe_index .recipe_of_display(p.recipe) .map(str::to_owned) @@ -256,7 +270,7 @@ impl Game<'_> { if !g.recipe_book.knows(&id) || self .res - .recipes + .recipes() .placement(&id) .is_none_or(|placement| placement.impossible()) { diff --git a/crates/horizon-client/src/game/lan_entities.rs b/crates/horizon-client/src/game/lan_entities.rs index 3ea172482..7a1236e52 100644 --- a/crates/horizon-client/src/game/lan_entities.rs +++ b/crates/horizon-client/src/game/lan_entities.rs @@ -37,6 +37,7 @@ fn state(id: u32, kind: &str, position: [f64; 3], yaw: f32, on_ground: bool) -> data: 0, meta: Vec::new(), equipment: Vec::new(), + attributes: Vec::new(), precise: false, } } @@ -179,6 +180,7 @@ impl Game<'_> { e.equipment.push((slot as u8, hub.stack(item))); } } + e.attributes = self.stand_attributes(a.id, &a.equipment); out.push(e); } for f in &self.item_frames { diff --git a/crates/horizon-client/src/game/lan_mobs.rs b/crates/horizon-client/src/game/lan_mobs.rs index 99888058c..0ee991737 100644 --- a/crates/horizon-client/src/game/lan_mobs.rs +++ b/crates/horizon-client/src/game/lan_mobs.rs @@ -131,6 +131,26 @@ impl Game<'_> { self.lan = Some(host); } + /// The guests' boxes for the blocks entities trigger (pressure plates, + /// tripwires, detector rails): `Entity.checkInsideBlocks` and + /// `Level.getEntities` see every player in the level, but not spectators + /// (`Entity.isIgnoringBlockTriggers`). + pub(super) fn lan_block_trigger_boxes(&self) -> Vec<([f64; 3], [f64; 3])> { + let Some(host) = self.lan.as_ref() else { + return Vec::new(); + }; + host.hub + .guests + .iter() + .filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator()) + .map(|g| { + let [x, y, z] = g.position; + let height = if g.sneaking { 1.5 } else { 1.8 }; + ([x - 0.3, y, z - 0.3], [x + 0.3, y + height, z + 0.3]) + }) + .collect() + } + /// The guests a projectile can hit, under their entity ids. pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> { let Some(host) = self.lan.as_ref() else { diff --git a/crates/horizon-client/src/game/lan_screen.rs b/crates/horizon-client/src/game/lan_screen.rs index 6be6fc7fa..335b5fbae 100644 --- a/crates/horizon-client/src/game/lan_screen.rs +++ b/crates/horizon-client/src/game/lan_screen.rs @@ -596,11 +596,11 @@ impl Game<'_> { View::Restrictions => self.draw_restrictions(batch), View::GameRules => { if let Some(rules) = o.rules.as_mut() { - rules.draw(batch, &self.atlas, self.cursor); + rules.draw(batch, &self.gui.atlas, self.cursor); } else { ui::menu_background( batch, - &self.atlas, + &self.gui.atlas, 0.0, 0.0, batch.width, @@ -614,7 +614,7 @@ impl Game<'_> { } fn draw_lock_question(&self, o: &WorldOptions, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); // Screen.extractTransparentBackground. batch.fill_gradient( @@ -656,7 +656,7 @@ impl Game<'_> { } fn draw_restrictions(&self, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("restrictions_screen.title", &[]); @@ -687,7 +687,7 @@ impl Game<'_> { } fn draw_options_view(&self, o: &mut WorldOptions, batch: &mut HudBatch, cursor: (f32, f32)) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); o.scroll = o.scroll.clamp(0.0, o.scroll_limit(h)); // extractMenuBackground: the in-world background, the list @@ -810,7 +810,7 @@ impl Game<'_> { match o.view { View::Options => {} View::GameRules => { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let exit = o.rules.as_mut().and_then(|rules| { if rules.clicks_button(atlas, self.cursor, (w, h)) { self.audio.play_button_click(); @@ -824,7 +824,7 @@ impl Game<'_> { return; } View::LockQuestion => { - let p = Popup::lock_question(&self.atlas.font, o.difficulty, (w, h)); + let p = Popup::lock_question(&self.gui.atlas.font, o.difficulty, (w, h)); let hit = p .buttons .iter() @@ -842,7 +842,8 @@ impl Game<'_> { return; } View::Restrictions => { - let r = Restrictions::new(&self.atlas.font, self.settings.chat_visibility, (w, h)); + let r = + Restrictions::new(&self.gui.atlas.font, self.settings.chat_visibility, (w, h)); let in_body = self.cursor.1 >= r.area.0 && self.cursor.1 < r.area.1; let action = r.action.is_some_and(|(ax, ay)| { in_body && ui::hovered(self.cursor, ax, ay, 200.0, 20.0) diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index ee6b55d16..c7f8a94a6 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -133,7 +133,7 @@ impl Game<'_> { if let Some(name) = &state.name { return name.clone(); } - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let profession = state.session.profession.trim_start_matches("minecraft:"); if state.session.villager { e.translate(&format!("entity.minecraft.villager.{profession}")) @@ -245,15 +245,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let trade_env = merchant::TradeEnv { - trades: &self.res.stations.trades, - enchantments: &self.res.stations.enchantments, + trades: &self.res.stations().trades, + enchantments: &self.res.stations().enchantments, maps: Some(&maps), }; let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + items: self.res.items(), + recipes: self.res.recipes(), + brewing: &self.res.stations().brewing, + banners: &self.res.stations().banners, trade: Some(&trade_env), }; let mut menu = Menu::new(Kind::Merchant); diff --git a/crates/horizon-client/src/game/leads.rs b/crates/horizon-client/src/game/leads.rs index 3b8fc29c4..ae5d87fff 100644 --- a/crates/horizon-client/src/game/leads.rs +++ b/crates/horizon-client/src/game/leads.rs @@ -220,11 +220,11 @@ impl Game<'_> { }; let name = self .res - .facts + .facts() .get(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); if !self .res - .items + .items() .block_tags .get("minecraft:fences") .is_some_and(|s| s.contains(&*name.name)) @@ -283,7 +283,7 @@ impl Game<'_> { } /// `LeashFeatureRenderer` for every lead and `LeashKnotRenderer` for the knots. pub(super) fn leash_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let white = atlas.font.white(); let uv = [ [white.u0, white.v1], diff --git a/crates/horizon-client/src/game/level_particles.rs b/crates/horizon-client/src/game/level_particles.rs index 4516ce7dd..47d06254d 100644 --- a/crates/horizon-client/src/game/level_particles.rs +++ b/crates/horizon-client/src/game/level_particles.rs @@ -1,6 +1,7 @@ //! Level events whose client handler (`LevelEventHandler`) spawns particles -//! on a block: dragon egg teleportation (2015), electric sparks (3002), -//! waxing (3003), wax off (3004) and scraping (3005). +//! on a block: dragon egg teleportation (2015), a consumable's teleport +//! (2017), electric sparks (3002), waxing (3003), wax off (3004) and +//! scraping (3005). use super::Game; use horizon_client::particles::{self, ParticleOptions, ParticleType}; use horizon_core::position::BlockPos; @@ -9,7 +10,12 @@ use horizon_world::level::LevelEvent; impl Game<'_> { pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) { self.particles - .block_teleportation(pos, data, self.settings.particles); + .block_teleportation(pos, data, [16, 8, 16], self.settings.particles); + } + /// Event 2017: `TeleportRandomlyConsumeEffect`'s directional particles. + pub(super) fn consume_teleport_particles(&mut self, pos: [i32; 3], data: i32) { + self.particles + .block_teleportation(pos, data, [127, 127, 127], self.settings.particles); } /// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client /// level's random. diff --git a/crates/horizon-client/src/game/levels.rs b/crates/horizon-client/src/game/levels.rs index 3a84e2f78..3225408f5 100644 --- a/crates/horizon-client/src/game/levels.rs +++ b/crates/horizon-client/src/game/levels.rs @@ -20,10 +20,11 @@ use super::{ }; use horizon_client::{ Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections, - save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, world::World, + save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership, + ticket_levels::ChunkTickets, world::World, }; use horizon_world::level::{LevelEvent, Ticks}; -use std::{collections::HashMap, sync::Arc}; +use std::{collections::HashMap, sync::Arc, time::Instant}; /// 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 @@ -37,6 +38,7 @@ pub(super) struct Parked { save: Arc, block_ticks: Ticks, tick_chunks: TickChunkMembership, + tickets: ChunkTickets, random_tick_sections: RandomTickSections, level_events: Vec, falling: Vec, @@ -105,7 +107,7 @@ impl Game<'_> { 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); + let mut world = World::new(self.res.facts().air, self.level.seed); world.fast_lava = dim == Dim::Nether; Ok(Parked { world, @@ -113,6 +115,7 @@ impl Game<'_> { save, block_ticks: Ticks::new(self.level.seed as i32), tick_chunks: Default::default(), + tickets: Default::default(), random_tick_sections: Default::default(), level_events: Vec::new(), falling: Vec::new(), @@ -159,6 +162,7 @@ impl Game<'_> { 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.tickets, &mut p.tickets); 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); @@ -287,6 +291,37 @@ impl Game<'_> { self.close_idle_levels() } + /// `tick_server` as a server thread runs it. With `HORIZON_SPIKES=MS`, a + /// tick longer than MS is logged with its thread CPU time and spans. + pub(super) fn tick_server_timed(&mut self, paused: bool) -> Result<()> { + let Some(threshold) = self.options.spikes else { + return self.tick_server(paused); + }; + let (started, cpu) = (Instant::now(), horizon_client::spans::thread_cpu()); + let result = self.tick_server(paused); + let wall = started.elapsed().as_secs_f32() * 1000.0; + // Taken every tick: nothing else takes this thread's spans. + let spans = horizon_client::spans::take(); + if wall > threshold { + let cpu = horizon_client::spans::thread_cpu() + .zip(cpu) + .map_or_else(String::new, |(end, start)| { + format!(", cpu {:.1} ms", (end - start).as_secs_f32() * 1000.0) + }); + let list: Vec = spans + .iter() + .filter(|(_, ms)| *ms >= 0.5) + .map(|(n, ms)| format!("{n} {ms:.1}")) + .collect(); + log::info!( + "Horizon: slow tick {wall:.1} ms{cpu} ({} mobs): {}", + self.mobs.len(), + list.join(", ") + ); + } + result + } + /// 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. diff --git a/crates/horizon-client/src/game/lightning.rs b/crates/horizon-client/src/game/lightning.rs index 834925c57..6c4dd933f 100644 --- a/crates/horizon-client/src/game/lightning.rs +++ b/crates/horizon-client/src/game/lightning.rs @@ -24,14 +24,18 @@ pub(super) struct Bolt { converted: Vec, } impl Game<'_> { - /// One `tickThunder` roll per loaded chunk. + /// `ServerChunkCache.tickSpawningChunk`: one `tickThunder` roll per + /// spawning chunk (within 128 blocks of a player) that is in entity + /// ticking range. pub(super) fn tick_thunder(&mut self) { // isRaining (rain level > 0.2) and isThundering (> 0.9, sky light, no ceiling). let (rain, thunder) = self.world.weather.levels(1.0); if rain <= 0.2 || thunder <= 0.9 || self.dim != super::Dim::Overworld { return; } - let chunks: Vec<(i32, i32)> = self.world.chunks.keys().copied().collect(); + let (_, mut chunks) = self.spawning_chunks(&self.level_players()); + let levels = self.tickets.levels(); + chunks.retain(|&(x, z)| levels.random_ticking(x, z)); for (cx, cz) in chunks { if self.world.random.next_int_bound(100_000).unwrap_or(1) != 0 { continue; @@ -50,7 +54,7 @@ impl Game<'_> { let difficulty = f64::from(self.ui.difficulty) * 0.75; let below = &self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] - 1, pos[2])) .name; let trap = self.ui.rules.bool("spawn_mobs") @@ -160,11 +164,11 @@ impl Game<'_> { } for p in spots { let state = self.world.block(p[0], p[1], p[2]); - if !self.res.facts.is_air(state) { + if !self.res.facts().is_air(state) { continue; } // BaseFireBlock.getState: soul fire on soul soil and sand. - let below = self.res.facts.get(self.world.block(p[0], p[1] - 1, p[2])); + let below = self.res.facts().get(self.world.block(p[0], p[1] - 1, p[2])); let name = if matches!(&*below.name, "minecraft:soul_soil" | "minecraft:soul_sand") { "minecraft:soul_fire" } else { @@ -236,7 +240,7 @@ impl Game<'_> { at[2].floor() as i32, ]; let state = self.world.block(p[0], p[1], p[2]); - if !self.res.facts.get(state).name.ends_with("lightning_rod") { + if !self.res.facts().get(state).name.ends_with("lightning_rod") { return; } let registry = self.pack.assets.registry; @@ -348,7 +352,7 @@ impl Game<'_> { /// `LightningBoltRenderer`: 4 layers of a trunk and two branches, 8 /// segments of 16 blocks, from the bolt's seed. pub(super) fn bolt_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let uv = [white.u0, white.v0]; // ARGB 0.45, 0.45, 0.5 at 0.3 alpha, packed RGBA. let color = (76u32 << 24) | (127 << 16) | (114 << 8) | 114; diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 541e4e6a9..f1ff1a300 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -192,14 +192,14 @@ impl Game<'_> { base: &str, layers: &[BannerLayer], ) { - let banners = &self.res.stations.banners; + let banners = &self.res.stations().banners; let layers: Vec<(String, String)> = layers .iter() .map(|l| (banners.banner_texture(&l.pattern), l.color.to_string())) .collect(); horizon_client::item_render::gui::draw_banner_result( &self.pack.item_renderer, - &self.atlas.sprites, + &self.gui.atlas.sprites, batch, x, y, @@ -217,7 +217,7 @@ impl Game<'_> { draws: &[ScreenDraw], background: bool, ) -> Option> { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let mut tooltip = None; let mut sheet: Option = None; for d in draws { @@ -317,7 +317,7 @@ impl Game<'_> { let l = &s.loom; let dye = s.inputs[1] .as_ref() - .and_then(|d| self.res.items.get(&d.item)) + .and_then(|d| self.res.items().get(&d.item)) .and_then(|i| i.dye.clone()) .unwrap_or_else(|| "white".to_owned()); let result = s @@ -342,7 +342,7 @@ impl Game<'_> { dye: &dye, mouse: local, }; - let draws = screen_layout::loom(&view, &self.res.stations.banners); + let draws = screen_layout::loom(&view, &self.res.stations().banners); self.paint_screen(batch, ox, oy, &draws, false) } } diff --git a/crates/horizon-client/src/game/mace.rs b/crates/horizon-client/src/game/mace.rs index 062d04525..46091a773 100644 --- a/crates/horizon-client/src/game/mace.rs +++ b/crates/horizon-client/src/game/mace.rs @@ -84,11 +84,11 @@ impl Game<'_> { direct_attacker: Some("minecraft:player"), is_direct: true, damage_type: Some("minecraft:mace_smash"), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; // EnchantmentHelper.modifyFallBasedDamage(..., 0) - let per_block = self.res.stations.enchantments.modify_value( + let per_block = self.res.stations().enchantments.modify_value( held.as_ref(), "minecraft:smash_damage_per_fallen_block", &ctx, @@ -111,10 +111,10 @@ impl Game<'_> { horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash", _ => "minecraft:player_attack", }), - items: Some(&self.res.items), + items: Some(self.res.items()), ..Default::default() }; - let enchantments = &self.res.stations.enchantments; + let enchantments = &self.res.stations().enchantments; let random = &mut self.world.random; // CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness. let mut breach = |fraction: f32| { @@ -143,7 +143,7 @@ impl Game<'_> { }; let weapon = self .res - .items + .items() .get(&stack.item) .and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage))); let smash = self.smash_attack(); diff --git a/crates/horizon-client/src/game/machines.rs b/crates/horizon-client/src/game/machines.rs index d46928060..c05c7295f 100644 --- a/crates/horizon-client/src/game/machines.rs +++ b/crates/horizon-client/src/game/machines.rs @@ -361,10 +361,10 @@ impl Game<'_> { fn containers(&self) -> Containers<'_> { Containers { world: &self.world, - behaviours: &self.res.behaviours, - items: &self.res.items, + behaviours: self.res.behaviours(), + items: self.res.items(), registry: self.pack.assets.registry, - brewing: Some(&self.res.stations.brewing), + brewing: Some(&self.res.stations().brewing), bone_meal: bone_meal(), } } @@ -502,7 +502,7 @@ impl Game<'_> { pub(super) fn tick_hopper(&mut self, pos: Pos) { let hopper = self .res - .facts + .facts() .get(self.world.block(pos.0, pos.1, pos.2)) .name .as_ref() @@ -626,12 +626,12 @@ impl Game<'_> { return false; } let above_state = self.world.block(above.0, above.1, above.2); - let blocked = self.res.facts.get(above_state).full_collision + let blocked = self.res.facts().get(above_state).full_collision && !self .res - .behaviours + .behaviours() .tag("minecraft:does_not_block_hoppers") - .is_some_and(|t| t.contains(self.res.behaviours.block(above_state))); + .is_some_and(|t| t.contains(self.res.behaviours().block(above_state))); if blocked { return false; } @@ -678,7 +678,7 @@ impl Game<'_> { /// `DispenserBlock.dispenseFrom` / `DropperBlock.dispenseFrom`. pub(super) fn dispense_from(&mut self, pos: BlockPos, state: BlockStateId) -> Result<()> { let key = (pos.x, pos.y, pos.z); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); if &*name == "minecraft:crafter" { return self.crafter_dispense(pos, state); } @@ -770,12 +770,20 @@ enum Screen { impl Game<'_> { fn machine_screen(&self) -> Option { let key = self.container?; + // A server's menu shows by its type, whatever block (or minecart) holds it. + if let Some(menu) = self.remote_menu_type() { + return match menu { + "minecraft:hopper" => Some(Screen::Hopper), + "minecraft:generic_3x3" => Some(Screen::Dispenser), + _ => None, + }; + } if key.1 == super::minecarts::CART_KEY_Y { return (self.open_cart_kind() == Some(super::minecarts::CartKind::Hopper)) .then_some(Screen::Hopper); } let state = self.world.block(key.0, key.1, key.2); - match &*self.res.facts.get(state).name { + match &*self.res.facts().get(state).name { "minecraft:hopper" => Some(Screen::Hopper), "minecraft:dispenser" => Some(Screen::Dispenser), "minecraft:dropper" => Some(Screen::Dropper), @@ -832,7 +840,7 @@ impl Game<'_> { let Some(screen) = self.machine_screen() else { return false; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let key_is_cart = self .container .is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y); @@ -852,7 +860,9 @@ impl Game<'_> { batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX); } let grey = horizon_client::hud::rgba(64, 64, 64, 255); - let title = &self.container_title(title.to_owned()); + let title = &self + .remote_menu_title() + .unwrap_or_else(|| self.container_title(title.to_owned())); let title_x = if screen == Screen::Hopper { 8.0 } else { diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index 5642e5c2a..d87646fe0 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -94,7 +94,7 @@ impl Game<'_> { // RecipeCache.get: the first crafting recipe that matches, assembled. let found = self .res - .recipes + .recipes() .find(&grid, 3) .map(|(name, result)| (name.to_owned(), result)) .filter(|(_, result)| result.count > 0); @@ -120,7 +120,7 @@ impl Game<'_> { horizon_world::level::flags::UPDATE_CLIENTS, ); // The remainders come from the grid as it was before anything moved. - let remainders = self.res.recipes.remainders(&recipe, &grid, 3); + let remainders = self.res.recipes().remainders(&recipe, &grid, 3); self.crafter_eject(key, facing, result, &recipe); for rest in remainders.into_iter().flatten() { self.crafter_eject(key, facing, rest, &recipe); @@ -202,7 +202,7 @@ impl Game<'_> { pub(in crate::game) fn crafter_result(&self) -> Option { let key = self.container?; let c = self.crafter_at(key)?; - self.res.recipes.craft(&c.items, 3) + self.res.recipes().craft(&c.items, 3) } fn crafter_open(&self) -> bool { matches!(self.container_kind(), Some(BlockEntity::Crafter(_))) @@ -243,7 +243,7 @@ impl Game<'_> { // The background goes first, then the labels, then the slot decorations. let (background, rest) = draws.split_at(2.min(draws.len())); self.paint_screen(batch, ox, oy, background, true); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let grey = rgba(64, 64, 64, 255); let title = self.container_title(self.translate("container.crafter", "Crafter")); let tw = HudBatch::text_width(atlas, &title); diff --git a/crates/horizon-client/src/game/maps.rs b/crates/horizon-client/src/game/maps.rs index 2d7639260..855ef941a 100644 --- a/crates/horizon-client/src/game/maps.rs +++ b/crates/horizon-client/src/game/maps.rs @@ -673,17 +673,18 @@ impl Game<'_> { } else { loop { y -= 1; - color = self.res.facts.get(self.world.block(x, y, z)).map_color; + color = + self.res.facts().get(self.world.block(x, y, z)).map_color; if color != 0 || y <= min_y { break; } } - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if y > min_y && f.fluid != Fluid::None { let mut solid = y - 1; loop { let below = - self.res.facts.get(self.world.block(x, solid, z)); + self.res.facts().get(self.world.block(x, solid, z)); solid -= 1; water_depth += 1; if solid <= min_y || below.fluid == Fluid::None { @@ -789,6 +790,7 @@ impl Game<'_> { } let slot = self.maps.slots.last()?.1; let rect = self + .gui .atlas .sprites .get(&format!("horizon/map{slot}")) @@ -797,7 +799,7 @@ impl Game<'_> { if m.texture_dirty { m.texture_dirty = false; let rgba: Vec = m.colors.iter().flat_map(|&c| packed_rgba(c)).collect(); - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -855,7 +857,7 @@ impl Game<'_> { .map(|m| m.decorations.clone()) .unwrap_or_default(); for (i, d) in decorations.iter().enumerate() { - let Some(s) = self.atlas.sprites.get(d.sprite).copied() else { + let Some(s) = self.gui.atlas.sprites.get(d.sprite).copied() else { continue; }; let dm = glam::Mat4::from_translation(glam::Vec3::new( @@ -931,7 +933,7 @@ impl Game<'_> { } else { "map/map_background" }; - if let Some(r) = self.atlas.sprites.get(background).copied() { + if let Some(r) = self.gui.atlas.sprites.get(background).copied() { for (c, uv) in [ ([-7.0, 135.0, 0.0], [r.u0, r.v1]), ([135.0, 135.0, 0.0], [r.u1, r.v1]), diff --git a/crates/horizon-client/src/game/minecarts.rs b/crates/horizon-client/src/game/minecarts.rs index 1e0b42b50..367dc6aaf 100644 --- a/crates/horizon-client/src/game/minecarts.rs +++ b/crates/horizon-client/src/game/minecarts.rs @@ -218,7 +218,7 @@ impl CartModels { impl Game<'_> { pub(super) fn rail(&self, x: i32, y: i32, z: i32) -> Option { let state = self.world.block(x, y, z); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); if !matches!( &*name, "minecraft:rail" @@ -247,11 +247,14 @@ impl Game<'_> { } } fn conductor(&self, x: i32, y: i32, z: i32) -> bool { - self.res.facts.get(self.world.block(x, y, z)).full_collision + self.res + .facts() + .get(self.world.block(x, y, z)) + .full_collision } fn cart_in_water(&self, c: &Minecart) -> bool { let p = c.position; - let f = self.res.facts.get(self.world.block( + let f = self.res.facts().get(self.world.block( p.x.floor() as i32, (p.y + 0.1).floor() as i32, p.z.floor() as i32, @@ -661,7 +664,7 @@ impl Game<'_> { stack.count = 0; } Some(s) if s.same_item_same_components(&stack) => { - let max = self.res.items.get(&s.item).map_or(64, |i| i.max_stack); + let max = self.res.items().get(&s.item).map_or(64, |i| i.max_stack); let moved = stack.count.min(max.saturating_sub(s.count)); s.count += moved; stack.count -= moved; @@ -889,9 +892,9 @@ impl Game<'_> { (-1, 1), ] { let (x, y, z) = (bx + dx, by + dy, bz + dz); - let below = self.res.facts.get(self.world.block(x, y - 1, z)); - let here = self.res.facts.get(self.world.block(x, y, z)); - let head = self.res.facts.get(self.world.block(x, y + 1, z)); + let below = self.res.facts().get(self.world.block(x, y - 1, z)); + let here = self.res.facts().get(self.world.block(x, y, z)); + let head = self.res.facts().get(self.world.block(x, y + 1, z)); if (below.full_collision || below.legacy_solid) && !here.full_collision && !head.full_collision @@ -1156,7 +1159,7 @@ impl Game<'_> { diffuse: bool, out: &mut Vec, ) { - let Ok(models) = self.pack.assets.model_catalog.collect_seeded(state, seed) else { + let Ok(models) = self.pack.render.model_catalog.collect_seeded(state, seed) else { return; }; for (_, model) in &models { @@ -1165,7 +1168,7 @@ impl Game<'_> { .pack .layer_names .get(&face.layer) - .and_then(|n| self.atlas.sprites.get(n)) + .and_then(|n| self.gui.atlas.sprites.get(n)) else { continue; }; @@ -1239,6 +1242,7 @@ impl Game<'_> { pub(super) fn cart_geometry(&self, camera: glam::DVec3, alpha: f64, out: &mut Vec) { let a = alpha as f32; let Some(uv) = self + .gui .atlas .sprites .get("entity/minecart/minecart") @@ -1382,15 +1386,15 @@ impl Game<'_> { game_time: self.world.game_time, max_y: self.dim.max_y(), world: &self.world, - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, nether: self.dim == super::Dim::Nether, lid: &lid, sign: &|_| None, banner: &|_| Vec::new(), - glyph: &|c| self.atlas.glyph_cell(c), + glyph: &|c| self.gui.atlas.glyph_cell(c), }; self.res - .block_entity_render + .block_entity_render() .render_state(&scene, state.0, m, light, out); } } diff --git a/crates/horizon-client/src/game/mob_blocks.rs b/crates/horizon-client/src/game/mob_blocks.rs index 8b2b2da40..27a60ca19 100644 --- a/crates/horizon-client/src/game/mob_blocks.rs +++ b/crates/horizon-client/src/game/mob_blocks.rs @@ -75,10 +75,10 @@ impl Game<'_> { if left <= 0 { return; } - let Some(kind) = self.res.mob_types.get("minecraft:elder_guardian") else { + let Some(kind) = self.res.mob_types().get("minecraft:elder_guardian") else { return; }; - let Some(r) = self.atlas.sprites.get("entity/guardian_elder").copied() else { + let Some(r) = self.gui.atlas.sprites.get("entity/guardian_elder").copied() else { return; }; let age = (APPARITION_TICKS - left) as f32 + alpha as f32; @@ -142,12 +142,12 @@ impl Game<'_> { return; }; let Some(head) = - render::part_transform(mob, alpha as f32, camera, &self.res.mob_data, "head") + render::part_transform(mob, alpha as f32, camera, self.res.mob_data(), "head") else { return; }; let m = banner_matrix(head); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let uv = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); // BannerRenderer: the flag sways with a per-banner phase. let phase = @@ -187,7 +187,7 @@ impl Game<'_> { ) { for (corners, shade, side) in FACES { let name = cube.sprites[usize::from(side)]; - let Some(r) = self.atlas.sprites.get(name).copied() else { + let Some(r) = self.gui.atlas.sprites.get(name).copied() else { continue; }; let tint = if side == 0 { cube.tint } else { 0xFF_FFFF }; @@ -261,7 +261,7 @@ impl Game<'_> { 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) + render::held_item_transform(mob, alpha as f32, camera, self.res.mob_data(), left) else { continue; }; diff --git a/crates/horizon-client/src/game/mob_gear.rs b/crates/horizon-client/src/game/mob_gear.rs index c4a77e38c..809b250dc 100644 --- a/crates/horizon-client/src/game/mob_gear.rs +++ b/crates/horizon-client/src/game/mob_gear.rs @@ -91,9 +91,9 @@ impl Game<'_> { let cost = random .next_int_between_inclusive(MIN_COST, top) .unwrap_or(MIN_COST); - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let pool = e.tag("minecraft:on_mob_spawn_equipment"); - let picked = e.select(&self.res.items, random, item, cost, pool); + let picked = e.select(self.res.items(), random, item, cost, pool); if let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) { for (enchantment, level) in picked { gear::upgrade(m, slot, &enchantment, level); diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index 5a1131c3b..b6abf38ef 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -284,7 +284,7 @@ impl Game<'_> { let focused = self.screen == Screen::Chat; self.ui .chat - .add(&self.atlas, line, None, self.ticks, focused); + .add(&self.gui.atlas, line, None, self.ticks, focused); } } /// The mods' HUD panels, stacked with the extras in their corners. @@ -305,7 +305,7 @@ impl Game<'_> { .iter() .map(|l| (l.text.as_str(), l.color)) .collect(); - extras_hud::draw_lines(batch, &self.atlas, corners, corner, &lines); + extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines); } } } diff --git a/crates/horizon-client/src/game/mount_menu.rs b/crates/horizon-client/src/game/mount_menu.rs index 55e9dde11..1db2210d3 100644 --- a/crates/horizon-client/src/game/mount_menu.rs +++ b/crates/horizon-client/src/game/mount_menu.rs @@ -283,7 +283,7 @@ impl Game<'_> { let Some(open) = self.mount_menu.open.as_ref() else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.sprite_region( atlas, "gui/container/horse", @@ -376,7 +376,7 @@ impl Game<'_> { m.hurt_time = 0; m.death_time = 0; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -385,7 +385,7 @@ impl Game<'_> { camera, &lookup, 240 | 240 << 8, - &self.res.mob_data, + self.res.mob_data(), &[], &mut verts, ); diff --git a/crates/horizon-client/src/game/mounts.rs b/crates/horizon-client/src/game/mounts.rs index 869364176..42eac1e9b 100644 --- a/crates/horizon-client/src/game/mounts.rs +++ b/crates/horizon-client/src/game/mounts.rs @@ -90,7 +90,11 @@ impl Game<'_> { && let Some(stack) = self.inventory[self.selected].as_mut() { stack.damage += wear; - let max = self.res.items.get(&stack.item).map_or(25, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(25, |i| i.max_damage); if stack.damage >= max { self.inventory[self.selected] = Some(ItemStack::new("minecraft:fishing_rod", 1)); } @@ -406,7 +410,7 @@ impl Game<'_> { .find(|c| { let f = |dy: i32| { self.res - .facts + .facts() .get(self.world.block( c.x.floor() as i32, c.y.floor() as i32 + dy, @@ -457,7 +461,7 @@ impl Game<'_> { return (0, false); }; let m = &self.mobs[i]; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let hearts = horizon_client::hud_layout::vehicle_max_hearts(m.attrs.max_health); let draws = horizon_client::hud_layout::vehicle_health(w, h, hearts, m.health); horizon_client::hud_layout::paint(batch, atlas, &draws); diff --git a/crates/horizon-client/src/game/music.rs b/crates/horizon-client/src/game/music.rs index 381af21cf..9198a78a1 100644 --- a/crates/horizon-client/src/game/music.rs +++ b/crates/horizon-client/src/game/music.rs @@ -50,7 +50,7 @@ impl Game<'_> { let (background, probe_volume) = match eye { Some(eye) => { let (dimension, biome) = (self.dim.id(), self.biome_at(eye)); - let tables = &self.res.music; + let tables = self.res.music(); ( tables.background(dimension, biome), tables.volume(dimension, biome), @@ -81,7 +81,7 @@ impl Game<'_> { .chunks .get(&(x >> 4, z >> 4)) .map_or("minecraft:plains", |c| { - self.res.biomes.list[c.biome(x, y, z) as usize] + self.res.biomes().list[c.biome(x, y, z) as usize] .name .as_str() }) @@ -89,11 +89,11 @@ impl Game<'_> { /// `isEyeInFluid(WATER)`: the eye inside the water of its block column. fn eye_in_water(&self, x: f64, eye_y: f64, z: f64) -> bool { let (bx, by, bz) = (x.floor() as i32, eye_y.floor() as i32, z.floor() as i32); - let f = self.res.facts.get(self.world.block(bx, by, bz)); + let f = self.res.facts().get(self.world.block(bx, by, bz)); if f.fluid != Fluid::Water { return false; } - let above = self.res.facts.get(self.world.block(bx, by + 1, bz)); + let above = self.res.facts().get(self.world.block(bx, by + 1, bz)); let height = if above.fluid == Fluid::Water { 1.0 } else { @@ -111,7 +111,7 @@ impl Game<'_> { }; let feet = [p.position.x, p.position.y, p.position.z]; let eye_y = feet[1] + f64::from(p.dimensions.eye_height); - let sounds = self.res.ambient.get(self.dim.id(), self.biome_at(feet)); + let sounds = self.res.ambient().get(self.dim.id(), self.biome_at(feet)); let underwater = self.eye_in_water(feet[0], eye_y, feet[2]); let world = &self.world; let light = |b: [i32; 3]| { @@ -123,7 +123,7 @@ impl Game<'_> { f64::from(p.dimensions.height), ); let registry = &self.pack.assets.registry; - let facts = &self.res.facts; + let facts = self.res.facts(); let bubble_column = horizon_client::ambience::bubble_column_in( [ feet[0] - half, diff --git a/crates/horizon-client/src/game/names.rs b/crates/horizon-client/src/game/names.rs index 368c5c0f2..707b9df96 100644 --- a/crates/horizon-client/src/game/names.rs +++ b/crates/horizon-client/src/game/names.rs @@ -218,7 +218,7 @@ impl Game<'_> { let forward = glam::DVec3::from_array(view_vector(self.yaw, self.pitch)); let right = forward.cross(glam::DVec3::Y).normalize_or_zero(); let up = right.cross(forward).normalize_or_zero(); - let white = self.atlas.font.white(); + let white = self.gui.atlas.font.white(); let away = forward.as_vec3() * 0.002; for (text, lift) in lines { let o = (o + glam::DVec3::new(0.0, *lift, 0.0)).as_vec3(); @@ -240,7 +240,7 @@ impl Game<'_> { .collect(); let width: f32 = chars .iter() - .map(|(c, _)| self.atlas.glyph(*c).map_or(6.0, |g| g.1)) + .map(|(c, _)| self.gui.atlas.glyph(*c).map_or(6.0, |g| g.1)) .sum(); let x0 = -(width / 2.0).trunc(); let y0 = if text.plain() == "deadmau5" { @@ -278,7 +278,7 @@ impl Game<'_> { } let mut x = x0; for (ch, color) in chars { - let Some((g, advance)) = self.atlas.glyph(ch) else { + let Some((g, advance)) = self.gui.atlas.glyph(ch) else { x += 6.0; continue; }; diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 80d26a823..9bf7023af 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -23,10 +23,54 @@ use horizon_core::{ use horizon_world::registry::BlockStateId; use std::collections::HashMap; +/// A player in the level in place, as spawning and despawning see it. +pub(super) struct LevelPlayer { + pub(super) position: Vec3, + pub(super) bounds: Aabb, + pub(super) alive: bool, + pub(super) creative: bool, + pub(super) spectator: bool, +} +impl LevelPlayer { + fn distance_sqr(&self, x: f64, y: f64, z: f64) -> f64 { + (self.position.x - x).powi(2) + + (self.position.y - y).powi(2) + + (self.position.z - z).powi(2) + } +} +/// `ChunkMap.euclideanDistanceSquared` below 128 blocks +/// (`playerIsCloseEnoughForSpawning`). +fn close_enough_for_spawning(p: &LevelPlayer, (cx, cz): (i32, i32)) -> bool { + let (x, z) = ( + f64::from(cx * 16 + 8) - p.position.x, + f64::from(cz * 16 + 8) - p.position.z, + ); + !p.spectator && x * x + z * z < 16384.0 +} +/// `EntityGetter.getNearestPlayer(x, y, z, -1, false)`: the nearest +/// non-spectator, alive or not. +pub(super) fn nearest_player( + players: &[LevelPlayer], + x: f64, + y: f64, + z: f64, +) -> Option<&LevelPlayer> { + let mut best: Option<(&LevelPlayer, f64)> = None; + for p in players.iter().filter(|p| !p.spectator) { + let d = p.distance_sqr(x, y, z); + if best.is_none_or(|(_, b)| d < b) { + best = Some((p, d)); + } + } + best.map(|(p, _)| p) +} + /// The game level as natural spawning reads it. pub(super) struct GameLevel<'g, 'a> { pub(super) game: &'g Game<'a>, pub(super) w: MobWorld<'g>, + /// Every player in the level ([`Game::level_players`]). + pub(super) players: Vec, /// Boxes of the mobs this pass created, not yet in the game's list. pub(super) pending: std::cell::RefCell>, /// The types and boxes of what a spawner created this tick. @@ -35,7 +79,7 @@ pub(super) struct GameLevel<'g, 'a> { impl GameLevel<'_, '_> { fn biome(&self, x: i32, y: i32, z: i32) -> Option<&BiomeInfo> { let chunk = self.game.world.chunks.get(&(x >> 4, z >> 4))?; - Some(self.game.res.biomes.get(chunk.biome(x, y, z))) + Some(self.game.res.biomes().get(chunk.biome(x, y, z))) } } impl SpawnLevel for GameLevel<'_, '_> { @@ -84,8 +128,11 @@ impl SpawnLevel for GameLevel<'_, '_> { fn world_seed(&self) -> i64 { self.w.world_seed } + /// `getNearestPlayer(x, y, z, distance, true)`, over every player. fn player_near(&self, x: f64, y: f64, z: f64, distance: f64) -> bool { - self.w.player_near(x, y, z, distance) + self.players.iter().any(|p| { + p.alive && !p.creative && !p.spectator && p.distance_sqr(x, y, z) < distance * distance + }) } } impl NaturalLevel for GameLevel<'_, '_> { @@ -106,7 +153,7 @@ impl NaturalLevel for GameLevel<'_, '_> { self.game.dim == Dim::Nether } fn mob_type(&self, entity: &str) -> Option<(Species, f32, f32, Category)> { - let t = self.game.res.mob_types.get(entity)?; + let t = self.game.res.mob_types().get(entity)?; Some(( t.species, t.width as f32, @@ -138,12 +185,7 @@ impl NaturalLevel for GameLevel<'_, '_> { StructureSpawns::shared(&self.game.options.resources) } fn nearest_player_distance_sqr(&self, x: f64, y: f64, z: f64) -> Option { - let p = self.game.player.as_ref()?; - if self.game.spectator() { - return None; - } - let d = [p.position.x - x, p.position.y - y, p.position.z - z]; - Some(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]) + nearest_player(&self.players, x, y, z).map(|p| p.distance_sqr(x, y, z)) } fn respawn(&self) -> Option<[i32; 3]> { // The world spawn point lives in the overworld. @@ -184,9 +226,9 @@ impl NaturalLevel for GameLevel<'_, '_> { } fn unobstructed(&self, bounds: Aabb) -> bool { let player = self - .game - .player_view() - .is_some_and(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); + .players + .iter() + .any(|p| p.alive && !p.spectator && p.bounds.intersects(bounds)); !player && !self.pending.borrow().iter().any(|b| b.intersects(bounds)) && !self @@ -198,10 +240,14 @@ impl NaturalLevel for GameLevel<'_, '_> { fn spawn_mobs(&self) -> bool { self.game.ui.rules.bool("spawn_mobs") } - /// Scanned down the column: sections of air alone are skipped (air counts - /// for no heightmap), and an unloaded column reads as air. + /// WORLD_SURFACE (every spawn attempt's) is the chunk's kept heightmap. + /// The others are scanned down the column: sections of air alone are + /// skipped (air counts for no heightmap). An unloaded column reads as air. fn heightmap(&self, kind: Heightmap, x: i32, z: i32) -> i32 { let world = self.w.world; + if kind == Heightmap::WorldSurface { + return self.w.world_surface(x, z); + } world .chunks .get(&(x >> 4, z >> 4)) @@ -217,24 +263,17 @@ impl NaturalLevel for GameLevel<'_, '_> { } } impl horizon_client::mobs::spawner::SpawnerLevel for GameLevel<'_, '_> { + /// `Level.hasNearbyAlivePlayer`, over every player. fn alive_player_near(&self, x: f64, y: f64, z: f64, range: f64) -> bool { - let Some(p) = self.game.player_view() else { - return false; - }; - if !p.alive || p.spectator { - return false; - } - let at = self.game.player.as_ref().map(|p| p.position); - at.is_some_and(|a| { - let d = (a.x - x).powi(2) + (a.y - y).powi(2) + (a.z - z).powi(2); - range < 0.0 || d < range * range + self.players.iter().any(|p| { + p.alive && !p.spectator && (range < 0.0 || p.distance_sqr(x, y, z) < range * range) }) } fn spawner_blocks_work(&self) -> bool { self.game.ui.rules.bool("spawner_blocks_work") } fn entity_exists(&self, id: &str) -> bool { - self.game.res.mob_types.contains_key(id) || self.game.entity_type_exists(id) + self.game.res.mob_types().contains_key(id) || self.game.entity_type_exists(id) } fn count_entities(&self, id: &str, bounds: Aabb) -> usize { let mobs = self @@ -257,6 +296,7 @@ impl<'a> Game<'a> { GameLevel { game: self, w: self.mob_world_base(&[]), + players: self.level_players(), pending: Default::default(), pending_ids: Default::default(), } @@ -264,7 +304,7 @@ impl<'a> Game<'a> { /// Creates a mob the spawner accepted, finalized the game's way; the /// caller adds it with [`Game::add_spawned`]. fn finalize_spawned(&self, r: &SpawnRequest, pending: &mut Vec) -> Option { - let kind = self.res.mob_types.get(r.entity)?.clone(); + let kind = self.res.mob_types().get(r.entity)?.clone(); let [x, y, z] = r.position; let mut mob = Mob::new(0, kind, Vec3::new(x, y, z), r.yaw); let facts = self.biome_facts(x.floor() as i32, y.floor() as i32, z.floor() as i32); @@ -295,25 +335,82 @@ impl<'a> Game<'a> { } } } + /// Every player in the level in place: the local player, and the LAN + /// guests or server players in it. + pub(super) fn level_players(&self) -> Vec { + let mut players: Vec = self.lan.as_ref().map_or_else(Vec::new, |h| { + h.hub + .guests + .iter() + .filter(|g| h.hub.here(g)) + .map(|g| LevelPlayer { + position: Vec3::new(g.position[0], g.position[1], g.position[2]), + bounds: super::lan_mobs::guest_bounds(g), + alive: !g.dead, + creative: g.creative(), + spectator: g.spectator(), + }) + .collect() + }); + if let Some(p) = self.player_view() { + players.insert( + 0, + LevelPlayer { + position: p.position, + bounds: p.bounds, + alive: p.alive, + creative: p.creative, + spectator: p.spectator, + }, + ); + } + players + } + /// `ChunkMap.collectSpawningChunks`: the natural spawn chunk tracker's + /// chunks (within 8 chunks of a player, `getSpawnCandidateChunks`) that + /// are ticking and within 128 blocks of a non-spectator. Also returns how + /// many chunks the tracker holds (`getNaturalSpawnChunkCount`). + pub(super) fn spawning_chunks(&self, players: &[LevelPlayer]) -> (i32, Vec<(i32, i32)>) { + let mut candidates: Vec<(i32, i32)> = Vec::with_capacity(289 * players.len()); + let mut seen = horizon_client::fast_hash::FxHashSet::default(); + for p in players { + let (pcx, pcz) = ( + p.position.x.floor() as i32 >> 4, + p.position.z.floor() as i32 >> 4, + ); + for dx in -8..=8 { + for dz in -8..=8 { + let key = (pcx + dx, pcz + dz); + if seen.insert(key) { + candidates.push(key); + } + } + } + } + let count = candidates.len() as i32; + let levels = self.tickets.levels(); + candidates.retain(|&(cx, cz)| { + levels.loaded_ticking(cx, cz) + && super::ticking_chunk(&self.world, cx, cz) + && players + .iter() + .any(|p| close_enough_for_spawning(p, (cx, cz))) + }); + (count, candidates) + } /// `ServerChunkCache.tickChunks`: the spawn state over the loaded mobs, /// the categories under their global caps (creatures every 400 ticks), - /// then `spawnForChunk` in the shuffled chunks within 128 blocks of the - /// player. + /// then `tickSpawningChunk` in the shuffled spawning chunks of every + /// player: inhabited time, then `spawnForChunk`. pub(super) fn spawn_natural(&mut self) { - let Some(p) = self.player.as_ref().map(|p| p.position) else { + let players = self.level_players(); + if players.is_empty() { return; - }; - let (pcx, pcz) = (p.x.floor() as i32 >> 4, p.z.floor() as i32 >> 4); - // ChunkMap.collectSpawningChunks: tracked chunks whose centre is - // within 128 blocks of a non-spectator. - let spectator = self.spectator(); - let mut chunks: Vec<(i32, i32)> = (-8..=8) - .flat_map(|dx| (-8..=8).map(move |dz| (pcx + dx, pcz + dz))) - .filter(|&(cx, cz)| { - let (x, z) = (f64::from(cx * 16 + 8) - p.x, f64::from(cz * 16 + 8) - p.z); - !spectator && x * x + z * z < 16384.0 && self.world.chunks.contains_key(&(cx, cz)) - }) - .collect(); + } + let (spawnable, mut chunks) = self.spawning_chunks(&players); + for &key in &chunks { + *self.world.inhabited.entry(key).or_insert(0) += 1; + } let spawn_mobs = self.ui.rules.bool("spawn_mobs"); let spawn_enemies = self.ui.rules.bool("spawn_monsters"); let mut random = std::mem::replace(&mut self.world.random, LegacyRandom::new(0)); @@ -335,12 +432,14 @@ impl<'a> Game<'a> { persistent: m.persistent, }) .collect(); - let players = vec![SpawnPlayer { - position: [p.x, p.y, p.z], - spectator, - }]; - // A single player's natural spawn chunk tracker covers 17 x 17 chunks. - let mut state = SpawnState::new(&level, 289, players, &counted, |cx, cz| { + let players = players + .iter() + .map(|p| SpawnPlayer { + position: [p.position.x, p.position.y, p.position.z], + spectator: p.spectator, + }) + .collect(); + let mut state = SpawnState::new(&level, spawnable, players, &counted, |cx, cz| { self.world.chunks.contains_key(&(cx, cz)) }); let categories = if spawn_mobs { diff --git a/crates/horizon-client/src/game/nautili.rs b/crates/horizon-client/src/game/nautili.rs index c039b7d9a..e7f16ca18 100644 --- a/crates/horizon-client/src/game/nautili.rs +++ b/crates/horizon-client/src/game/nautili.rs @@ -11,7 +11,7 @@ use horizon_core::random::RandomSource; impl Game<'_> { fn item_tagged(&self, tag: &str, item: &str) -> bool { self.res - .items + .items() .item_tags .get(tag) .is_some_and(|t| t.contains(item)) @@ -43,7 +43,7 @@ impl Game<'_> { } let taming: Vec = self .res - .items + .items() .item_tags .get("minecraft:nautilus_taming_items") .map(|t| t.iter().cloned().collect()) diff --git a/crates/horizon-client/src/game/nether_portal.rs b/crates/horizon-client/src/game/nether_portal.rs index abfff5b53..a30cf822a 100644 --- a/crates/horizon-client/src/game/nether_portal.rs +++ b/crates/horizon-client/src/game/nether_portal.rs @@ -114,7 +114,7 @@ impl Game<'_> { Dim::Nether }; let state = self.world.block(entry.x, entry.y, entry.z); - let b = &self.res.behaviours; + let b = self.res.behaviours(); let (entry_x_axis, offset) = match b.portal_axis(state) { Some(x_axis) => { let area = largest_rectangle_around( @@ -152,7 +152,7 @@ impl Game<'_> { /// (the points of interest `PortalForcer` searches): loaded chunks as /// they are, the others as saved; chunks never generated have none. fn portal_blocks(&self, center: BlockPos, radius: i32) -> Vec { - let b = &self.res.behaviours; + let b = self.res.behaviours(); let chunk_radius = radius.div_euclid(16) + 1; let (cx, cz) = (center.x >> 4, center.z >> 4); let mut out = Vec::new(); @@ -163,7 +163,7 @@ impl Game<'_> { Some(c) => &**c, None => match self .save - .load(x, z, self.pack.assets.registry, &self.res.biomes) + .load(x, z, self.pack.assets.registry, self.res.biomes()) { Some(c) => { saved = c; @@ -213,7 +213,7 @@ impl Game<'_> { ); if let Some(found) = found { let state = self.world.block(found.x, found.y, found.z); - let x_axis = self.res.behaviours.portal_axis(state).unwrap_or(true); + let x_axis = self.res.behaviours().portal_axis(state).unwrap_or(true); return Some(largest_rectangle_around( found, if x_axis { Axis::X } else { Axis::Z }, @@ -234,7 +234,7 @@ impl Game<'_> { /// `NetherPortalBlock.createDimensionTransition`: the arrival position /// and the yaw turned by. pub(super) fn arrival(&self, plan: &Plan, exit: FoundRectangle) -> (Vec3, f32) { - let b = &self.res.behaviours; + let b = self.res.behaviours(); let corner = exit.min_corner; let exit_x_axis = b .portal_axis(self.world.block(corner.x, corner.y, corner.z)) @@ -298,6 +298,12 @@ impl Game<'_> { else { return Ok(()); }; + self.player_through_nether_portal(entry) + } + /// `Entity.handlePortal` once the player's portal process at `entry` + /// finished: `NetherPortalBlock.getPortalDestination`, then + /// `teleportToPortalDestination` (`isAllowedToEnterPortal`). + pub(super) fn player_through_nether_portal(&mut self, entry: BlockPos) -> Result<()> { let Some(p) = self.player.as_ref() else { return Ok(()); }; @@ -354,10 +360,23 @@ impl Game<'_> { ) -> Result<()> { self.resolve_arrivals(); let plan = self.portals.travel.take(); - let exit = plan.as_ref().and_then(|plan| self.nether_exit_portal(plan)); - let (position, rotation) = match (plan, exit) { - (Some(plan), Some(exit)) => self.arrival(&plan, exit), - _ => (target, 0.0), + let Some(plan) = plan else { + // A command teleport can change dimensions without going through + // a portal. It has no portal placement, rotation, or sound effect. + player.position = target; + player.velocity = Vec3::ZERO; + player.fall_distance = 0.0; + self.previous_position = target; + self.player = Some(player); + self.pad.player_replaced(); + self.sway = Default::default(); + self.apply_equipment(); + return Ok(()); + }; + let exit = self.nether_exit_portal(&plan); + let (position, rotation) = match exit { + Some(exit) => self.arrival(&plan, exit), + None => (target, 0.0), }; player.position = position; // Relative.ROTATION and Relative.DELTA: the yaw turns, the motion @@ -540,7 +559,7 @@ impl Game<'_> { |p, _| { if self .res - .behaviours + .behaviours() .portal_axis(self.world.block(p.x, p.y, p.z)) .is_some() { @@ -584,7 +603,7 @@ impl Game<'_> { for sy in y0..=y1 { y_mask |= 1 << sy; } - let behaviours = &self.res.behaviours; + let behaviours = self.res.behaviours(); let chunks = &self.world.chunks; (x0..=x1).any(|cx| { (z0..=z1).any(|cz| { diff --git a/crates/horizon-client/src/game/options.rs b/crates/horizon-client/src/game/options.rs index d625f938b..12efde5be 100644 --- a/crates/horizon-client/src/game/options.rs +++ b/crates/horizon-client/src/game/options.rs @@ -111,7 +111,7 @@ impl Game<'_> { } pub(super) fn draw_options(&mut self, batch: &mut HudBatch) { let mut ui = std::mem::take(&mut self.ui.options); - ui.draw(&self.settings, batch, &self.atlas, self.cursor); + ui.draw(&self.settings, batch, &self.gui.atlas, self.cursor); self.ui.options = ui; } pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> { @@ -133,7 +133,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.atlas, + &self.gui.atlas, self.cursor.0, self.cursor.1, size, @@ -152,7 +152,7 @@ impl Game<'_> { let mut ui = std::mem::take(&mut self.ui.options); let events = ui.click( &mut self.settings, - &self.atlas, + &self.gui.atlas, self.cursor.0, self.cursor.1, size, @@ -165,7 +165,7 @@ impl Game<'_> { } pub(super) fn options_key(&mut self, key: KeyCode, text: Option<&str>) -> Result<()> { let mut ui = std::mem::take(&mut self.ui.options); - let events = ui.key(&mut self.settings, &self.atlas, key, text); + let events = ui.key(&mut self.settings, &self.gui.atlas, key, text); self.ui.options = ui; self.handle_option_events(events) } @@ -176,7 +176,7 @@ impl Game<'_> { ) -> bool { self.ui .options - .shortcut(&self.atlas, shortcut, &mut self.clipboard) + .shortcut(&self.gui.atlas, shortcut, &mut self.clipboard) } pub(super) fn options_scroll(&mut self, amount: f32) { let size = self.gui_size(); @@ -238,7 +238,7 @@ impl Game<'_> { pub(super) fn load_language(&mut self, code: &str) { let root = self.options.resources.clone(); lang::set(lang::Language::load(&[&root], code)); - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } /// Settings that Horizon applies beyond render distance, volume and GUI scale. pub(super) fn apply_ui_settings(&mut self) { @@ -269,14 +269,14 @@ impl Game<'_> { }; self.ui.chat.options = chat; if rescale { - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } - let font = &mut self.atlas.font; + let font = &mut self.gui.atlas.font; if font.uniform != s.force_unicode || font.japanese != s.japanese_glyphs { font.uniform = s.force_unicode; font.japanese = s.japanese_glyphs; font.reset_cache(); - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); } // A new renderer (resource reload, first window) takes the loaded pack. let stale = self diff --git a/crates/horizon-client/src/game/packs.rs b/crates/horizon-client/src/game/packs.rs index febafc932..0f5a48312 100644 --- a/crates/horizon-client/src/game/packs.rs +++ b/crates/horizon-client/src/game/packs.rs @@ -74,6 +74,15 @@ fn vanilla_info() -> PackInfo { fixed: false, } } +/// Shared by the startup menu, which has no world resources yet. +pub(super) fn pack_infos(vanilla: &Path) -> Vec { + let mut infos: Vec = packs::discover(vanilla, &packs_dir()) + .iter() + .map(info) + .collect(); + infos.push(vanilla_info()); + infos +} impl Game<'_> { fn vanilla_root(&self) -> PathBuf { if self.ui.vanilla_root.as_os_str().is_empty() { @@ -85,9 +94,7 @@ impl Game<'_> { /// The packs the pack screen offers and the current selection /// (`PackSelectionScreen` makes its `PackSelectionModel` from them). pub(super) fn refresh_pack_lists(&mut self) { - let all = packs::discover(&self.vanilla_root(), &packs_dir()); - let mut infos: Vec = all.iter().map(info).collect(); - infos.push(vanilla_info()); + let infos = pack_infos(&self.vanilla_root()); let o = &mut self.ui.options; o.pack_infos = infos; o.pack_selection = self.settings.resource_packs.clone(); @@ -100,6 +107,12 @@ impl Game<'_> { /// particle and font textures), item models, sounds, languages, GUI /// metadata and the cloud and world border textures. pub(super) fn reload_packs(&mut self) { + // Pack reload updates tail-owned mob metadata. Keep menus responsive + // until those resources exist, then apply the latest selection once. + if self.rest_loader.is_some() { + self.pending_pack_reload = true; + return; + } let vanilla = self.vanilla_root(); if self.ui.vanilla_root.as_os_str().is_empty() { self.ui.vanilla_root = vanilla.clone(); @@ -119,14 +132,19 @@ impl Game<'_> { } } fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> { - let assets = std::sync::Arc::new(self.pack.assets.reload(root)?); + let render = std::sync::Arc::new(self.pack.assets.reload(root)?); let mut atlas = HudAtlas::build(root)?; atlas.font.uniform = self.settings.force_unicode; atlas.font.japanese = self.settings.japanese_glyphs; + let gui = super::UiResources { + atlas, + panorama: std::sync::Arc::new(horizon_client::gfx::panorama::Faces::load(root)), + }; let pack = super::PackResources::load( root, - assets, - &self.res.facts, + self.pack.assets.clone(), + render, + self.res.facts(), self.pack.context.biomes.clone(), self.pack.context.light.clone(), )?; @@ -137,7 +155,7 @@ impl Game<'_> { let renderer = match self .window .clone() - .map(|window| self.renderer_for(window, &pack, &atlas)) + .map(|window| self.renderer_for(window, &pack, &gui)) .transpose() { Ok(renderer) => renderer, @@ -158,12 +176,12 @@ impl Game<'_> { self.options.resources = root.to_path_buf(); let context = pack.context.clone(); self.pack = pack; - self.atlas = atlas; + self.gui = gui; horizon_client::ui_theme::reset_atlas(); // Villager hats come from the pack's texture metadata (shared data, swapped in place). *self .res - .mob_data + .mob_data() .villager_hats .write() .unwrap_or_else(std::sync::PoisonError::into_inner) = @@ -179,7 +197,7 @@ impl Game<'_> { self.renderer = Some(renderer); self.apply_ui_settings(); } - self.ui.chat.rescale(&self.atlas); + self.ui.chat.rescale(&self.gui.atlas); Ok(()) } } diff --git a/crates/horizon-client/src/game/pad.rs b/crates/horizon-client/src/game/pad.rs index 0c988c3b7..9a71bdc75 100644 --- a/crates/horizon-client/src/game/pad.rs +++ b/crates/horizon-client/src/game/pad.rs @@ -6,12 +6,12 @@ use super::{Game, Screen}; use horizon_client::{ Result, - gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble, TriggerFeel}, + gamepad::{self, Button, Edges, GlyphStyle, HealthWatch, PadState, Rumble}, keybinds::{KeyBinds, key_code, mouse_button}, mouse::Rotation, }; use serde_json::{Value, json}; -use std::time::{Duration, Instant}; +use std::time::Instant; use winit::{event_loop::ActiveEventLoop, keyboard::KeyCode}; pub(super) const HELP: &[&str] = &[ @@ -25,10 +25,9 @@ pub(super) const HELP: &[&str] = &[ /// The controllers and the state the game last acted on. #[derive(Default)] pub(super) struct Pads { - gilrs: Option, - started: bool, - /// The pad last touched; only its input counts. - active: Option, + /// The real controllers and the DualSense's output. + #[cfg(feature = "controllers")] + devices: hardware::Devices, /// The virtual pad of `horizon-ctl pad`. injected: PadState, /// The virtual pad was in use at the last poll. @@ -48,49 +47,38 @@ pub(super) struct Pads { pub(super) style: GlyphStyle, /// The cursor the pad drives in menus. pub(super) menu: super::pad_menu::MenuCursor, - /// Vibrations playing (an effect stops when dropped) and when they end. - rumbles: Vec<(gilrs::ff::Effect, Instant)>, /// The last vibration asked for, for `pad status`. last_rumble: Option<(&'static str, gamepad::Pulse)>, /// The player's health between polls (a drop is damage taken). health: HealthWatch, - /// The active pad is a DualSense. - dualsense: bool, - /// Its own output over HID (rumble here; gilrs only reads it), started once this window - /// has the pad in hand; dropped, it releases the pad. - output: Option, - /// Its HD haptics, on USB: looked for once each time the output opens. - haptics: Option, - haptics_tried: bool, - /// What it was last told to show. - shown: Option, } -fn gilrs_button(button: Button) -> gilrs::Button { - use gilrs::Button as G; - match button { - Button::South => G::South, - Button::East => G::East, - Button::West => G::West, - Button::North => G::North, - Button::LeftBumper => G::LeftTrigger, - Button::RightBumper => G::RightTrigger, - Button::LeftTrigger => G::LeftTrigger2, - Button::RightTrigger => G::RightTrigger2, - Button::Select => G::Select, - Button::Start => G::Start, - Button::LeftStick => G::LeftThumb, - Button::RightStick => G::RightThumb, - Button::DPadUp => G::DPadUp, - Button::DPadDown => G::DPadDown, - Button::DPadLeft => G::DPadLeft, - Button::DPadRight => G::DPadRight, +#[cfg(feature = "controllers")] +mod hardware; + +/// A build without the `controllers` feature (the server build, which must not need libudev): no +/// hardware pads, only `horizon-ctl pad`'s virtual one. +#[cfg(not(feature = "controllers"))] +mod hardware { + use super::{super::Game, Pads}; + use horizon_client::gamepad::{PadState, Pulse, Rumble}; + use serde_json::{Value, json}; + + impl Pads { + pub(super) fn read(&mut self) -> PadState { + PadState::default() + } } -} -fn is_dualsense(pad: &gilrs::Gamepad) -> bool { - matches!((pad.vendor_id(), pad.product_id()), - (Some(vendor), Some(product)) if horizon_dualsense::is_dualsense(vendor, product)) + impl Game<'_> { + pub(super) fn pad_output_off(&mut self) {} + pub(super) fn pad_output_frame(&mut self) {} + pub(in crate::game) fn pad_close_output(&mut self) {} + pub(super) fn pad_vibrate(&mut self, _: Rumble, _: Pulse) {} + pub(super) fn pad_devices_status(&self) -> Value { + json!({ "backend": false, "controllers": [] }) + } + } } impl Pads { @@ -99,93 +87,6 @@ impl Pads { pub(super) fn player_replaced(&mut self) { self.health.forget(); } - /// Open gilrs on first use. A platform without it (or a Linux without - /// udev) leaves controllers off; the game runs as before. - fn start(&mut self) { - if self.started { - return; - } - self.started = true; - self.gilrs = match gilrs::Gilrs::new() { - Ok(g) => { - for (_, pad) in g.gamepads() { - log::info!("Controller connected: {}", pad.name()); - } - Some(g) - } - Err(gilrs::Error::NotImplemented(_)) => None, - Err(e) => { - log::warn!("Horizon: controllers are unavailable: {e}"); - None - } - }; - } - - /// Drain gilrs' events and read the active pad. - fn read(&mut self) -> PadState { - let Some(gilrs) = self.gilrs.as_mut() else { - return PadState::default(); - }; - while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() { - use gilrs::EventType as E; - match event { - E::Connected => { - log::info!("Controller connected: {}", gilrs.gamepad(id).name()); - if let Some(output) = &self.output { - output.scan(); - } - } - E::Disconnected => { - log::info!("Controller disconnected: {}", gilrs.gamepad(id).name()); - if self.active == Some(id) { - self.active = None; - } - if let Some(output) = &self.output { - output.scan(); - } - } - E::ButtonPressed(..) => self.active = Some(id), - E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _) - if value.abs() > 0.5 => - { - self.active = Some(id) - } - _ => {} - } - } - let Some(pad) = self.active.and_then(|id| gilrs.connected_gamepad(id)) else { - // Before any pad is touched (the virtual pad playing), a DualSense still shows it. - self.dualsense = gilrs.gamepads().any(|(_, pad)| is_dualsense(&pad)); - return PadState::default(); - }; - self.style = GlyphStyle::of_vendor(pad.vendor_id()); - self.dualsense = is_dualsense(&pad); - let mut state = PadState::default(); - for button in Button::ALL { - if !matches!(button, Button::LeftTrigger | Button::RightTrigger) { - state.set(button, pad.is_pressed(gilrs_button(button))); - } - } - let axis = |a| pad.value(a); - use gilrs::Axis as A; - state.left = [axis(A::LeftStickX), axis(A::LeftStickY)]; - state.right = [axis(A::RightStickX), axis(A::RightStickY)]; - // Triggers arrive as analog buttons on most mappings, as plain - // buttons on some. - let trigger = |b: gilrs::Button| { - let value = pad.button_data(b).map_or(0.0, |d| d.value()); - if pad.is_pressed(b) { - value.max(1.0) - } else { - value - } - }; - state.triggers = [ - trigger(gilrs::Button::LeftTrigger2), - trigger(gilrs::Button::RightTrigger2), - ]; - state - } } impl Game<'_> { @@ -193,9 +94,7 @@ impl Game<'_> { pub(super) fn poll_pads(&mut self, event_loop: &ActiveEventLoop) { let settings = &self.settings.controller; if !settings.enabled { - // Dropping the output frees the triggers. - self.pad.output = None; - self.pad.shown = None; + self.pad_output_off(); if self.pad.state != PadState::default() { self.pad.state = PadState::default(); for (button, down) in self.pad.edges.release_all() { @@ -204,7 +103,6 @@ impl Game<'_> { } return; } - self.pad.start(); let hardware = self.pad.read(); self.ui.options.pad_style = self.settings.controller.glyphs.resolve(self.pad.style); let state = hardware.merge(&self.pad.injected); @@ -219,11 +117,7 @@ impl Game<'_> { self.pad.in_use = true; } self.pad.state = state; - if self.pad.dualsense && self.pad.in_use && self.focused && self.pad.output.is_none() { - self.pad.output = Some(horizon_dualsense::Link::start()); - } - self.pad_haptics(); - self.pad_show(); + self.pad_output_frame(); // Damage from any source, here or on a server; nothing counts on // the title screen. let health = self @@ -234,8 +128,6 @@ impl Game<'_> { if let Some(damage) = self.pad.health.observe(health) { self.pad_rumble(Rumble::Hurt(damage)); } - let now = Instant::now(); - self.pad.rumbles.retain(|(_, end)| *end > now); let ticking = self.title.is_none() && self.screen == Screen::Playing && !self.pause; for button in std::mem::take(&mut self.pad.late_releases) { if !ticking || self.pad.pressed_at[button as usize] != Some(self.ticks) { @@ -404,150 +296,8 @@ impl Game<'_> { self.pitch = rotation.x_rot; } - /// The DualSense's HID output, while it is the active pad, open, and this window has focus - /// (another game on the same pad keeps it otherwise). - fn pad_output(&self) -> Option<&horizon_dualsense::Link> { - let output = self.pad.output.as_ref()?; - (self.pad.dualsense && self.focused && output.open().is_some()).then_some(output) - } - - /// What the DualSense shows: while playing, its triggers feel what their actions do; in - /// menus, paused, unfocused or with another pad active, they are free. - fn pad_show(&mut self) { - if self.pad.output.is_none() { - return; - } - let playing = self.pad.dualsense - && self.focused - && self.title.is_none() - && self.screen == Screen::Playing - && !self.pause; - let (using, attacking) = if playing { - self.trigger_feels() - } else { - (TriggerFeel::Free, TriggerFeel::Free) - }; - // The lightbar follows the player; menus keep the last colour. - let in_world = self.title.is_none(); - let lightbar = match self.player.as_mut().filter(|_| in_world) { - Some(p) => { - let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; - let health = p.health.health() / max.max(1.0); - self.settings - .controller - .lightbar - .colour(health, self.dim.id()) - } - None => self.pad.shown.and_then(|s| s.lightbar), - }; - let lights = self.settings.controller.lightbar != gamepad::Lightbar::Off; - let state = horizon_dualsense::device::State { - triggers: self.settings.controller.trigger_effects(using, attacking), - lightbar: lightbar.filter(|_| lights), - player_leds: lights.then_some(horizon_dualsense::PLAYER_1), - }; - if self.pad.shown != Some(state) - && let Some(output) = &self.pad.output - { - output.set(state); - self.pad.shown = Some(state); - } - } - - /// What `key.use` and `key.attack` are doing, for the triggers bound to them. - fn trigger_feels(&self) -> (TriggerFeel, TriggerFeel) { - let using = match self.using { - Some((slot, ticks)) => match self.stack_in(slot) { - Some(s) if &*s.item == "minecraft:bow" => { - TriggerFeel::Draw(gamepad::bow_power(ticks)) - } - // TridentItem.THROW_THRESHOLD_TIME. - Some(s) if &*s.item == "minecraft:trident" => { - TriggerFeel::Draw(ticks as f32 / 10.0) - } - Some(s) if &*s.item == "minecraft:crossbow" => { - TriggerFeel::Draw(ticks as f32 / Self::charge_ticks(s).max(1) as f32) - } - Some(s) if self.blocks_attacks(s).is_some() => TriggerFeel::Brace, - _ => TriggerFeel::Free, - }, - None => self.idle_use_feel(), - }; - // Creative breaks at once; blocks that can't be broken have a negative hardness. - let attacking = match &self.mining { - Some(m) if !self.creative => { - let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); - TriggerFeel::Texture(self.res.facts.get(state).hardness) - } - _ => TriggerFeel::Free, - }; - (using, attacking) - } - - /// The use trigger while nothing is in use: a loaded crossbow clicks, an item that boosts (a - /// rocket while gliding, the stick of the mount being ridden) catches, a shield weighs, and - /// locks while an axe has disabled it. - fn idle_use_feel(&self) -> TriggerFeel { - let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying); - let mount = self - .riding - .and_then(|id| self.mobs.iter().find(|m| m.id == id)); - let mount = mount.map_or("", |m| m.kind.id.as_str()); - let feel = |stack: Option<&horizon_client::items::ItemStack>| match stack - .map(|s| (s, &*s.item)) - { - Some((s, "minecraft:crossbow")) if s.data().is_some_and(|d| !d.charged.is_empty()) => { - TriggerFeel::Click - } - Some((_, "minecraft:firework_rocket")) if gliding => TriggerFeel::Boost, - Some((_, "minecraft:carrot_on_a_stick")) if mount == "minecraft:pig" => { - TriggerFeel::Boost - } - Some((_, "minecraft:warped_fungus_on_a_stick")) if mount == "minecraft:strider" => { - TriggerFeel::Boost - } - Some((s, _)) if self.blocks_attacks(s).is_some() => match self.shield_cooldown { - 0 => TriggerFeel::Brace, - _ => TriggerFeel::Locked, - }, - _ => TriggerFeel::Free, - }; - // Use tries the main hand first. - match feel(self.stack_in(self.selected)) { - TriggerFeel::Free => feel(self.offhand.as_ref()), - main => main, - } - } - - /// Open the pad's haptics once its output is open over USB (its audio device is there - /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until - /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). - fn pad_haptics(&mut self) { - let usb = self.pad.output.as_ref().and_then(|o| o.open()) - == Some(horizon_dualsense::Transport::Usb); - if !usb { - self.pad.haptics = None; - self.pad.haptics_tried = false; - } else if !self.pad.haptics_tried { - self.pad.haptics_tried = true; - if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") - && std::env::var_os("HORIZON_NO_AUDIO").is_none() - { - self.pad.haptics = horizon_dualsense::haptics::Haptics::open(); - } - } - } - - /// Release the DualSense's output (the game is quitting). - pub(super) fn pad_close_output(&mut self) { - self.pad.haptics = None; - self.pad.output = None; - } - /// Vibrate the active pad, when vibration is on and the pad is the one - /// playing (a pad lying idle while the mouse plays stays still): a - /// DualSense through its own report, else gilrs' force feedback, which - /// platforms without it (gilrs on macOS) skip. + /// playing (a pad lying idle while the mouse plays stays still). pub(super) fn pad_rumble(&mut self, rumble: Rumble) { let settings = &self.settings.controller; if !settings.enabled || !settings.vibration || !self.pad.in_use { @@ -557,68 +307,7 @@ impl Game<'_> { return; }; self.pad.last_rumble = Some((rumble.name(), pulse)); - let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - if let Some(haptics) = self - .pad - .haptics - .as_ref() - .filter(|_| self.pad_output().is_some()) - { - let steps = rumble.shape().into_iter().map(|step| { - ( - step.strong, - step.weak, - Duration::from_millis(u64::from(step.millis)), - ) - }); - haptics.play(&steps.collect::>()); - return; - } - if let Some(output) = self.pad_output() { - let steps = rumble.shape().into_iter().map(|step| { - let length = Duration::from_millis(u64::from(step.millis)); - ([level(step.strong), level(step.weak)], length) - }); - output.rumble(steps.collect()); - return; - } - let (Some(gilrs), Some(id)) = (self.pad.gilrs.as_mut(), self.pad.active) else { - return; - }; - if !gilrs - .connected_gamepad(id) - .is_some_and(|g| g.is_ff_supported()) - { - return; - } - use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks}; - let length = Ticks::from_ms(pulse.millis); - let motor = |kind| BaseEffect { - kind, - scheduling: Replay { - play_for: length, - ..Default::default() - }, - envelope: Default::default(), - }; - let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; - let effect = EffectBuilder::new() - .add_effect(motor(BaseEffectType::Strong { - magnitude: magnitude(pulse.strong), - })) - .add_effect(motor(BaseEffectType::Weak { - magnitude: magnitude(pulse.weak), - })) - .repeat(Repeat::For(length)) - .gamepads(&[id]) - .finish(gilrs); - match effect.and_then(|e| e.play().map(|()| e)) { - Ok(effect) => { - let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50); - self.pad.rumbles.push((effect, end)); - } - Err(e) => log::debug!("Horizon: controller vibration: {e}"), - } + self.pad_vibrate(rumble, pulse); } /// `horizon-ctl pad ...`. @@ -639,32 +328,15 @@ impl Game<'_> { }; match arg(1)? { "status" => { - let pads: Vec = self.pad.gilrs.as_ref().map_or(Vec::new(), |g| { - g.gamepads() - .map(|(id, p)| { - json!({ - "name": p.name(), - "vendor": p.vendor_id(), - "product": p.product_id(), - "active": self.pad.active == Some(id), - }) - }) - .collect() - }); let s = &self.pad.state; let held: Vec<&str> = Button::ALL .into_iter() .filter(|b| self.pad.edges.is_held(*b)) .map(Button::name) .collect(); - Ok(json!({ + let mut status = json!({ "enabled": self.settings.controller.enabled, - "backend": self.pad.gilrs.is_some(), - "controllers": pads, "glyphs": self.pad.style.name(), - "dualsense_output": self.pad.output.as_ref().and_then(|o| o.open()) - .map(|t| format!("{t:?}")), - "trigger_effects": self.pad.shown.map(|s| s.triggers), "last_rumble": self.pad.last_rumble.map(|(why, p)| json!({ "reason": why, "strong": p.strong, "weak": p.weak, "ms": p.millis, })), @@ -674,7 +346,13 @@ impl Game<'_> { "left": s.left, "right": s.right, "triggers": s.triggers, - })) + }); + if let (Some(status), Value::Object(devices)) = + (status.as_object_mut(), self.pad_devices_status()) + { + status.extend(devices); + } + Ok(status) } "release" => { self.pad.injected = PadState::default(); diff --git a/crates/horizon-client/src/game/pad/hardware.rs b/crates/horizon-client/src/game/pad/hardware.rs new file mode 100644 index 000000000..b464ef3ee --- /dev/null +++ b/crates/horizon-client/src/game/pad/hardware.rs @@ -0,0 +1,409 @@ +//! The real controllers (the `controllers` feature): gilrs' pads, and the DualSense's own output +//! over HID: its rumble, adaptive triggers, lights and HD haptics. A build without the feature (the +//! server build) has the stub in pad.rs instead, and only `horizon-ctl pad`'s virtual pad. +use super::{ + super::{Game, Screen}, + Pads, +}; +use horizon_client::gamepad::{self, Button, GlyphStyle, PadState, Rumble, TriggerFeel}; +use serde_json::{Value, json}; +use std::time::{Duration, Instant}; + +/// The controllers gilrs sees and the DualSense's output. +#[derive(Default)] +pub(super) struct Devices { + gilrs: Option, + started: bool, + /// The pad last touched; only its input counts. + active: Option, + /// Vibrations playing (an effect stops when dropped) and when they end. + rumbles: Vec<(gilrs::ff::Effect, Instant)>, + /// The active pad is a DualSense. + dualsense: bool, + /// Its own output over HID (rumble here; gilrs only reads it), started once this window + /// has the pad in hand; dropped, it releases the pad. + output: Option, + /// Its HD haptics, on USB: looked for once each time the output opens. + haptics: Option, + haptics_tried: bool, + /// What it was last told to show. + shown: Option, +} + +fn gilrs_button(button: Button) -> gilrs::Button { + use gilrs::Button as G; + match button { + Button::South => G::South, + Button::East => G::East, + Button::West => G::West, + Button::North => G::North, + Button::LeftBumper => G::LeftTrigger, + Button::RightBumper => G::RightTrigger, + Button::LeftTrigger => G::LeftTrigger2, + Button::RightTrigger => G::RightTrigger2, + Button::Select => G::Select, + Button::Start => G::Start, + Button::LeftStick => G::LeftThumb, + Button::RightStick => G::RightThumb, + Button::DPadUp => G::DPadUp, + Button::DPadDown => G::DPadDown, + Button::DPadLeft => G::DPadLeft, + Button::DPadRight => G::DPadRight, + } +} + +fn is_dualsense(pad: &gilrs::Gamepad) -> bool { + matches!((pad.vendor_id(), pad.product_id()), + (Some(vendor), Some(product)) if horizon_dualsense::is_dualsense(vendor, product)) +} + +impl Pads { + /// Open gilrs on first use. A platform without it (or a Linux without + /// udev) leaves controllers off; the game runs as before. + fn start(&mut self) { + if self.devices.started { + return; + } + self.devices.started = true; + self.devices.gilrs = match gilrs::Gilrs::new() { + Ok(g) => { + for (_, pad) in g.gamepads() { + log::info!("Controller connected: {}", pad.name()); + } + Some(g) + } + Err(gilrs::Error::NotImplemented(_)) => None, + Err(e) => { + log::warn!("Horizon: controllers are unavailable: {e}"); + None + } + }; + } + + /// Drain gilrs' events and read the active pad (opening gilrs the first time). + pub(super) fn read(&mut self) -> PadState { + self.start(); + let Some(gilrs) = self.devices.gilrs.as_mut() else { + return PadState::default(); + }; + while let Some(gilrs::Event { id, event, .. }) = gilrs.next_event() { + use gilrs::EventType as E; + match event { + E::Connected => { + log::info!("Controller connected: {}", gilrs.gamepad(id).name()); + if let Some(output) = &self.devices.output { + output.scan(); + } + } + E::Disconnected => { + log::info!("Controller disconnected: {}", gilrs.gamepad(id).name()); + if self.devices.active == Some(id) { + self.devices.active = None; + } + if let Some(output) = &self.devices.output { + output.scan(); + } + } + E::ButtonPressed(..) => self.devices.active = Some(id), + E::AxisChanged(_, value, _) | E::ButtonChanged(_, value, _) + if value.abs() > 0.5 => + { + self.devices.active = Some(id) + } + _ => {} + } + } + let Some(pad) = self + .devices + .active + .and_then(|id| gilrs.connected_gamepad(id)) + else { + // Before any pad is touched (the virtual pad playing), a DualSense still shows it. + self.devices.dualsense = gilrs.gamepads().any(|(_, pad)| is_dualsense(&pad)); + return PadState::default(); + }; + self.style = GlyphStyle::of_vendor(pad.vendor_id()); + self.devices.dualsense = is_dualsense(&pad); + let mut state = PadState::default(); + for button in Button::ALL { + if !matches!(button, Button::LeftTrigger | Button::RightTrigger) { + state.set(button, pad.is_pressed(gilrs_button(button))); + } + } + let axis = |a| pad.value(a); + use gilrs::Axis as A; + state.left = [axis(A::LeftStickX), axis(A::LeftStickY)]; + state.right = [axis(A::RightStickX), axis(A::RightStickY)]; + // Triggers arrive as analog buttons on most mappings, as plain + // buttons on some. + let trigger = |b: gilrs::Button| { + let value = pad.button_data(b).map_or(0.0, |d| d.value()); + if pad.is_pressed(b) { + value.max(1.0) + } else { + value + } + }; + state.triggers = [ + trigger(gilrs::Button::LeftTrigger2), + trigger(gilrs::Button::RightTrigger2), + ]; + state + } +} + +impl Game<'_> { + /// Controllers are turned off: dropping the DualSense's output frees its triggers. + pub(super) fn pad_output_off(&mut self) { + self.pad.devices.output = None; + self.pad.devices.shown = None; + } + + /// After each poll: the DualSense's output opens once this window has the pad in hand, then + /// shows what the game is doing; vibrations that are over stop. + pub(super) fn pad_output_frame(&mut self) { + if self.pad.devices.dualsense + && self.pad.in_use + && self.focused + && self.pad.devices.output.is_none() + { + self.pad.devices.output = Some(horizon_dualsense::Link::start()); + } + self.pad_haptics(); + self.pad_show(); + let now = Instant::now(); + self.pad.devices.rumbles.retain(|(_, end)| *end > now); + } + + /// The DualSense's HID output, while it is the active pad, open, and this window has focus + /// (another game on the same pad keeps it otherwise). + fn pad_output(&self) -> Option<&horizon_dualsense::Link> { + let output = self.pad.devices.output.as_ref()?; + (self.pad.devices.dualsense && self.focused && output.open().is_some()).then_some(output) + } + + /// What the DualSense shows: while playing, its triggers feel what their actions do; in + /// menus, paused, unfocused or with another pad active, they are free. + fn pad_show(&mut self) { + if self.pad.devices.output.is_none() { + return; + } + let playing = self.pad.devices.dualsense + && self.focused + && self.title.is_none() + && self.screen == Screen::Playing + && !self.pause; + let (using, attacking) = if playing { + self.trigger_feels() + } else { + (TriggerFeel::Free, TriggerFeel::Free) + }; + // The lightbar follows the player; menus keep the last colour. + let in_world = self.title.is_none(); + let lightbar = match self.player.as_mut().filter(|_| in_world) { + Some(p) => { + let max = p.attribute("minecraft:max_health").unwrap_or(20.0) as f32; + let health = p.health.health() / max.max(1.0); + self.settings + .controller + .lightbar + .colour(health, self.dim.id()) + } + None => self.pad.devices.shown.and_then(|s| s.lightbar), + }; + let lights = self.settings.controller.lightbar != gamepad::Lightbar::Off; + let state = horizon_dualsense::device::State { + triggers: self.settings.controller.trigger_effects(using, attacking), + lightbar: lightbar.filter(|_| lights), + player_leds: lights.then_some(horizon_dualsense::PLAYER_1), + }; + if self.pad.devices.shown != Some(state) + && let Some(output) = &self.pad.devices.output + { + output.set(state); + self.pad.devices.shown = Some(state); + } + } + + /// What `key.use` and `key.attack` are doing, for the triggers bound to them. + fn trigger_feels(&self) -> (TriggerFeel, TriggerFeel) { + let using = match self.using { + Some((slot, ticks)) => match self.stack_in(slot) { + Some(s) if &*s.item == "minecraft:bow" => { + TriggerFeel::Draw(gamepad::bow_power(ticks)) + } + // TridentItem.THROW_THRESHOLD_TIME. + Some(s) if &*s.item == "minecraft:trident" => { + TriggerFeel::Draw(ticks as f32 / 10.0) + } + Some(s) if &*s.item == "minecraft:crossbow" => { + TriggerFeel::Draw(ticks as f32 / Self::charge_ticks(s).max(1) as f32) + } + Some(s) if self.blocks_attacks(s).is_some() => TriggerFeel::Brace, + _ => TriggerFeel::Free, + }, + None => self.idle_use_feel(), + }; + // Creative breaks at once; blocks that can't be broken have a negative hardness. + let attacking = match &self.mining { + Some(m) if !self.creative => { + let state = self.world.block(m.pos[0], m.pos[1], m.pos[2]); + TriggerFeel::Texture(self.res.facts().get(state).hardness) + } + _ => TriggerFeel::Free, + }; + (using, attacking) + } + + /// The use trigger while nothing is in use: a loaded crossbow clicks, an item that boosts (a + /// rocket while gliding, the stick of the mount being ridden) catches, a shield weighs, and + /// locks while an axe has disabled it. + fn idle_use_feel(&self) -> TriggerFeel { + let gliding = self.player.as_ref().is_some_and(|p| p.fall_flying); + let mount = self + .riding + .and_then(|id| self.mobs.iter().find(|m| m.id == id)); + let mount = mount.map_or("", |m| m.kind.id.as_str()); + let feel = |stack: Option<&horizon_client::items::ItemStack>| match stack + .map(|s| (s, &*s.item)) + { + Some((s, "minecraft:crossbow")) if s.data().is_some_and(|d| !d.charged.is_empty()) => { + TriggerFeel::Click + } + Some((_, "minecraft:firework_rocket")) if gliding => TriggerFeel::Boost, + Some((_, "minecraft:carrot_on_a_stick")) if mount == "minecraft:pig" => { + TriggerFeel::Boost + } + Some((_, "minecraft:warped_fungus_on_a_stick")) if mount == "minecraft:strider" => { + TriggerFeel::Boost + } + Some((s, _)) if self.blocks_attacks(s).is_some() => match self.shield_cooldown { + 0 => TriggerFeel::Brace, + _ => TriggerFeel::Locked, + }, + _ => TriggerFeel::Free, + }; + // Use tries the main hand first. + match feel(self.stack_in(self.selected)) { + TriggerFeel::Free => feel(self.offhand.as_ref()), + main => main, + } + } + + /// Open the pad's haptics once its output is open over USB (its audio device is there + /// only then); close them when it goes. Opt-in with `HORIZON_DUALSENSE_HAPTICS=1` until + /// they are proven on a pad (docs/controllers.md); never for games without sound (tests). + fn pad_haptics(&mut self) { + let usb = self.pad.devices.output.as_ref().and_then(|o| o.open()) + == Some(horizon_dualsense::Transport::Usb); + if !usb { + self.pad.devices.haptics = None; + self.pad.devices.haptics_tried = false; + } else if !self.pad.devices.haptics_tried { + self.pad.devices.haptics_tried = true; + if std::env::var_os("HORIZON_DUALSENSE_HAPTICS").is_some_and(|v| v == "1") + && std::env::var_os("HORIZON_NO_AUDIO").is_none() + { + self.pad.devices.haptics = horizon_dualsense::haptics::Haptics::open(); + } + } + } + + /// Release the DualSense's output (the game is quitting). + pub(in crate::game) fn pad_close_output(&mut self) { + self.pad.devices.haptics = None; + self.pad.devices.output = None; + } + + /// Play a vibration on the active pad: a DualSense through its own report, else gilrs' force + /// feedback, which platforms without it (gilrs on macOS) skip. + pub(super) fn pad_vibrate(&mut self, rumble: Rumble, pulse: gamepad::Pulse) { + let level = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + if let Some(haptics) = self + .pad + .devices + .haptics + .as_ref() + .filter(|_| self.pad_output().is_some()) + { + let steps = rumble.shape().into_iter().map(|step| { + ( + step.strong, + step.weak, + Duration::from_millis(u64::from(step.millis)), + ) + }); + haptics.play(&steps.collect::>()); + return; + } + if let Some(output) = self.pad_output() { + let steps = rumble.shape().into_iter().map(|step| { + let length = Duration::from_millis(u64::from(step.millis)); + ([level(step.strong), level(step.weak)], length) + }); + output.rumble(steps.collect()); + return; + } + let (Some(gilrs), Some(id)) = (self.pad.devices.gilrs.as_mut(), self.pad.devices.active) + else { + return; + }; + if !gilrs + .connected_gamepad(id) + .is_some_and(|g| g.is_ff_supported()) + { + return; + } + use gilrs::ff::{BaseEffect, BaseEffectType, EffectBuilder, Repeat, Replay, Ticks}; + let length = Ticks::from_ms(pulse.millis); + let motor = |kind| BaseEffect { + kind, + scheduling: Replay { + play_for: length, + ..Default::default() + }, + envelope: Default::default(), + }; + let magnitude = |v: f32| (v.clamp(0.0, 1.0) * f32::from(u16::MAX)) as u16; + let effect = EffectBuilder::new() + .add_effect(motor(BaseEffectType::Strong { + magnitude: magnitude(pulse.strong), + })) + .add_effect(motor(BaseEffectType::Weak { + magnitude: magnitude(pulse.weak), + })) + .repeat(Repeat::For(length)) + .gamepads(&[id]) + .finish(gilrs); + match effect.and_then(|e| e.play().map(|()| e)) { + Ok(effect) => { + let end = Instant::now() + Duration::from_millis(u64::from(pulse.millis) + 50); + self.pad.devices.rumbles.push((effect, end)); + } + Err(e) => log::debug!("Horizon: controller vibration: {e}"), + } + } + + /// The hardware part of `pad status`. + pub(super) fn pad_devices_status(&self) -> Value { + let devices = &self.pad.devices; + let pads: Vec = devices.gilrs.as_ref().map_or(Vec::new(), |g| { + g.gamepads() + .map(|(id, p)| { + json!({ + "name": p.name(), + "vendor": p.vendor_id(), + "product": p.product_id(), + "active": devices.active == Some(id), + }) + }) + .collect() + }); + json!({ + "backend": devices.gilrs.is_some(), + "controllers": pads, + "dualsense_output": devices.output.as_ref().and_then(|o| o.open()).map(|t| format!("{t:?}")), + "trigger_effects": devices.shown.map(|s| s.triggers), + }) + } +} diff --git a/crates/horizon-client/src/game/pad_menu.rs b/crates/horizon-client/src/game/pad_menu.rs index 5c623202b..257586572 100644 --- a/crates/horizon-client/src/game/pad_menu.rs +++ b/crates/horizon-client/src/game/pad_menu.rs @@ -939,7 +939,7 @@ impl Game<'_> { } else if self.screen == Screen::Options { let result = match text { Some(t) => { - self.ui.options.type_text(&self.atlas, t); + self.ui.options.type_text(&self.gui.atlas, t); Ok(()) } None => self.options_key(key.expect("a key"), None), @@ -983,7 +983,7 @@ impl Game<'_> { .focus .is_some_and(|f| f.center().1 > batch.height / 2.0) || self.screen == Screen::Chat; - let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor); keyboard.draw(&mut ui, at_top, self.ui.options.pad_style); ui.finish(); return; @@ -998,7 +998,7 @@ impl Game<'_> { return; } // An arrow, outlined, pointing up-left at (x, y). - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (x, y) = (x.floor(), y.floor()); const ROWS: [u8; 10] = [1, 2, 3, 4, 5, 6, 7, 4, 2, 1]; for (i, &w) in ROWS.iter().enumerate() { @@ -1043,7 +1043,7 @@ impl Game<'_> { }; if horizon { use horizon_client::ui_theme::{self as theme, Ui, color}; - let mut ui = Ui::new(&self.atlas, batch, self.cursor); + let mut ui = Ui::new(&self.gui.atlas, batch, self.cursor); let k = ui.batch.scale / ui.density; let (x, y, w, h) = (x * k, y * k, w * k, h * k); let radius = match focus.kind { @@ -1066,7 +1066,7 @@ impl Game<'_> { return; } if matches!(focus.kind, Kind::Row | Kind::Field) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let white = rgba(255, 255, 255, 255); batch.fill(atlas, x, y, w, 1.0, white); batch.fill(atlas, x, y + h - 1.0, w, 1.0, white); diff --git a/crates/horizon-client/src/game/paintings.rs b/crates/horizon-client/src/game/paintings.rs index c65dbbb89..321e59f7d 100644 --- a/crates/horizon-client/src/game/paintings.rs +++ b/crates/horizon-client/src/game/paintings.rs @@ -94,7 +94,7 @@ impl Game<'_> { for x in slo[0].floor() as i32..=shi[0].floor() as i32 { for y in slo[1].floor() as i32..=shi[1].floor() as i32 { for z in slo[2].floor() as i32..=shi[2].floor() as i32 { - let f = self.res.facts.get(self.world.block(x, y, z)); + let f = self.res.facts().get(self.world.block(x, y, z)); if !(f.legacy_solid || f.has_class("DiodeBlock")) { return false; } @@ -232,8 +232,16 @@ impl Game<'_> { } /// BlockAttachedEntity.tick: check survival every 100 ticks. pub(super) fn tick_paintings(&mut self) { + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); let mut i = 0; while i < self.paintings.len() { + let (lo, hi) = self.paintings[i].bounds(); + let centre = [0, 2].map(|k| ((lo[k] + hi[k]) / 2.0).floor() as i32); + if !ticking(centre[0], centre[1]) { + i += 1; + continue; + } self.paintings[i].check_interval += 1; if self.paintings[i].check_interval >= 100 { self.paintings[i].check_interval = 0; @@ -249,7 +257,7 @@ impl Game<'_> { /// PaintingRenderer: the variant on the front, the back texture behind and /// on the edges. pub(super) fn painting_geometry(&self, camera: glam::DVec3, out: &mut Vec) { - let sprites = &self.atlas.sprites; + let sprites = &self.gui.atlas.sprites; let Some(back) = sprites.get("painting/back").copied() else { return; }; diff --git a/crates/horizon-client/src/game/passengers.rs b/crates/horizon-client/src/game/passengers.rs index 27d8a4af6..4e6ba339d 100644 --- a/crates/horizon-client/src/game/passengers.rs +++ b/crates/horizon-client/src/game/passengers.rs @@ -186,9 +186,9 @@ impl Game<'_> { at[2].floor() as i32, ); let frequent = self.world.chunks.get(&(x >> 4, z >> 4)).is_some_and(|c| { - let b = self.res.biomes.get(c.biome(x, y, z)); + let b = self.res.biomes().get(c.biome(x, y, z)); self.res - .mob_data + .mob_data() .biome_has("minecraft:more_frequent_drowned_spawns", &b.name) }); if frequent { diff --git a/crates/horizon-client/src/game/persist.rs b/crates/horizon-client/src/game/persist.rs index 53651dc6c..7a967a024 100644 --- a/crates/horizon-client/src/game/persist.rs +++ b/crates/horizon-client/src/game/persist.rs @@ -105,7 +105,9 @@ impl Game<'_> { chunk.saved = Some(Arc::new(extras)); } /// Register a newly resident chunk with the tick scheduler, with the - /// block and fluid ticks it was saved with. + /// block and fluid ticks it was saved with (`LevelChunk.registerTickContainerInLevel` + /// at FULL). They are unpacked when the chunk starts ticking + /// (`start_ticking_chunks`). pub(super) fn register_chunk_ticks(&mut self, key: (i32, i32)) { let pos = ChunkPos::new(key.0, key.1); let saved = self.world.chunks.get(&key).and_then(|c| c.saved.clone()); @@ -130,9 +132,7 @@ impl Game<'_> { .is_ok() && loaded { - let time = self.world.game_time; - self.block_ticks.blocks.unpack_chunk(pos, time); - self.block_ticks.fluids.unpack_chunk(pos, time); + self.tick_chunks.wait(key); } // The saved list is consumed: later saves take the scheduler's ticks. if loaded && let Some(c) = self.world.chunks.get_mut(&key) { @@ -215,7 +215,7 @@ impl Game<'_> { fall_distance, damage: horizon_client::falling_block::Damage::from_nbt( &tag, - self.res.facts.get(state).name.ends_with("anvil"), + self.res.facts().get(state).name.ends_with("anvil"), ), saved: uuid.map(|u| Box::new((u, tag.clone()))), }); @@ -321,7 +321,7 @@ impl Game<'_> { self.persist.unknown.entry(key).or_default().push(tag); } } - _ if self.res.mob_types.contains_key(&kind) => { + _ if self.res.mob_types().contains_key(&kind) => { self.load_mob(tag, None); } _ if !kind.is_empty() && entity_nbt::position(&tag).is_some() => { @@ -346,7 +346,7 @@ impl Game<'_> { if let Some(Tag::List(list)) = c.remove(&"Passengers".into()) { for p in list { let known = - entity_nbt::kind(&p).is_some_and(|k| self.res.mob_types.contains_key(&k)); + entity_nbt::kind(&p).is_some_and(|k| self.res.mob_types().contains_key(&k)); if known { riders.push(p); } else { @@ -358,7 +358,7 @@ impl Game<'_> { c.insert("Passengers".into(), Tag::List(unknown)); } } - let mut m = entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, self.next_entity)?; + let mut m = entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), self.next_entity)?; m.extra.mount = mount; m.extra.passenger = mount.is_some(); if finalize { diff --git a/crates/horizon-client/src/game/perspective.rs b/crates/horizon-client/src/game/perspective.rs index 4214bdd70..cdc7fa2d8 100644 --- a/crates/horizon-client/src/game/perspective.rs +++ b/crates/horizon-client/src/game/perspective.rs @@ -266,7 +266,7 @@ impl Game<'_> { binding: self.collision, subject: None, }, - facts: &self.res.facts, + facts: self.res.facts(), context, }; view.align_with_entity(&entity, partial, kind, |from, to| { @@ -296,7 +296,7 @@ impl Game<'_> { return; }; if self.player_model.is_none() { - let Some(kind) = self.res.player_type.clone() else { + let Some(kind) = self.res.player_type().clone() else { return; }; self.player_model = Some(Mob::new(0, kind, p.position, self.yaw)); @@ -430,7 +430,7 @@ impl Game<'_> { m.position.z.floor() as i32, ); let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); horizon_client::mobs::render::render_with( m, @@ -438,7 +438,7 @@ impl Game<'_> { camera, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), &self.player_armor_layers(), out, ); @@ -484,7 +484,7 @@ impl Game<'_> { m.position.y += 0.125 * f64::from(u8::from(m.extra.crouching)); m.previous = m.position; let camera = glam::DVec3::new(m.position.x, m.position.y, m.position.z); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); let mut verts = Vec::new(); horizon_client::mobs::render::render_with( @@ -493,7 +493,7 @@ impl Game<'_> { camera, &lookup, 240 | 240 << 8, - &self.res.mob_data, + self.res.mob_data(), &self.player_armor_layers(), &mut verts, ); @@ -546,7 +546,7 @@ impl Game<'_> { ) { let Some(asset) = self.armor[1] .as_ref() - .and_then(|s| self.res.items.get(&s.item)) + .and_then(|s| self.res.items().get(&s.item)) .and_then(|i| i.equip_asset.as_ref()) else { return; @@ -555,9 +555,10 @@ impl Game<'_> { let Some((texture, _)) = assets.equipment.get(asset).and_then(|k| k.get("wings")) else { return; }; - let (Some(model), Some(rect)) = - (assets.player.get("elytra"), self.atlas.sprites.get(texture)) - else { + let (Some(model), Some(rect)) = ( + assets.player.get("elytra"), + self.gui.atlas.sprites.get(texture), + ) else { return; }; let base = horizon_client::mobs::render::base_transform(m, partial, camera) diff --git a/crates/horizon-client/src/game/piglins.rs b/crates/horizon-client/src/game/piglins.rs index 3515b380b..9df5311aa 100644 --- a/crates/horizon-client/src/game/piglins.rs +++ b/crates/horizon-client/src/game/piglins.rs @@ -11,14 +11,18 @@ use horizon_core::random::RandomSource; impl Game<'_> { fn piglin_loved(&self, item: &str) -> bool { self.res - .items + .items() .item_tags .get("minecraft:piglin_loved") .is_some_and(|t| t.contains(item)) } /// `PiglinAi.isWearingSafeArmor`. pub(super) fn wearing_gold(&self) -> bool { - let tag = self.res.items.item_tags.get("minecraft:piglin_safe_armor"); + let tag = self + .res + .items() + .item_tags + .get("minecraft:piglin_safe_armor"); self.armor .iter() .flatten() @@ -119,7 +123,7 @@ impl Game<'_> { let m = &self.mobs[i]; let from = [m.position.x, m.position.y + 1.3, m.position.z]; let items = if &*item == "minecraft:gold_ingot" && !m.is_baby() { - self.res.items.loot_table( + self.res.items().loot_table( "minecraft:gameplay/piglin_bartering", false, None, @@ -191,7 +195,7 @@ impl Game<'_> { ]; !self .res - .facts + .facts() .get(self.world.block( p[0].floor() as i32, p[1].floor() as i32, @@ -203,7 +207,7 @@ impl Game<'_> { /// Whether breaking or opening this block angers piglins. pub(super) fn guarded_by_piglins(&self, name: &str) -> bool { self.res - .items + .items() .block_tags .get("minecraft:guarded_by_piglins") .is_some_and(|t| t.contains(name)) diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index bc4f3b6bc..51cb1fc0a 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -169,7 +169,7 @@ impl Game<'_> { return Ok(false); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if self.res.facts.get(state).fluid != horizon_client::blocks::Fluid::Water { + if self.res.facts().get(state).fluid != horizon_client::blocks::Fluid::Water { return Ok(false); } let at = [ @@ -369,11 +369,11 @@ impl Game<'_> { let armor: Vec> = self.armor.to_vec(); if self.potions.protection_for.as_ref() != Some(&armor) { let mut table = Vec::new(); - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let mut random = horizon_core::random::LegacyRandom::new(0); for (_, def) in self.motion.health.damage.entries() { let ctx = horizon_client::enchant::EffectContext { - items: Some(&self.res.items), + items: Some(self.res.items()), damage_type: Some(&def.name), this: Some("minecraft:player"), ..Default::default() @@ -429,7 +429,7 @@ impl Game<'_> { let state = self.world .block(p.x.floor() as i32, p.y.floor() as i32, p.z.floor() as i32); - if self.res.facts.get(state).full_collision + if self.res.facts().get(state).full_collision || self.mobs.iter().any(|m| { m.alive() && (m.position.x - p.x).abs() < m.kind.width / 2.0 + 0.125 @@ -587,7 +587,7 @@ impl Game<'_> { // `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 undead = &self.res.stations().enchantments.entity_tags; let mut hits = Vec::new(); for (i, m) in self.mobs.iter().enumerate() { let d2 = (m.position.x - at.x).powi(2) @@ -644,7 +644,7 @@ impl Game<'_> { .map(hud_overlays::EffectIcon::from) .collect(); let draws = hud_overlays::effects(batch.width as i32, false, &icons); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// `EffectsInInventory`: panels to the right of survival/creative inventory. pub(super) fn draw_inventory_effects( @@ -660,11 +660,11 @@ impl Game<'_> { &self.potions.effects.list, self.clock.rate(), &|key| self.pack.names.get(key).map(str::to_owned), - &|text| self.atlas.font.width(text).ceil() as i32, + &|text| self.gui.atlas.font.width(text).ceil() as i32, ); if let Some(lines) = inventory_effects::paint( batch, - &self.atlas, + &self.gui.atlas, &panels, [self.cursor.0 as i32, self.cursor.1 as i32], ) { diff --git a/crates/horizon-client/src/game/powder_snow.rs b/crates/horizon-client/src/game/powder_snow.rs index 7d0a7770d..6a904706f 100644 --- a/crates/horizon-client/src/game/powder_snow.rs +++ b/crates/horizon-client/src/game/powder_snow.rs @@ -68,7 +68,7 @@ impl Game<'_> { pub(super) fn is_powder_snow(&self, pos: [i32; 3]) -> bool { &*self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name == "minecraft:powder_snow" diff --git a/crates/horizon-client/src/game/raids.rs b/crates/horizon-client/src/game/raids.rs index 25a440af3..8c31ca25b 100644 --- a/crates/horizon-client/src/game/raids.rs +++ b/crates/horizon-client/src/game/raids.rs @@ -100,7 +100,7 @@ impl RaidLevel for Lvl<'_, '_> { let w = g.mob_world_base(&[]); spawn_rules::is_spawn_position_ok(Species::Ravager, &w, x, y, z) || w.block_name(x, y - 1, z) == "minecraft:snow" - && g.res.facts.is_air(g.world.block(x, y, z)) + && g.res.facts().is_air(g.world.block(x, y, z)) } fn player(&self) -> Option { let p = self.game.player.as_ref()?; @@ -221,7 +221,7 @@ impl Game<'_> { let top = if self.dim == Dim::Nether { 127 } else { 319 }; (horizon_client::chunk::MIN_Y..=top) .rev() - .find(|&y| !self.res.facts.is_air(self.world.block(x, y, z))) + .find(|&y| !self.res.facts().is_air(self.world.block(x, y, z))) .map_or(horizon_client::chunk::MIN_Y, |y| y + 1) } /// Every claimed village point of interest (job sites, beds, bells). @@ -356,7 +356,7 @@ impl Game<'_> { .get(&(at[0] >> 4, at[2] >> 4)) .map(|c| { self.res - .biomes + .biomes() .get(c.biome(at[0], at[1], at[2])) .name .clone() @@ -716,7 +716,7 @@ impl Game<'_> { leader: bool, reason: raider::Reason, ) -> Option { - let t = self.res.mob_types.get(kind).cloned()?; + let t = self.res.mob_types().get(kind).cloned()?; self.next_entity += 1; let mut mob = Mob::new(self.next_entity, t, Vec3::new(at[0], at[1], at[2]), 0.0); if leader { @@ -982,11 +982,11 @@ impl Game<'_> { for z in c[2] - 64..=c[2] + 64 { for x in c[0] - 64..=c[0] + 64 { let state = self.world.block(x, y, z); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { continue; } let bed = *known.entry(state.0).or_insert_with(|| { - self.res.facts.get(state).name.ends_with("_bed") + self.res.facts().get(state).name.ends_with("_bed") && self.pack.assets.registry.state(state).is_some_and(|s| { s.properties.get("part").map(String::as_str) == Some("head") }) @@ -1121,7 +1121,7 @@ impl Game<'_> { pub(super) fn throw_gift(&mut self, table: &str, from: [f64; 3], to: [f64; 3]) { let drops = self .res - .items + .items() .loot_table(table, false, None, &mut self.world.random); let d = Vec3::new(to[0] - from[0], to[1] - from[1], to[2] - from[2]).normalize(); for stack in drops { @@ -1163,7 +1163,7 @@ impl Game<'_> { .get(&(at[0] >> 4, at[2] >> 4)) .map(|c| { game.res - .biomes + .biomes() .get(c.biome(at[0], at[1], at[2])) .name .clone() diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 706c8d73e..843c01476 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -205,7 +205,7 @@ impl Game<'_> { return; } self.ensure_book(); - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let book = self.recipe_ui.book.as_ref(); // SmithingTrimDemoSlotDisplay draws from a random of its own. let mut random = super::dispenser::entity_random(); @@ -224,8 +224,8 @@ impl Game<'_> { }) .or_else(|| index.result(id).map(|r| ItemStack::new(r, 1))) .or_else(|| { - self.res.stations.recipes.trim_demo( - &self.res.stations.enchantments, + self.res.stations().recipes.trim_demo( + &self.res.stations().enchantments, id, &mut |n| { horizon_core::random::RandomSource::next_int_bound( @@ -275,10 +275,10 @@ impl Game<'_> { Kind::Inventory }); let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - banners: &self.res.stations.banners, + 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 { @@ -306,7 +306,7 @@ impl Game<'_> { return; } let known = &self.level.recipe_book.recipes; - let index = &self.res.stations.recipe_index; + let index = &self.res.stations().recipe_index; let ui = &mut self.recipe_ui; match ui.client_known.as_ref() { Some(previous) if previous == known => return, @@ -336,8 +336,8 @@ impl Game<'_> { } fn ensure_book(&mut self) { if self.recipe_ui.book.is_none() { - let mut book = Book::build(&self.res.recipes, &self.res.items); - book.set_display_ids(&self.res.stations.recipe_index); + let mut book = Book::build(self.res.recipes(), self.res.items()); + book.set_display_ids(&self.res.stations().recipe_index); self.recipe_ui.book = Some(book); } if self.recipe_ui.search.is_none() { @@ -497,7 +497,7 @@ impl Game<'_> { && !book.collection_matches(&c.entries, &query, &|stack| { horizon_client::item_tooltip::lines( stack, - self.res.items.get(&stack.item), + self.res.items().get(&stack.item), &|k| self.pack.names.get(k).map(str::to_owned), ) }) @@ -660,7 +660,7 @@ impl Game<'_> { search.focused = true; search.reset_blink(); if !magnifier { - let idx = search.index_at(&self.atlas, cursor.0); + let idx = search.index_at(&self.gui.atlas, cursor.0); search.set_cursor(idx, false); } return true; @@ -895,7 +895,7 @@ impl Game<'_> { ui.client.highlight.insert(e.id); } if e.flags & 1 != 0 - && let Some(id) = self.res.stations.recipe_index.recipe_of_display(e.id) + && let Some(id) = self.res.stations().recipe_index.recipe_of_display(e.id) && !toast.iter().any(|t| t == id) { toast.push(id.to_owned()); @@ -959,7 +959,7 @@ impl Game<'_> { return; }; let ghost = book - .ghost(entry, book_type, grid, fuel_empty, &self.res.items) + .ghost(entry, book_type, grid, fuel_empty, self.res.items()) .into_iter() .map(|g| Ghost { slot: match (g.target, book_type) { @@ -992,7 +992,7 @@ impl Game<'_> { let (bx, by) = self.book_button_pos(book_type, ox, batch); let hover = inside(cursor, bx, by, 20.0, 18.0); batch.sprite( - &self.atlas, + &self.gui.atlas, &sprite(if hover { "button_highlighted" } else { @@ -1040,7 +1040,7 @@ impl Game<'_> { fn draw_book_panel(&mut self, batch: &mut HudBatch, book_type: BookType) { let (xo, yo) = self.book_origin(batch); let cursor = self.cursor; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let search = match self.recipe_ui.search.as_mut() { Some(edit) => { // The box's place, for clicks and typing. @@ -1163,7 +1163,7 @@ impl Game<'_> { let mut tooltip: Option> = None; for d in calls { let start = batch.vertices.len(); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; match &d.call { Call::Blit { x, y, w, h, u, v, .. diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5f888175f..60003cc4f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -94,11 +94,7 @@ pub(super) struct Remote { biome_bits: u8, view_distance: i32, sequence: i32, - last_pos: [f64; 3], - last_rot: (f32, f32), - last_on_ground: bool, - last_collision: bool, - reminder: u32, + position_sender: horizon_client::player_sync::PositionSender, last_input: u8, was_sprinting: bool, carried: Option, @@ -125,6 +121,8 @@ pub(super) struct Remote { health: (f32, i32, f32), game_mode: i32, pub chat: Vec<(String, Instant)>, + /// Lines received since joining, for the control socket's events. + pub chat_received: u64, /// The server's command tree (ClientboundCommandsPacket). pub commands: Option, players: HashMap, @@ -142,6 +140,8 @@ pub(super) struct Remote { profile: u128, destroying: Option<([i32; 3], u8, f32)>, destroy_delay: u32, + input: horizon_client::interaction_input::InteractionInput, + stop_mining: bool, placing: Option<([i32; 3], u64)>, death_message: Option, player_type: Option>, @@ -149,7 +149,12 @@ pub(super) struct Remote { synced: Vec>, decode_errors: u32, clock: Option, + /// `ClientClockManager.ClientClockInstance`'s rate and partial tick for + /// the level's clock (its total is `world.day_time`), and + /// `lastTickGameTime`. clock_rate: f32, + clock_partial: f32, + clock_game_time: i64, /// `ClientChunkCache.Storage`'s view centre (ClientboundSetChunkCacheCenterPacket). chunk_center: (i32, i32), } @@ -179,6 +184,13 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo impl Game<'_> { /// Leave the title for a server (ConnectScreen): an empty world fed by the connection. pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> { + if self.defer_world_entry(super::PendingWorldEntry::Server { + address: address.to_owned(), + name: name.to_owned(), + })? { + return Ok(()); + } + self.join_world_rest()?; if let Err(error) = self.join_server(address, name, None) { log::warn!("Horizon: could not join server: {error}"); if self.title.is_none() { @@ -235,12 +247,12 @@ impl Game<'_> { let mut streaming = Streaming::new( Arc::new(NoTerrain), self.pack.context.clone(), - self.res.threads, + self.res.threads(), ); streaming.remote = true; streaming.radius = self.settings.render_distance; self.streaming = streaming; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.save = Arc::new(SaveDir::new( std::env::temp_dir().join("horizon-remote-unused"), )); @@ -264,6 +276,7 @@ impl Game<'_> { self.container = None; self.carried = None; self.using = None; + self.clicks.miss_time = 0; self.set_mode_id(0); self.experience = Experience { level: 0, @@ -293,11 +306,7 @@ impl Game<'_> { biome_bits: 7, view_distance: self.settings.render_distance, sequence: 0, - last_pos: [0.0; 3], - last_rot: (0.0, 0.0), - last_on_ground: false, - last_collision: false, - reminder: 0, + position_sender: Default::default(), last_input: 0, was_sprinting: false, carried: None, @@ -315,6 +324,7 @@ impl Game<'_> { health: (20.0, 20, 5.0), game_mode: 0, chat: Vec::new(), + chat_received: 0, commands: None, players: HashMap::new(), tab_players: HashMap::new(), @@ -325,6 +335,8 @@ impl Game<'_> { profile: 0, destroying: None, destroy_delay: 0, + input: Default::default(), + stop_mining: false, placing: None, death_message: None, player_type, @@ -332,6 +344,8 @@ impl Game<'_> { decode_errors: 0, clock: None, clock_rate: 1.0, + clock_partial: 0.0, + clock_game_time: 0, chunk_center: (0, 0), }); // The level's TickRateManager follows the server's ticking packets. @@ -369,7 +383,7 @@ impl Game<'_> { self.score.board = Default::default(); self.streaming = Streaming::new(Arc::new(NoTerrain), self.pack.context.clone(), 1); self.streaming.paused = true; - self.world = World::new(self.res.facts.air, 0); + self.world = World::new(self.res.facts().air, 0); self.player = None; self.mobs.clear(); self.clear_remote_objects(); @@ -487,7 +501,7 @@ impl Game<'_> { pub(super) fn chat_line(&mut self, text: String) { log::info!("[chat] {text}"); self.ui.chat.add( - &self.atlas, + &self.gui.atlas, horizon_client::text::Text::literal(text.clone()), None, self.ticks, @@ -495,6 +509,7 @@ impl Game<'_> { ); if let Some(r) = self.remote.as_mut() { r.chat.push((text, Instant::now())); + r.chat_received += 1; if r.chat.len() > 100 { r.chat.remove(0); } @@ -634,7 +649,7 @@ impl Game<'_> { .get("minecraft:worldgen/biome") .map(|list| { list.iter() - .map(|(name, _)| self.res.biomes.id(name)) + .map(|(name, _)| self.res.biomes().id(name)) .collect() }) .unwrap_or_default(); @@ -654,6 +669,8 @@ impl Game<'_> { r.dimension = dimension; r.game_mode = spawn.game_type; r.loaded_sent = false; + // A replacement LocalPlayer has a fresh sendPosition baseline. + r.position_sender = Default::default(); r.predictions.clear(); self.set_mode_id(spawn.game_type); self.dim = Dim::from_id(&spawn.dimension); @@ -661,7 +678,7 @@ impl Game<'_> { let mut streaming = Streaming::new( Arc::new(NoTerrain), self.pack.context.clone(), - self.res.threads, + self.res.threads(), ); streaming.remote = true; streaming.radius = self.streaming.radius; @@ -671,7 +688,7 @@ impl Game<'_> { self.world.day_time, self.world.weather, ); - self.world = World::new(self.res.facts.air, spawn.seed); + self.world = World::new(self.res.facts().air, spawn.seed); self.world.game_time = time; self.world.day_time = day; self.world.weather = weather; @@ -965,7 +982,7 @@ impl Game<'_> { } /// Keep the renderable block entities (chests, furnaces) in step with blocks. fn sync_block_entity(&mut self, pos: (i32, i32, i32), state: BlockStateId) { - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); match BlockEntity::for_block(&name) { Some(entity) => { let same = self @@ -1028,9 +1045,9 @@ impl Game<'_> { // A block we just placed: play its place sound (the server skips the placer). if let Some((target, _)) = self.remote.as_ref().and_then(|r| r.placing) && target == pos - && !self.res.facts.is_air(state) + && !self.res.facts().is_air(state) { - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, @@ -1051,7 +1068,7 @@ impl Game<'_> { 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() + self.res.mob_types().get(kind).cloned() }; if kind == "minecraft:experience_orb" { // Its value (ExperienceOrb.DATA_VALUE) follows in SetEntityData. @@ -1138,14 +1155,16 @@ impl Game<'_> { /// Map a menu slot to Horizon's inventory screen slot ids. fn menu_slot(menu: &str, slot: i32) -> Option { let s = usize::try_from(slot).ok()?; - let rows = |n: usize| -> Option { + // A container of `n` slots, then the inventory and the hotbar. + let slots = |n: usize| -> Option { match s { - _ if s < n * 9 => Some(300 + s), - _ if s < n * 9 + 27 => Some(9 + s - n * 9), - _ if s < n * 9 + 36 => Some(s - n * 9 - 27), + _ if s < n => Some(300 + s), + _ if s < n + 27 => Some(9 + s - n), + _ if s < n + 36 => Some(s - n - 27), _ => None, } }; + let rows = |n: usize| slots(n * 9); match menu { "inventory" => match s { 0 => Some(200), @@ -1183,6 +1202,10 @@ impl Game<'_> { "minecraft:generic_9x4" => rows(4), "minecraft:generic_9x5" => rows(5), "minecraft:generic_9x6" => rows(6), + // HopperMenu; DispenserMenu (dispensers and droppers). + "minecraft:hopper" => slots(5), + "minecraft:generic_3x3" => slots(9), + "minecraft:brewing_stand" => slots(5), _ => None, } } @@ -1208,6 +1231,9 @@ impl Game<'_> { fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { + // ClientCommonPacketListenerImpl.handlePing runs on the game + // thread, after all preceding packets (especially teleports). + C::Ping(p) => self.send(S::Pong(p)), // PingDebugMonitor.onPongReceived. C::PongResponse(p) => { let delay = self.debug_millis() - p.time; @@ -1323,7 +1349,7 @@ impl Game<'_> { // shulker boxes, bells) when the block is still the one it names. C::BlockEvent(p) => { let state = self.world.block(p.pos[0], p.pos[1], p.pos[2]); - let block = &self.res.facts.get(state).name; + let block = &self.res.facts().get(state).name; let named = self.remote.as_ref().and_then(|r| { r.builtin .get("minecraft:block")? @@ -1337,10 +1363,13 @@ impl Game<'_> { C::LevelEvent(p) if p.kind == 2015 => { self.dragon_egg_particles(p.pos, p.data); } + C::LevelEvent(p) if p.kind == 2017 => { + self.consume_teleport_particles(p.pos, p.data); + } C::LevelEvent(p) if p.kind == 2001 => { // LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block. let state = BlockStateId(p.data.max(0) as u32); - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(p.pos[0]) + 0.5, f64::from(p.pos[1]) + 0.5, @@ -1486,6 +1515,25 @@ impl Game<'_> { } } } + // LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS): + // another player starts using the item in a hand (eating, a + // bow drawn, a shield up), or stops. + let other = self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&p.id) && r.entity_id != p.id); + if other && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + for (index, _, value) in &p.values { + if let (8, Value::Byte(flags)) = (index, value) { + m.extra.using_off_hand = flags & 2 != 0; + if flags & 1 == 0 { + m.extra.using_item = 0; + } else if m.extra.using_item == 0 { + m.extra.using_item = 1; + } + } + } + } // 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) { @@ -1498,6 +1546,20 @@ impl Game<'_> { } } } + // Entity.DATA_SHARED_FLAGS_ID's crouching bit: another + // player's crouch (their model and Entity.isDiscrete's name tag). + if self + .remote + .as_ref() + .is_some_and(|r| r.level_players.contains_key(&p.id)) + && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) + { + for (index, _, value) in &p.values { + if let (0, Value::Byte(flags)) = (index, value) { + m.extra.crouching = flags & 2 != 0; + } + } + } for (index, _, value) in &p.values { if *index == ITEM_ENTITY_ITEM && let Value::Item(stack) = value @@ -1580,6 +1642,15 @@ impl Game<'_> { pl.velocity = Vec3::new(p.velocity[0], p.velocity[1], p.velocity[2]); } } + // ClientPacketListener.handleDamageEvent: LivingEntity.handleDamageEvent + // jolts the walk animation and restarts the hurt flash. Its hurt + // sound comes as a sound from Horizon's host, which plays it itself. + C::DamageEvent(p) => { + if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.limb_speed = 1.5; + m.hurt_time = 10; + } + } C::HurtAnimation(p) => { if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { m.hurt_time = 10; @@ -1607,6 +1678,21 @@ impl Game<'_> { } } C::Animate(p) => self.remote_animate(p.id, p.action), + // ClientPacketListener.handleSwingAnimation: the entity swings + // (LivingEntity.swing, which a swing in its first half ignores). + C::SwingAnimation(p) => { + use horizon_client::first_person::Hand; + let hand = if p.hand == 1 { Hand::Off } else { Hand::Main }; + let animation = horizon_client::first_person::SwingAnimation { + kind: p.kind.clamp(0, 255) as u8, + duration: p.duration, + }; + if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) { + self.swing_hand(hand, animation); + } else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) { + m.swing(); + } + } C::UpdateMobEffect(p) => self.remote_effect(&p), C::RemoveMobEffect(p) => { if self.remote.as_ref().is_some_and(|r| r.entity_id == p.id) @@ -1656,8 +1742,12 @@ impl Game<'_> { total: p.total, } } + // ClientPacketListener.handleSetTime: the game time, then + // ClientClockManager.handleUpdates: the clock catches up with the + // game time and takes the server's state. C::SetTime(p) => { self.world.game_time = p.game_time; + self.remote_clock_tick(); let clock = { let r = self.remote.as_ref(); let names = @@ -1678,6 +1768,7 @@ impl Game<'_> { if let Some(r) = self.remote.as_mut() { r.clock = Some(c.clock); r.clock_rate = c.rate; + r.clock_partial = c.partial_tick; } } } @@ -1722,7 +1813,12 @@ impl Game<'_> { } _ => {} }, - C::PlayerAbilities(p) => self.creative = p.flags & 8 != 0, + C::PlayerAbilities(p) => { + self.creative = p.flags & 8 != 0; + if let Some(player) = &mut self.player { + player.flying_speed = p.flying_speed; + } + } C::SetHeldSlot(p) => { self.selected = p.slot.clamp(0, 8) as usize; if let Some(r) = self.remote.as_mut() { @@ -1761,17 +1857,27 @@ impl Game<'_> { self.remote_synced(); } C::ContainerSetData(p) => { - if let Some(key) = self.container - && let Some(BlockEntity::Furnace(f)) = self.world.block_entities.get_mut(&key) + let v = i32::from(p.value); + match self + .container + .and_then(|key| self.world.block_entities.get_mut(&key)) { - let v = i32::from(p.value); - match p.id { + Some(BlockEntity::Furnace(f)) => match p.id { 0 => f.lit_remaining = v, 1 => f.lit_total = v, 2 => f.cooking_timer = v, 3 => f.cooking_total = v, _ => {} - } + }, + // BrewingStandBlockEntity.dataAccess. + Some(BlockEntity::Brewing(b)) => match p.id { + 0 => b.brew_time = v, + 1 => b.fuel = v, + 2 => b.total_brew_time = v, + 3 => b.total_fuel = v, + _ => {} + }, + _ => {} } } C::OpenScreen(p) => self.remote_open_screen(p), @@ -2189,10 +2295,11 @@ impl Game<'_> { self.skin_slots.len() } else { let (old, slot) = self.skin_slots.remove(0); - self.atlas.sprites.remove(&old); + self.gui.atlas.sprites.remove(&old); slot }; let Some(rect) = self + .gui .atlas .sprites .get(&format!("horizon/skin{slot}")) @@ -2200,7 +2307,7 @@ impl Game<'_> { else { return; }; - let (w, h) = (self.atlas.width as f32, self.atlas.height as f32); + let (w, h) = (self.gui.atlas.width as f32, self.gui.atlas.height as f32); self.map_patches.push(horizon_client::font::Patch { x: (rect.u0 * w).round() as u32, y: (rect.v0 * h).round() as u32, @@ -2208,7 +2315,7 @@ impl Game<'_> { height: 64, rgba, }); - self.atlas.sprites.insert(location.clone(), rect); + self.gui.atlas.sprites.insert(location.clone(), rect); self.skin_slots.push((location, slot)); } /// Whether a downloaded skin is in the atlas, marking it recently shown. @@ -2331,10 +2438,11 @@ impl Game<'_> { p.pitch }) .clamp(-90.0, 90.0); - let delta = Vec3::new( - pick(rel::DELTA_X, velocity.x, p.delta[0]), - pick(rel::DELTA_Y, velocity.y, p.delta[1]), - pick(rel::DELTA_Z, velocity.z, p.delta[2]), + let delta = horizon_client::player_sync::teleport_velocity( + velocity, + (self.yaw, self.pitch), + (yaw, pitch), + p, ); match self.player.as_mut() { Some(player) => { @@ -2357,8 +2465,8 @@ impl Game<'_> { self.yaw = yaw; self.pitch = pitch; if let Some(r) = self.remote.as_mut() { - r.last_pos = [position.x, position.y, position.z]; - r.last_rot = (yaw, pitch); + // handleMovePlayer does not change LocalPlayer.sendPosition's + // baseline: the next tick must still report the corrected state. r.destroying = None; } self.mining = None; @@ -2375,6 +2483,16 @@ impl Game<'_> { /// One client tick while connected (Minecraft.tick with a ClientLevel). pub(super) fn tick_remote(&mut self) -> Result<()> { + self.tick_remote_level()?; + // Minecraft.tick sends this even when the player cannot tick yet, + // including while waiting for chunks. Keep it outside early returns. + if self.remote.as_ref().is_some_and(|r| r.joined) { + self.send(S::ClientTickEnd(Empty)); + } + Ok(()) + } + + fn tick_remote_level(&mut self) -> Result<()> { self.ticks += 1; // Options.broadcastOptions: a changed render distance is sent again. let view = client_view_distance(self.settings.render_distance); @@ -2387,15 +2505,12 @@ impl Game<'_> { horizon_protocol::packets::configuration::ClientInformation::new(view), )); } - // Minecraft.tick: TickRateManager.tick; ClientLevel.tick advances + // Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances // the time only while the level runs normally. let running = self.clock.world_runs(); if running { self.world.game_time += 1; - let rate = self.remote.as_ref().map_or(1.0, |r| r.clock_rate); - if rate > 0.0 { - self.world.day_time += rate.round() as i64; - } + self.remote_clock_tick(); } // Weather levels drift toward their targets between server updates. let w = &mut self.world.weather; @@ -2404,6 +2519,10 @@ impl Game<'_> { if self.use_delay > 0 { self.use_delay -= 1; } + // Minecraft.handleKeybinds precedes entity ticking and sendChanges. + // Window callbacks only queue clicks, so an interaction cannot leak + // between CLIENT_TICK_END and a later pong. + self.remote_handle_input(); // ClientLevel.tick: the border's size change. self.border.tick(); self.tick_remote_entities(running); @@ -2426,6 +2545,15 @@ impl Game<'_> { (player.position.z.floor() as i32) >> 4, ); if !self.streaming.is_lit(cx, cz) { + // LocalPlayer.tick can wait for chunks, but Minecraft.tick still + // calls sendChanges: rotations and the 20-tick position reminder + // must continue, as well as moves into the unloaded area. + if let Some(r) = self.remote.as_ref() + && r.loaded_sent + { + let input = r.last_input; + self.remote_send_state(input); + } return Ok(()); } if self.remote.as_ref().is_some_and(|r| !r.loaded_sent) { @@ -2498,7 +2626,7 @@ impl Game<'_> { horizon_client::motion::MotionEvent::Emission { state, in_water, .. } if !crouching => { - let sounds = self.res.facts.get(state).sounds.clone(); + let sounds = self.res.facts().get(state).sounds.clone(); // Player.playStepSound: muffled under the swim sound in water. let (volume, pitch) = if in_water { (sounds.volume * 0.05, sounds.pitch * 0.8) @@ -2520,16 +2648,9 @@ impl Game<'_> { // The player's own model (third person, the inventory's preview). self.tick_player_model(); if !dead { - self.remote_mining(); - // 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 @@ -2605,6 +2726,7 @@ impl Game<'_> { let mut lerps = std::mem::take(&mut r.lerps); let head_lerps = &mut r.head_lerps; let players = &r.level_players; + let mut using = Vec::new(); for m in &mut self.mobs { let player = players.contains_key(&(m.id as i32)); if !running && !player { @@ -2629,6 +2751,9 @@ impl Game<'_> { if !m.alive() { m.death_time += 1; } + // LivingEntity.updateSwingTime. + m.anim.attack_anim_o = m.anim.attack_anim; + horizon_client::mobs::ai::tick_swing(m); // Entity.commonTick: LinearInterpolationHandler.interpolate. if let Some(l) = lerps.get_mut(&(m.id as i32)) && l.steps > 0 @@ -2653,6 +2778,28 @@ impl Game<'_> { m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32; *steps -= 1; } + // LivingEntity.updatingUsingItem for another player: the ticks the + // item has been used before this one. + if player && m.extra.using_item > 0 { + let item = if m.extra.using_off_hand { + m.extra.off_hand.clone() + } else { + m.extra.main_hand.clone() + }; + if let Some(item) = item { + let eye = if m.extra.crouching { 1.27 } else { 1.62 }; + let at = [m.position.x, m.position.y, m.position.z]; + using.push(( + item, + m.extra.using_item as u32 - 1, + at, + eye, + m.head_pitch, + m.yaw, + )); + } + m.extra.using_item += 1; + } // LivingEntity.tick's tickHeadTurn: a mob's BodyRotationControl, // a player's body following its walk and look. if player { @@ -2700,6 +2847,9 @@ impl Game<'_> { } } head_lerps.retain(|_, (_, steps)| *steps > 0); + for (item, ticks, at, eye, pitch, yaw) in using { + self.remote_player_eating(&item, ticks, at, eye, pitch, yaw); + } if running { // Boats, minecarts, armor stands, projectiles and the rest // interpolate like mobs. @@ -2725,6 +2875,47 @@ impl Game<'_> { } } } + /// `Consumable.onConsumeTick` for another player using a consumable: the + /// crumbs at their mouth every 4 ticks once 21.875% of its use has passed + /// (`shouldEmitParticlesAndSounds`; the sounds come from the server). + fn remote_player_eating( + &mut self, + item: &str, + ticks: u32, + at: [f64; 3], + eye: f64, + pitch: f32, + yaw: f32, + ) { + let Some(consumable) = self + .res + .items() + .get(item) + .and_then(|i| i.consumable.as_ref()) + .filter(|c| c.particles) + else { + return; + }; + let duration = consumable.ticks().max(0) as u32; + let remaining = duration - ticks.min(duration); + if !consumable.should_emit(remaining as i32) { + return; + } + let options = self.item_particle(&ItemStack::new(item, 1)); + let mut spawned = Vec::new(); + horizon_client::particles::item_use_particles( + &mut self.world.random, + pitch, + yaw, + at, + at[1] + eye, + 5, + |p, v| spawned.push((p, v)), + ); + for (p, v) in spawned { + self.particles.add(&options, p, v); + } + } /// LocalPlayer.sendPosition plus input, sprint and held-slot updates. fn remote_send_state(&mut self, input: u8) { let Some(p) = self.player.as_ref() else { @@ -2759,41 +2950,12 @@ impl Game<'_> { data: 0, })); } - r.reminder += 1; - let d = [ - pos[0] - r.last_pos[0], - pos[1] - r.last_pos[1], - pos[2] - r.last_pos[2], - ]; - let moved = d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || r.reminder >= 20; - let rotated = yaw != r.last_rot.0 || pitch != r.last_rot.1; - let flags = u8::from(on_ground) | u8::from(collision) << 1; - let [x, y, z] = pos; - if moved && rotated { - out.push(S::MovePlayerPosRot(play::MovePlayerPosRot { - x, - y, - z, - yaw, - pitch, - flags, - })); - } else if moved { - out.push(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })); - } else if rotated { - out.push(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })); - } else if r.last_on_ground != on_ground || r.last_collision != collision { - out.push(S::MovePlayerStatus(play::MovePlayerStatus { flags })); + if let Some(packet) = r + .position_sender + .update(pos, (yaw, pitch), on_ground, collision) + { + out.push(packet); } - if moved { - r.last_pos = pos; - r.reminder = 0; - } - if rotated { - r.last_rot = (yaw, pitch); - } - r.last_on_ground = on_ground; - r.last_collision = collision; // Creative inventory edits are sent slot by slot (SetCreativeModeSlot). let mut creative_slots = Vec::new(); if self.creative { @@ -2836,16 +2998,12 @@ impl Game<'_> { } /// MultiPlayerGameMode.startDestroyBlock / continueDestroyBlock. - fn remote_mining(&mut self) { + fn remote_mining(&mut self, start: bool) { let Some(r) = self.remote.as_mut() else { return; }; - if r.destroy_delay > 0 { + if !start && r.destroy_delay > 0 { r.destroy_delay -= 1; - } - if !self.left || self.screen != Screen::Playing { - self.stop_remote_mining(); - self.mining = None; return; } let Some(hit) = self.pick() else { @@ -2854,14 +3012,9 @@ impl Game<'_> { }; let face = face_direction(hit.face); let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if self.res.facts.is_air(state) { + if self.res.facts().is_air(state) { return; } - if self.remote.as_ref().is_some_and(|r| r.destroy_delay > 0) { - return; - } - self.swing_arm(); - self.send(S::Punch(Empty)); if self.creative { let seq = self.next_sequence(); self.predict_break(hit.pos, state, seq); @@ -2876,14 +3029,17 @@ impl Game<'_> { } return; } - let facts = self.res.facts.get(state).clone(); + let facts = self.res.facts().get(state).clone(); let held = self.held().cloned(); - let mut speed = self.res.items.mining_speed(held.as_ref(), &facts.name); + let mut speed = self.res.items().mining_speed(held.as_ref(), &facts.name); if self.player.as_ref().is_some_and(|p| !p.ground.on_ground) { speed /= 5.0; } - let harvest = - !facts.requires_tool || self.res.items.correct_for_drops(held.as_ref(), &facts.name); + let harvest = !facts.requires_tool + || self + .res + .items() + .correct_for_drops(held.as_ref(), &facts.name); let progress = if facts.hardness < 0.0 { 0.0 } else if facts.hardness == 0.0 { @@ -2896,6 +3052,9 @@ impl Game<'_> { .as_ref() .and_then(|r| r.destroying) .is_some_and(|(p, _, _)| p == hit.pos); + if start && same { + return; + } if !same { if let Some((old, _, _)) = self.remote.as_mut().and_then(|r| r.destroying.take()) { self.send(S::PlayerAction(play::PlayerAction { @@ -2990,7 +3149,7 @@ impl Game<'_> { .and_modify(|p| p.0 = sequence) .or_insert((sequence, state.0 as i32)); } - let s = self.res.facts.get(state).sounds.clone(); + let s = self.res.facts().get(state).sounds.clone(); let at = [ f64::from(pos[0]) + 0.5, f64::from(pos[1]) + 0.5, @@ -3010,15 +3169,25 @@ impl Game<'_> { } self.mining = None; } - /// Minecraft.startUseItem: use on the targeted block, then the item itself. + /// Minecraft.startUseItem: use one crosshair target, then the item itself. fn remote_use(&mut self) { - let held_block = self - .held() - .and_then(|h| self.res.items.get(&h.item)) - .is_some_and(|i| i.block.is_some()); + // Minecraft.startUseItem returns before resetting rightClickDelay + // while a survival block break is active. + if self.remote.as_ref().is_some_and(|r| r.destroying.is_some()) { + return; + } + self.use_delay = 4; + // Resolve the crosshair once. A passing entity interaction keeps + // that target and may only fall back to using the item itself. + let entity = self.entity_targeted(); + horizon_client::interaction_input::use_on_target(&mut RemoteUseWorld(self), entity); + } + + fn remote_use_entity(&mut self) -> bool { let sneaking = self.keys.contains(&KeyCode::ShiftLeft); - // Entities first (interact), like the hit result order. - if let Some((i, _)) = self.mob_hit() { + if let Some((i, distance)) = self.mob_hit() + && self.before_block(distance) + { let id = self.mobs[i].id as i32; self.send(S::Interact(play::Interact { id, @@ -3034,9 +3203,17 @@ impl Game<'_> { .is_some_and(|r| r.level_players.contains_key(&id)); if !player { self.swing_arm(); - return; + return true; } } + false + } + + fn remote_use_block(&mut self) -> bool { + let held_block = self + .held() + .and_then(|h| self.res.items().get(&h.item)) + .is_some_and(|i| i.block.is_some()); if let Some(hit) = self.pick() { let seq = self.next_sequence(); let cursor = [ @@ -3065,9 +3242,13 @@ impl Game<'_> { } if held_block { self.swing_arm(); - return; + return true; } } + false + } + + fn remote_use_item(&mut self) { if let Some(held) = self.held().cloned() { let seq = self.next_sequence(); self.send(S::UseItem(play::UseItem { @@ -3078,12 +3259,12 @@ impl Game<'_> { })); // MultiPlayerGameMode.useItem runs the use here too: food starts // being eaten (Consumable.startConsuming). - if let Some(info) = self.res.items.get(&held.item).cloned() { + if let Some(info) = self.res.items().get(&held.item).cloned() { self.start_eating(&info); } } } - /// `LivingEntity.updatingUsingItem` for food on a server client: the + /// `LivingEntity.updatingUsingItem` for a consumable 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) { @@ -3091,77 +3272,169 @@ impl Game<'_> { return; }; let stack = self.stack_in(slot).cloned(); - let food = stack + let consumable = 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 { + .and_then(|s| self.res.items().get(&s.item)) + .and_then(|i| i.consumable.clone()); + let (Some(stack), Some(consumable)) = (stack, consumable) else { self.using = None; return; }; - if !self.right || slot != self.selected || self.screen != Screen::Playing { + // Button release belongs to the next handleKeybinds phase, which + // sends RELEASE_USE_ITEM. Do not silently clear a use begun by a + // quick press/release between ticks. + if slot != self.selected { self.using = None; return; } // Consumable.shouldEmitParticlesAndSounds, as in tick_used_item. - let duration = 32; + let duration = consumable.ticks().max(0) as u32; let remaining = duration - ticks.min(duration); - if duration - remaining > (duration as f32 * 0.21875) as u32 && remaining % 4 == 0 { + if consumable.particles && consumable.should_emit(remaining as i32) { self.eat_particles(&stack, 5); } if ticks + 1 >= duration { self.using = None; - self.eat_particles(&stack, 16); + if consumable.particles { + self.eat_particles(&stack, 16); + } } else { self.using = Some((slot, ticks + 1)); } } - /// Left click: attack the targeted entity (MultiPlayerGameMode.attack). + /// MouseHandler updates KeyMapping; handleKeybinds sends packets on a tick. pub(super) fn remote_mouse(&mut self, button: MouseButton, pressed: bool) -> Result<()> { - if self.screen == Screen::Chat { - return Ok(()); - } - match button { + use horizon_client::interaction_input::Button; + let input = match button { MouseButton::Left => { - if pressed && let Some((i, _)) = self.mob_hit() { - let id = self.mobs[i].id as i32; - self.send(S::Attack(play::Attack { id })); - self.send(S::Punch(Empty)); - self.swing_arm(); - return Ok(()); - } - if pressed && self.pick().is_none() { - self.send(S::Punch(Empty)); - self.swing_arm(); - } - self.left = pressed; + self.toggles + .button(2, pressed, false, self.settings.toggle_attack); + self.left = self.toggles.is_down(2); + Some(Button::Attack) } MouseButton::Right => { - self.right = pressed; - if pressed { - self.remote_use(); - self.use_delay = 4; - } else { - self.send(S::PlayerAction(play::PlayerAction { - action: 6, - pos: [0; 3], - direction: 0, - sequence: 0, - })); - } + self.toggles + .button(3, pressed, false, self.settings.toggle_use); + self.right = self.toggles.is_down(3); + Some(Button::Use) } - MouseButton::Middle if pressed => { - if let Some(hit) = self.pick() { - self.send(S::PickItemFromBlock(play::PickItemFromBlock { - pos: hit.pos, - include_data: self.has_control_down(), - })); - } - } - _ => {} + MouseButton::Middle => Some(Button::Pick), + _ => None, + }; + if pressed + && let Some(button) = input + && let Some(remote) = self.remote.as_mut() + { + remote.input.press(button); } Ok(()) } + + pub(super) fn request_remote_mining_stop(&mut self) { + if let Some(r) = self.remote.as_mut() { + r.stop_mining = true; + } + } + + fn remote_handle_input(&mut self) { + let Some(r) = self.remote.as_mut() else { + return; + }; + let mut input = std::mem::take(&mut r.input); + let stop = std::mem::take(&mut r.stop_mining); + let ready = r.loaded_sent && self.screen == Screen::Playing && self.sleeping.is_none(); + if stop || !ready { + self.stop_remote_mining(); + } + if !ready { + return; + } + // MultiPlayerGameMode.tick syncs the carried slot before keybinds. + let carried_changed = self.remote.as_mut().is_some_and(|r| { + if r.carried == Some(self.selected) { + false + } else { + r.carried = Some(self.selected); + true + } + }); + if carried_changed { + self.send(S::SetCarriedItem(play::SetCarriedItem { + slot: self.selected as i16, + })); + } + let (attack, use_item) = (self.left, self.right); + input.tick(&mut RemoteInputWorld(self), attack, use_item); + if self.clicks.miss_time > 0 { + self.clicks.miss_time -= 1; + } + if let Some(r) = self.remote.as_mut() { + r.input = input; + } + } + + fn remote_start_attack(&mut self) -> bool { + if self.clicks.miss_time > 0 { + return false; + } + if self.spectator() { + return true; + } + let mut instant = false; + if let Some((i, distance)) = self.mob_hit() + && self.before_block(distance) + { + self.send(S::Attack(play::Attack { + id: self.mobs[i].id as i32, + })); + self.reset_attack_strength(); + } else if !self.entity_targeted() + && let Some(hit) = self.pick() + { + self.remote_mining(true); + instant = self + .res + .facts() + .is_air(self.world.block(hit.pos[0], hit.pos[1], hit.pos[2])); + } else { + if !self.creative { + self.clicks.miss_time = 10; + } + self.reset_attack_strength(); + } + self.swing_arm(); + self.send(S::Punch(Empty)); + instant + } + + fn remote_continue_attack(&mut self, down: bool) { + if !down { + self.clicks.miss_time = 0; + } + if self.clicks.miss_time > 0 || self.using.is_some() { + return; + } + let entity = self.entity_targeted(); + if down + && !entity + && let Some(hit) = self.pick() + { + let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); + if !self.res.facts().is_air(state) { + self.remote_mining(false); + self.swing_arm(); + self.send(S::Punch(Empty)); + } else { + if let Some(r) = self.remote.as_mut() { + r.destroying = None; + } + self.mining = None; + } + } else { + self.stop_remote_mining(); + self.mining = None; + } + } /// Keys with a multiplayer meaning; returns true when consumed. pub(super) fn remote_key(&mut self, key: KeyCode) -> Result { if self.screen != Screen::Playing { @@ -3552,6 +3825,14 @@ impl Game<'_> { speed: 1.0, })) } + // HopperMenu, and DispenserMenu (MenuType.GENERIC_3x3: dispensers + // and droppers). + "minecraft:hopper" => Some(BlockEntity::Chest(vec![None; 5])), + // BrewingStandMenu: its times come in ContainerSetData. + "minecraft:brewing_stand" => Some(BlockEntity::Brewing(Box::new( + horizon_client::brewing::BrewingStand::new(), + ))), + "minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])), m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { let rows = m .strip_prefix("minecraft:generic_9x") @@ -3587,7 +3868,7 @@ impl Game<'_> { // an ender chest's or a double chest's slots are no one block's, // so they go under a key no block has. let holds = |k: &(i32, i32, i32)| { - let name = &self.res.facts.get(self.world.block(k.0, k.1, k.2)).name; + let name = &self.res.facts().get(self.world.block(k.0, k.1, k.2)).name; BlockEntity::for_block(name).is_some_and(|e| { e.id() == entity.id() && e.slots().len() == entity.slots().len() }) @@ -3599,6 +3880,14 @@ impl Game<'_> { self.screen = Screen::Inventory; self.capture(false); } + /// The type of the menu a server opened (`MenuType`'s id). + pub(super) fn remote_menu_type(&self) -> Option<&str> { + Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str()) + } + /// The title the server gave the menu it opened. + pub(super) fn remote_menu_title(&self) -> Option { + self.remote.as_ref()?.menu_title.clone() + } /// A server's chest-like menu (`MenuType.GENERIC_9xN`): its rows and title. pub(super) fn remote_chest_menu(&self) -> Option<(usize, String)> { let r = self.remote.as_ref()?; @@ -3630,7 +3919,7 @@ impl Game<'_> { if self.player.is_some() { return false; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255)); let shown = horizon_client::net::shown_address(&r.session.address); @@ -3655,7 +3944,7 @@ impl Game<'_> { /// The server's death message; chat uses the shared ChatComponent. pub(super) fn remote_hud(&self, batch: &mut HudBatch) { let Some(r) = &self.remote else { return }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = batch.width; if self.screen == Screen::Dead && let Some(message) = &r.death_message @@ -3677,12 +3966,29 @@ impl Game<'_> { .filter_map(|(id, uuid)| Some((*id as u32, r.players.get(uuid)?.clone()))) .collect() } + /// `ClientClockManager.tick`: the clock moves on by the game time that + /// passed since its last tick, at its rate. A game time the server sets + /// forward (its sync every second) moves the clock with it. + fn remote_clock_tick(&mut self) { + let Some(r) = self.remote.as_mut() else { + return; + }; + let delta = self.world.game_time - r.clock_game_time; + r.clock_game_time = self.world.game_time; + let partial = f64::from(r.clock_partial) + delta as f64 * f64::from(r.clock_rate); + let full = partial.floor(); + r.clock_partial = (partial - full) as f32; + self.world.day_time += full as i64; + } pub(super) fn remote_status(&self) -> Option { let r = self.remote.as_ref()?; Some(serde_json::json!({ "address": horizon_client::net::shown_address(&r.session.address), "name": r.session.name, "joined": r.joined, + // ServerboundPlayerLoadedPacket sent: the level around the + // player is ready, and the client ticks and sends its moves. + "loaded": r.loaded_sent, "status": r.status, "entity_id": r.entity_id, "dimension": r.dimension.name, @@ -3704,6 +4010,8 @@ impl Game<'_> { let armor = [&e.head, &e.chest, &e.legs, &e.feet].map(|s| s.as_deref()); serde_json::json!({ "id": m.id, + "swinging": m.ai.swinging, + "using": m.extra.using_item, "armor": armor, "main_hand": e.main_hand.as_deref(), "off_hand": e.off_hand.as_deref(), @@ -3716,6 +4024,13 @@ impl Game<'_> { .filter(|t| t.kind == "minecraft:player") .map(|t| t.position) .collect::>(), + // The other players this client draws dead (lying down, after EntityEvent DEATH). + "dead_players": self + .mobs + .iter() + .filter(|m| r.level_players.contains_key(&(m.id as i32)) && !m.alive()) + .map(|m| m.id) + .collect::>(), // The player's own model exists (third person and the inventory draw it). "player_model": self.player_model.is_some(), "health": r.health.0, @@ -3807,6 +4122,57 @@ fn client_view_distance(render_distance: i32) -> i8 { render_distance.clamp(2, i32::from(i8::MAX)) as i8 } +struct RemoteInputWorld<'g, 'a>(&'g mut Game<'a>); + +struct RemoteUseWorld<'g, 'a>(&'g mut Game<'a>); + +impl horizon_client::interaction_input::TargetUseWorld for RemoteUseWorld<'_, '_> { + fn use_entity(&mut self) -> bool { + self.0.remote_use_entity() + } + fn use_block(&mut self) -> bool { + self.0.remote_use_block() + } + fn use_item(&mut self) { + self.0.remote_use_item(); + } +} + +impl horizon_client::interaction_input::InteractionWorld for RemoteInputWorld<'_, '_> { + fn using_item(&self) -> bool { + self.0.using.is_some() + } + fn release_using(&mut self) { + self.0.send(S::PlayerAction(play::PlayerAction { + action: 6, + pos: [0; 3], + direction: 0, + sequence: 0, + })); + self.0.using = None; + } + fn start_attack(&mut self) -> bool { + self.0.remote_start_attack() + } + fn start_use(&mut self) { + self.0.remote_use(); + } + fn pick(&mut self) { + if let Some(hit) = self.0.pick() { + self.0.send(S::PickItemFromBlock(play::PickItemFromBlock { + pos: hit.pos, + include_data: self.0.has_control_down(), + })); + } + } + fn use_delay(&self) -> u32 { + self.0.use_delay + } + fn continue_attack(&mut self, down: bool) { + self.0.remote_continue_attack(down); + } +} + #[cfg(test)] mod tests { use super::Game; diff --git a/crates/horizon-client/src/game/render_control.rs b/crates/horizon-client/src/game/render_control.rs index 21a5aee46..31a7a33a0 100644 --- a/crates/horizon-client/src/game/render_control.rs +++ b/crates/horizon-client/src/game/render_control.rs @@ -12,6 +12,7 @@ pub const HELP: &[&str] = &[ "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", + "section-cull [on|off] occlusion culling of solid sections (A/B checks); replies the mode", ]; impl Game<'_> { @@ -120,7 +121,7 @@ impl Game<'_> { let key = (int(1)?, int(2)?, int(3)?); let name = self .res - .facts + .facts() .get(self.world.block(key.0, key.1, key.2)) .name .clone(); diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index 4ee10e6d2..b990869a5 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -66,15 +66,21 @@ impl Game<'_> { ) -> FogData { let forward = self.forward(); let at = [camera.x, camera.y, camera.z]; - let fog_type = fog_type(&self.world, &self.res.facts, at, forward); - let water = self.res.biomes.get(biome).water_fog; + let fog_type = fog_type(&self.world, self.res.facts(), at, forward); + let water = self.res.biomes().get(biome).water_fog; let (rain, thunder) = if self.dim == Dim::Overworld { self.world.weather.levels(self.clock.fraction() as f32) } else { (0.0, 0.0) }; + let title_fog = horizon_client::fog::FogTables::default(); + let tables = if self.title.is_some() { + &title_fog + } else { + self.res.fog() + }; horizon_client::fog::setup_fog( - &self.res.fog, + tables, &self.fog, &FogInputs { fog_type, @@ -117,7 +123,7 @@ impl Game<'_> { horizon_client::gfx::ShaderInputs { rain, thunder, - submerged: match fog_type(&self.world, &self.res.facts, at, self.forward()) { + submerged: match fog_type(&self.world, self.res.facts(), at, self.forward()) { FogType::Atmospheric => 0, FogType::Water => 1, FogType::Lava => 2, @@ -139,7 +145,7 @@ impl Game<'_> { camera.y < 63.0 && fog_type( &self.world, - &self.res.facts, + self.res.facts(), [camera.x, camera.y, camera.z], self.forward(), ) != FogType::Water @@ -170,7 +176,7 @@ impl Game<'_> { t[1].floor() as i32, t[2].floor() as i32, ); - let f = self.res.facts.get(state); + let f = self.res.facts().get(state); if f.render_shape != horizon_client::blocks::RenderShape::Invisible && f.solid_render && f.full_collision @@ -180,7 +186,7 @@ impl Game<'_> { } } let in_water = - fog_type(&self.world, &self.res.facts, eye, self.forward()) == FogType::Water; + fog_type(&self.world, self.res.facts(), eye, self.forward()) == FogType::Water; let water = (in_water && !spectator).then(|| (self.eye_brightness(eye), self.yaw, self.pitch)); // Hud.extractCameraOverlays; the spyglass scope (and its easing) is @@ -211,7 +217,7 @@ impl Game<'_> { let gui_overlays = hud_overlays::camera_overlays(size[0] as i32, size[1] as i32, &overlays, &mut scope); self.screen_fx.build(&ScreenInputs { - sprites: &self.atlas.sprites, + sprites: &self.gui.atlas.sprites, aspect: size[0] as f32 / size[1].max(1) as f32, partial, block_overlay, @@ -243,7 +249,7 @@ impl Game<'_> { self.screen_fx.tick(brightness, inside_portal); // LocalPlayer water vision and AtmosphericFogEnvironment rain fog. let in_water = - fog_type(&self.world, &self.res.facts, e, self.forward()) == FogType::Water; + fog_type(&self.world, self.res.facts(), e, self.forward()) == FogType::Water; self.fog.tick(in_water); let b = [ e[0].floor() as i32, @@ -260,7 +266,7 @@ impl Game<'_> { .chunks .get(&(b[0] >> 4, b[2] >> 4)) .map_or(0, |c| c.biome(b[0], b[1], b[2])); - let rains = self.res.biomes.get(biome).precipitation; + let rains = self.res.biomes().get(biome).precipitation; update_rain_fog( &mut self.fog, rain, @@ -278,8 +284,8 @@ impl Game<'_> { (0.0, 0.0) }; let world = &self.world; - let facts = &self.res.facts; - let biomes = &self.res.biomes; + let facts = self.res.facts(); + let biomes = self.res.biomes(); let raining = rain > 0.2; let raining_at = |p: [i32; 3]| { raining @@ -300,7 +306,7 @@ impl Game<'_> { e[1].floor() as i32, e[2].floor() as i32, ]; - animate_tick(&self.res.animate, &mut self.particles, &ctx, block); + animate_tick(self.res.animate(), &mut self.particles, &ctx, block); if rain > 0.0 { // ClientLevel.tickWeatherEffects: rain splashes (weather radius 10). let mut random = LegacyRandom::new(self.world.game_time.wrapping_mul(312_987_231)); @@ -336,7 +342,7 @@ impl Game<'_> { let smoke = f.fluid == Fluid::Lava || &*f.name == "minecraft:magma_block" || (f.name.ends_with("campfire") - && self.res.animate.is_lit_campfire(state.0)); + && self.res.animate().is_lit_campfire(state.0)); let ty = if smoke { ParticleType::Smoke } else { @@ -354,7 +360,7 @@ impl Game<'_> { } if let Some(r) = &self.renderer { campfire_particles( - &self.res.animate, + self.res.animate(), &mut self.particles, &ctx, r.block_entities(), diff --git a/crates/horizon-client/src/game/respawn_anchor.rs b/crates/horizon-client/src/game/respawn_anchor.rs index aa94d5b17..4604c076f 100644 --- a/crates/horizon-client/src/game/respawn_anchor.rs +++ b/crates/horizon-client/src/game/respawn_anchor.rs @@ -63,7 +63,7 @@ pub(super) enum AnchorUse { impl Game<'_> { fn is_anchor(&self, state: BlockStateId) -> bool { - &*self.res.facts.get(state).name == "minecraft:respawn_anchor" + &*self.res.facts().get(state).name == "minecraft:respawn_anchor" } fn anchor_charges(&self, state: BlockStateId) -> i32 { self.pack @@ -177,7 +177,7 @@ impl Game<'_> { } /// `RespawnAnchorBlock.isWaterThatWouldFlow`. fn water_would_flow(&self, p: [i32; 3]) -> bool { - let f = self.res.facts.get(self.world.block(p[0], p[1], p[2])); + let f = self.res.facts().get(self.world.block(p[0], p[1], p[2])); if f.fluid != Fluid::Water { return false; } @@ -188,7 +188,7 @@ impl Game<'_> { return false; } self.res - .facts + .facts() .get(self.world.block(p[0], p[1] - 1, p[2])) .fluid != Fluid::Water @@ -203,7 +203,7 @@ impl Game<'_> { .any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]])); let above = self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1] + 1, pos[2])) .fluid == Fluid::Water; @@ -225,7 +225,7 @@ impl Game<'_> { /// halves and explodes; `StrawBedBlock` just falls apart. pub(super) fn destroy_bed_on_use(&mut self, head: [i32; 3]) -> Result<()> { let state = self.world.block(head[0], head[1], head[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let center = [ f64::from(head[0]) + 0.5, f64::from(head[1]) + 0.5, @@ -259,7 +259,7 @@ impl Game<'_> { let foot = [head[0] + back[0], head[1], head[2] + back[2]]; if self .res - .facts + .facts() .get(self.world.block(foot[0], foot[1], foot[2])) .name == name @@ -297,7 +297,7 @@ impl Game<'_> { /// climbable blocks and open trapdoors. fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape { let state = self.world.block(p[0], p[1], p[2]); - let name = &self.res.facts.get(state).name; + let name = &self.res.facts().get(state).name; let open_trapdoor = name.ends_with("_trapdoor") && self .pack @@ -326,7 +326,7 @@ impl Game<'_> { } pub(super) fn block_in_tag(&self, tag: &str, block: &str) -> bool { self.res - .items + .items() .block_tags .get(tag) .is_some_and(|s| s.contains(block)) @@ -334,7 +334,7 @@ impl Game<'_> { /// `EntityType.isBlockDangerous` for the player. fn dangerous_for_player(&self, p: [i32; 3]) -> bool { let state = self.world.block(p[0], p[1], p[2]); - let name = &*self.res.facts.get(state).name; + let name = &*self.res.facts().get(state).name; let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire") && self .pack @@ -397,7 +397,7 @@ impl Game<'_> { } let name = |q: [i32; 3]| { self.res - .facts + .facts() .get(self.world.block(q[0], q[1], q[2])) .name .clone() diff --git a/crates/horizon-client/src/game/scoreboard.rs b/crates/horizon-client/src/game/scoreboard.rs index 4e715c7b7..99dae39a5 100644 --- a/crates/horizon-client/src/game/scoreboard.rs +++ b/crates/horizon-client/src/game/scoreboard.rs @@ -131,6 +131,7 @@ impl Game<'_> { pub(super) fn holder_name(&mut self, t: Target) -> Option { match t { Target::Player => Some(self.acting_player_name().to_owned()), + Target::Guest(conn) => self.command_guest(conn).map(|g| g.name.clone()), Target::Mob(id) | Target::Item(id) => Some(uuid_text(self.uuid_for(id))), _ => None, } @@ -179,7 +180,7 @@ impl Game<'_> { | Target::Cart(id) | Target::Other(id) => self.persist.raw.get(&id), Target::Player => self.level.player_extra.as_ref(), - Target::Orb(_) | Target::Arrow(_) => None, + Target::Guest(_) | Target::Orb(_) | Target::Arrow(_) => None, }; match raw.and_then(|r| r.get("Tags")) { Some(Tag::List(l)) => l @@ -584,11 +585,11 @@ impl Game<'_> { batch.height as i32, board, objective, - &self.atlas.font, + &self.gui.atlas.font, self.settings.text_background(0.3), self.settings.text_background(0.4), ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } @@ -648,8 +649,8 @@ impl Game<'_> { ), upside_down: &up, }; - let draws = self.tab_list.layout(&inputs, &self.atlas.font); - horizon_client::hud_layout::paint(batch, &self.atlas, &draws); + let draws = self.tab_list.layout(&inputs, &self.gui.atlas.font); + horizon_client::hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/screens.rs b/crates/horizon-client/src/game/screens.rs index 365dd5992..cecd8d46f 100644 --- a/crates/horizon-client/src/game/screens.rs +++ b/crates/horizon-client/src/game/screens.rs @@ -92,7 +92,7 @@ impl Game<'_> { let (world, quit) = self.pause_labels(); self.tick_friends(); let friends = self.friends_view(); - let mut ui = horizon_client::ui_theme::Ui::new(&self.atlas, batch, self.cursor); + let mut ui = horizon_client::ui_theme::Ui::new(&self.gui.atlas, batch, self.cursor); horizon_client::front::pause::draw( &mut ui, &world, @@ -104,7 +104,7 @@ impl Game<'_> { ui.finish(); return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let title = Text::translate("menu.game", &[]); @@ -156,7 +156,7 @@ impl Game<'_> { let mut b = HudBatch::new(size); let (world, quit) = self.pause_labels(); horizon_client::front::pause::click( - &self.atlas, + &self.gui.atlas, &mut b, self.cursor.0, self.cursor.1, @@ -197,7 +197,7 @@ impl Game<'_> { } /// DeathScreen: gradient, the title at double size, the cause and score. pub(super) fn draw_death_screen(&mut self, batch: &mut HudBatch) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); // fillGradient(0x60500000 -> 0xA0803030). let rows = h.ceil() as i32; @@ -288,6 +288,11 @@ impl Game<'_> { if hit == Some(0) && self.remote.is_none() { let keep = self.ui.rules.bool("keep_inventory") || self.spectator(); self.experience.respawn(keep); + // The guests are sent the respawned host as a new entity, not the dead body. + if let Some(host) = self.lan.as_mut() { + let id = host.host_entity; + host.hub.respawned(id); + } // Autosaves keep a login position; death must resolve the respawn point instead. self.level.position = None; } diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 72a91d7da..de7ea6df2 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -277,7 +277,7 @@ impl Game<'_> { let n = registry.len(); let tag = |name: &str| { self.res - .items + .items() .block_tags .get(name) .cloned() @@ -296,7 +296,7 @@ impl Game<'_> { resonator: vec![false; n], }; for i in 0..n { - let facts = self.res.facts.get(BlockStateId(i as u32)); + let facts = self.res.facts().get(BlockStateId(i as u32)); let name: &str = &facts.name; t.kinds[i] = match name { "minecraft:sculk_sensor" => KIND_SENSOR, @@ -614,7 +614,7 @@ impl Game<'_> { }; !own && !calibrated_out && frequency != 0 - && self.res.behaviours.sculk_sensor_can_activate(state) + && self.res.behaviours().sculk_sensor_can_activate(state) } SculkKind::Shrieker => !self.shrieker_shrieking(state) && ctx.player, SculkKind::Catalyst => false, @@ -705,18 +705,10 @@ impl Game<'_> { } Ok(()) } - /// `ServerLevel.shouldTickBlocksAt`, as `tick_blocks` decides it. + /// `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk, from every + /// player's tickets (`update_chunk_tickets`), once the chunk is lit. fn chunk_ticks(&self, cx: i32, cz: i32) -> bool { - let Some(p) = self.player.as_ref() else { - return false; - }; - let (pcx, pcz) = ( - (p.position.x.floor() as i32) >> 4, - (p.position.z.floor() as i32) >> 4, - ); - let simulation = self.settings.render_distance.min(8); - (cx - pcx).abs() <= simulation - && (cz - pcz).abs() <= simulation + self.tickets.levels().block_ticking(cx, cz) && self.world.chunks.get(&(cx, cz)).is_some_and(|c| c.lit) } fn tick_sculk_block(&mut self, key: (i32, i32, i32)) -> Result<()> { @@ -775,7 +767,7 @@ impl Game<'_> { match kind { SculkKind::Sensor | SculkKind::Calibrated => { let state = self.world.block(key.0, key.1, key.2); - if self.res.behaviours.sculk_sensor_can_activate(state) { + if self.res.behaviours().sculk_sensor_can_activate(state) { let frequency = sculk::frequency(info.event); if let Some(e) = self.sculk_entity(key) { e.last_frequency = frequency; @@ -865,7 +857,7 @@ impl Game<'_> { if self.mobs.iter().any(|m| m.id == id && m.species() == Species::Warden)); match self.kind_of_state(state.0) { KIND_SENSOR | KIND_CALIBRATED => { - if is_warden || !self.res.behaviours.sculk_sensor_can_activate(state) { + if is_warden || !self.res.behaviours().sculk_sensor_can_activate(state) { continue; } let calibrated = self.kind_of_state(state.0) == KIND_CALIBRATED; @@ -1008,7 +1000,7 @@ impl Game<'_> { if warning < 4 { return false; } - let Some(kind) = self.res.mob_types.get("minecraft:warden").cloned() else { + let Some(kind) = self.res.mob_types().get("minecraft:warden").cloned() else { return false; }; for _ in 0..20 { @@ -1051,7 +1043,7 @@ impl Game<'_> { /// `SpawnUtil.moveToPossibleSpawnPosition` with `ON_TOP_OF_COLLIDER`. fn spawn_position(&self, x: i32, y: i32, z: i32, range: i32) -> Option<(i32, i32, i32)> { use horizon_client::mobs::data; - let flags = |b: BlockStateId| self.res.mob_data.state(b); + let flags = |b: BlockStateId| self.res.mob_data().state(b); let mut search = y; let mut above = self.world.block(x, search, z); for _ in (-range..=range).rev() { @@ -1170,7 +1162,7 @@ impl Game<'_> { && let Some(eye) = self.eye_position() { let in_water = - horizon_client::fog::fog_type(&self.world, &self.res.facts, eye, self.forward()) + horizon_client::fog::fog_type(&self.world, self.res.facts(), eye, self.forward()) == FogType::Water; return self.fog.water_vision(in_water); } @@ -1335,7 +1327,7 @@ impl Game<'_> { .play("minecraft:block.sculk.charge", Some(c), 1.0, 1.0); let solid = self .res - .facts + .facts() .get(self.world.block(pos.x, pos.y, pos.z)) .full_collision; let (particles, spread) = if solid { (40, 0.45f32) } else { (20, 0.25f32) }; @@ -1543,7 +1535,8 @@ impl Game<'_> { at[1].floor() as i32, at[2].floor() as i32, ); - self.res.facts.get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water + self.res.facts().get(self.world.block(x, y, z)).fluid + == horizon_client::blocks::Fluid::Water } /// `Entity.move`'s emission: footsteps, swimming, landing and splashes. fn entity_motion_events( @@ -1590,13 +1583,13 @@ impl Game<'_> { at[2].floor() as i32, ); let state = self.world.block(block.0, block.1, block.2); - let air = self.res.facts.is_air(state); + let air = self.res.facts().is_air(state); let climbable = self .res - .items + .items() .block_tags .get("minecraft:climbable") - .is_some_and(|t| t.contains(&*self.res.facts.get(state).name)); + .is_some_and(|t| t.contains(&*self.res.facts().get(state).name)); let travelled = if climbable { ((dx * dx + dy * dy + dz * dz).sqrt() * f64::from(0.6f32)) as f32 } else { diff --git a/crates/horizon-client/src/game/sculk_fixture.rs b/crates/horizon-client/src/game/sculk_fixture.rs index 2ebdbcb2b..890e571b8 100644 --- a/crates/horizon-client/src/game/sculk_fixture.rs +++ b/crates/horizon-client/src/game/sculk_fixture.rs @@ -303,8 +303,8 @@ impl Game<'_> { } fn sculk_fixture_reset(&mut self, s: &Scenario) -> Result<()> { - self.world = World::new(self.res.facts.air, 0); - let plains = u32::from(self.res.biomes.id("minecraft:plains")); + self.world = World::new(self.res.facts().air, 0); + let plains = u32::from(self.res.biomes().id("minecraft:plains")); let layers = [ self.fixture_state("minecraft:bedrock")?, self.fixture_state("minecraft:dirt")?, @@ -439,7 +439,7 @@ impl Game<'_> { for spec in &s.mobs { let kind = self .res - .mob_types + .mob_types() .get(&spec.kind) .cloned() .ok_or_else(|| format!("unknown mob {}", spec.kind))?; @@ -696,6 +696,8 @@ impl Game<'_> { seed_fresh(m, 0x5eed + (named + i + 1) as i64); } } + // The player's tickets, as `tick_world` takes them. + self.update_chunk_tickets(); // Entities: the player's warden spawn tracker, then the mobs. self.tick_sculk_entities(); // (ServerChunkCache.tick, natural spawning and its chunk shuffle, is not run.) diff --git a/crates/horizon-client/src/game/server_travel.rs b/crates/horizon-client/src/game/server_travel.rs index 6c0ec48e7..56fdbaca5 100644 --- a/crates/horizon-client/src/game/server_travel.rs +++ b/crates/horizon-client/src/game/server_travel.rs @@ -304,6 +304,7 @@ impl Game<'_> { /// The hub's view of the server for packets sent outside its own tick. pub(super) fn server_ctx(&mut self) -> TickCtx<'_> { let spawn = self.spawn.map_or([0.5, 80.0, 0.5], |s| [s.x, s.y, s.z]); + let clock_rate = self.network_clock_rate(); TickCtx { world: &mut self.world, host: None, @@ -312,11 +313,7 @@ impl Game<'_> { spawn, difficulty: i32::from(self.ui.difficulty), difficulty_locked: self.level.difficulty_locked, - clock_rate: if self.ui.rules.bool("advance_time") { - self.ui.clock.rate - } else { - 0.0 - }, + clock_rate, tick_rate: self.clock.rate(), tick_frozen: self.clock.frozen(), collision: Some(self.collision), diff --git a/crates/horizon-client/src/game/shield.rs b/crates/horizon-client/src/game/shield.rs index 849c62958..c4f7f98d1 100644 --- a/crates/horizon-client/src/game/shield.rs +++ b/crates/horizon-client/src/game/shield.rs @@ -34,7 +34,7 @@ impl Game<'_> { &self, stack: &ItemStack, ) -> Option<&horizon_client::items::BlocksAttacks> { - self.res.items.get(&stack.item)?.blocks_attacks.as_ref() + self.res.items().get(&stack.item)?.blocks_attacks.as_ref() } /// `ShieldItem.use` (ItemUtils.startUsingInstantly) for the hand at `slot`; /// false when that hand holds no blocking item or it is on cooldown. @@ -64,7 +64,7 @@ impl Game<'_> { if (ticks as i32) < (component.delay_seconds * 20.0).round() as i32 { return None; } - let tags = &self.res.stations.enchantments.damage_tags; + let tags = &self.res.stations().enchantments.damage_tags; let matches = |spec: &str| match spec.strip_prefix('#') { Some(tag) => tags.get(tag).is_some_and(|t| t.contains(damage_type)), None => spec == damage_type, @@ -150,7 +150,11 @@ impl Game<'_> { }; if item_damage > 0 && !self.creative { let loss = self.durability_loss(&stack, item_damage as u32); - let max = self.res.items.get(&stack.item).map_or(0, |i| i.max_damage); + let max = self + .res + .items() + .get(&stack.item) + .map_or(0, |i| i.max_damage); let cell = self.stack_in_mut(slot); if let Some(s) = cell.as_mut() && max > 0 @@ -182,7 +186,7 @@ impl Game<'_> { .extra .main_hand .as_deref() - .and_then(|item| self.res.items.get(item)) + .and_then(|item| self.res.items().get(item)) .map_or(0.0, |i| i.disable_blocking_seconds); // Ravager.blockedByItem: stunned half the time (the defender pushed // apart), else the defender flung away; no roar in progress. diff --git a/crates/horizon-client/src/game/sign_edit.rs b/crates/horizon-client/src/game/sign_edit.rs index c0a780063..c679bad69 100644 --- a/crates/horizon-client/src/game/sign_edit.rs +++ b/crates/horizon-client/src/game/sign_edit.rs @@ -88,7 +88,7 @@ impl Game<'_> { return; }; let line = edit.line; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let width = |s: &str| HudBatch::text_width(atlas, s); let Some(key) = self.sign_edit.as_ref().map(|e| e.pos) else { return; @@ -130,7 +130,7 @@ impl Game<'_> { } else { &mut sign.back }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; self.text_selection.apply( sign_line_id(front, line), &mut text.lines[line], @@ -163,7 +163,7 @@ impl Game<'_> { let Some(BlockEntity::Sign(sign)) = self.world.block_entities.get(&edit.pos) else { return; }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (w, h) = (batch.width, batch.height); batch.fill(atlas, 0.0, 0.0, w, h, rgba(16, 16, 16, 160)); let title = if sign.hanging { @@ -175,7 +175,7 @@ impl Game<'_> { batch.text(atlas, title, (w - tw) / 2.0, 40.0, u32::MAX, true); let name = self .res - .facts + .facts() .get(self.world.block(edit.pos.0, edit.pos.1, edit.pos.2)) .name .clone(); diff --git a/crates/horizon-client/src/game/sniffers.rs b/crates/horizon-client/src/game/sniffers.rs index 61325ede6..a30c0ba5c 100644 --- a/crates/horizon-client/src/game/sniffers.rs +++ b/crates/horizon-client/src/game/sniffers.rs @@ -93,7 +93,7 @@ impl Game<'_> { self.particles.push(particle); } if self.mobs[i].age.is_multiple_of(10) { - let hit = self.res.facts.get(below).sounds.hit.clone(); + let hit = self.res.facts().get(below).sounds.hit.clone(); self.audio.play(&hit, Some(at), 0.5, 0.5); } } diff --git a/crates/horizon-client/src/game/spawner.rs b/crates/horizon-client/src/game/spawner.rs index a2131f9b0..538cb39e7 100644 --- a/crates/horizon-client/src/game/spawner.rs +++ b/crates/horizon-client/src/game/spawner.rs @@ -68,7 +68,7 @@ impl Game<'_> { /// (`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" { + if &*self.res.facts().get(state).name != "minecraft:spawner" { return Ok(()); } let Some(BlockEntity::Spawner(mut spawner)) = self.world.block_entities.take(&key) else { @@ -145,7 +145,7 @@ impl Game<'_> { r: &SpawnerSpawn, planned: &mut Vec, ) -> Option { - let kind = self.res.mob_types.get(r.id)?.clone(); + let kind = self.res.mob_types().get(r.id)?.clone(); let [x, y, z] = r.position; let at = Vec3::new(x, y, z); let bounds = if r.finalize { @@ -195,7 +195,7 @@ impl Game<'_> { tag.insert("PersistenceRequired".into(), Tag::Byte(1)); } let tag = Tag::Compound(tag); - let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, &self.res.mob_types, 0)?; + let mob = horizon_client::entity_nbt::mob_from_nbt(&tag, self.res.mob_types(), 0)?; let bounds = mob.bounds(); planned.push(Planned::Loaded(tag)); bounds @@ -331,7 +331,7 @@ impl Game<'_> { .get(&key) .is_none_or(|(k, _)| *k != kind) { - let Some(t) = self.res.mob_types.get(&kind).cloned() else { + let Some(t) = self.res.mob_types().get(&kind).cloned() else { return false; }; let mob = Mob::new(u32::MAX, t, Vec3::ZERO, 0.0); @@ -351,7 +351,7 @@ impl Game<'_> { } _ => return None, }; - self.res.mob_types.contains_key(&id).then_some(id) + self.res.mob_types().contains_key(&id).then_some(id) } /// `SpawnEggItem.useOn` on a spawner: the egg sets its mob. None when the /// clicked block has no spawner. @@ -393,7 +393,7 @@ impl Game<'_> { alpha: f64, out: &mut Vec, ) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let lookup = |name: &str| atlas.sprites.get(name).map(|r| [r.u0, r.v0, r.u1, r.v1]); for (key, (_, mob)) in &self.spawners.displays { let at = glam::DVec3::new(f64::from(key.0), f64::from(key.1), f64::from(key.2)); @@ -436,7 +436,7 @@ impl Game<'_> { origin, &lookup, packed, - &self.res.mob_data, + self.res.mob_data(), out, ); } diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs new file mode 100644 index 000000000..9531b0f38 --- /dev/null +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -0,0 +1,782 @@ +//! The interactive title before world resources exist. Uses only the menu +//! atlas/panorama; transfers the actual screen and queued entry to Game. +use super::*; +use horizon_client::{ + clipboard::{self, AppendSelection, SystemClipboard}, + options_ui::{Event, OptionsUi, Page}, +}; +use winit::{event::KeyEvent, keyboard::ModifiersState}; + +#[derive(Default)] +pub(super) struct StartupMenu { + title: Option, + options: OptionsUi, + options_open: bool, + root: PathBuf, + cursor: (f32, f32), + pointer: (f64, f64), + modifiers: ModifiersState, + physical_keys: HashSet<KeyCode>, + dragging: bool, + clipboard: SystemClipboard, + selection: AppendSelection, + pub pending: Option<PendingWorldEntry>, + pub reload_packs: bool, + pub perf: horizon_client::telemetry::Session, +} + +impl StartupMenu { + pub fn new(options: &Options, pack_error: Option<&str>) -> Result<Self> { + let pending = if let Some(address) = &options.server { + Some(PendingWorldEntry::Server { + address: address.clone(), + name: options.player_name(), + }) + } else { + options + .world + .as_ref() + .map(|folder| PendingWorldEntry::Local { + folder: folder.clone(), + name: None, + seed: Some(options.seed), + creative: options.creative, + create: None, + }) + }; + let mut menu = Self { + pending, + ..Default::default() + }; + menu.root = options.resources.clone(); + if let Some(error) = pack_error { + menu.options.open_at(false, Page::Packs); + menu.options.resource_error = Some(error.to_owned()); + menu.options_open = true; + } + if menu.pending.is_some() { + menu.perf.world_opening(); + } + Ok(menu) + } + + pub(super) fn set_root(&mut self, root: PathBuf, settings: &Settings) { + horizon_client::ui::load_metadata(&root); + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&root], + &settings.language, + )); + self.root = root; + if self.title.is_none() { + let mut title = Title::new( + std::env::current_dir().unwrap_or_default().join("saves"), + &self.root, + ); + title.last_server = settings.file.string("lastServer"); + if horizon_client::ui_theme::horizon() { + title + .opening + .set(Some(horizon_client::front::Opening::new())); + } + self.title = Some(title); + } + } + + pub(super) fn handoff(&mut self, game: &mut Game<'_>) { + game.title = self.title.take(); + game.pending_entry = self.pending.take(); + game.cursor = self.cursor; + game.modifiers = self.modifiers; + game.physical_keys = std::mem::take(&mut self.physical_keys); + game.clipboard = std::mem::take(&mut self.clipboard); + game.text_selection = std::mem::take(&mut self.selection); + game.perf = std::mem::take(&mut self.perf); + // Preserve an existing resource-error screen opened by start_game. + if self.options_open { + let resource_error = game.ui.options.resource_error.take(); + game.ui.options = std::mem::take(&mut self.options); + game.ui.options.resource_error = + game.ui.options.resource_error.take().or(resource_error); + game.screen = Screen::Options; + game.options_from_title = true; + game.dragging = self.dragging; + } + } + + fn queue_entry(&mut self, action: Action, player_name: String) { + let entry = match action { + Action::Play { folder } => PendingWorldEntry::Local { + folder, + name: None, + seed: None, + creative: false, + create: None, + }, + Action::Create { + folder, + name, + seed, + creative, + options, + } => PendingWorldEntry::Local { + folder, + name: Some(name), + seed, + creative, + create: Some(Box::new(options)), + }, + Action::Connect { address } => PendingWorldEntry::Server { + address, + name: player_name, + }, + _ => return, + }; + self.pending = Some(entry); + self.perf.world_opening(); + } + + fn shortcut(&mut self, event: &KeyEvent) -> Option<clipboard::EditShortcut> { + let edit = if cfg!(target_os = "macos") { + self.modifiers.super_key() + } else { + self.modifiers.control_key() + }; + clipboard::edit_shortcut( + clipboard::shortcut_letter(&event.logical_key, event.physical_key), + edit, + self.modifiers.shift_key(), + self.modifiers.alt_key(), + ) + } + + fn title_key(&mut self, event: &KeyEvent) { + let shortcut = self.shortcut(event); + let Some(title) = &mut self.title else { return }; + if title.skip_opening() { + return; + } + if let Some(shortcut) = shortcut { + if title.has_caret_field() { + title.field_shortcut(shortcut, &mut self.clipboard); + } else if let Some((id, value, max)) = title.focused_field() + && self + .selection + .apply(id, value, shortcut, &mut self.clipboard, |v, t| { + clipboard::append_limited(v, t, max) + }) + { + title.search_changed(); + } + return; + } + match event.physical_key { + PhysicalKey::Code(KeyCode::Escape) => title.escape(), + PhysicalKey::Code(KeyCode::Tab) => title.tab(), + PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => title.confirm_edit(), + PhysicalKey::Code( + key @ (KeyCode::Backspace + | KeyCode::Delete + | KeyCode::ArrowLeft + | KeyCode::ArrowRight + | KeyCode::Home + | KeyCode::End), + ) if title.has_caret_field() => { + title.field_key( + key, + self.modifiers.control_key(), + self.modifiers.shift_key(), + ); + } + _ => { + let cleared = !title.has_caret_field() + && title + .focused_field() + .is_some_and(|(id, value, _)| self.selection.take(id, value)); + if cleared { + title.search_changed(); + } + if event.physical_key == PhysicalKey::Code(KeyCode::Backspace) { + if !cleared { + title.backspace(); + } + } else if let Some(text) = &event.text { + title.type_text(text); + } + } + } + } +} + +/// Each generation has its own channel and progress. Pack changes wait for the +/// old tail before starting another generation, including cache/global writes. +pub(super) fn spawn_loader( + options: &Options, + settings: &Settings, + vanilla_root: &std::path::Path, + started: Instant, + progress: &Progress, +) -> Result<(Receiver<LoaderMsg>, JoinHandle<()>)> { + let (sender, receiver) = std::sync::mpsc::channel(); + let settings = settings.clone(); + let vanilla_root = vanilla_root.to_path_buf(); + let dev_mods = options.dev_mods.clone(); + let progress = progress.clone(); + let handle = std::thread::Builder::new() + .name("resource-loader".into()) + .spawn(move || { + let mut pack_error = None; + let root = packs::startup_root(&vanilla_root, &settings.resource_packs).unwrap_or_else( + |error| { + pack_error = Some(error.to_string()); + vanilla_root.clone() + }, + ); + let root = mods::content_root(&root, &settings.mods.enabled, &dev_mods); + let result = load_resources( + root, + &vanilla_root, + &settings, + started, + true, + &progress, + &mut |gui, root| { + let _ = sender.send(LoaderMsg::Ui(gui, root.to_path_buf())); + }, + ) + .map(|mut loaded| { + loaded.pack_error = loaded.pack_error.or(pack_error); + loaded + }) + .map_err(|error| error.to_string()); + let _ = sender.send(LoaderMsg::Done(result)); + })?; + Ok((receiver, handle)) +} + +impl Loading { + pub(super) fn poll_menu_resources(&mut self) -> Result<()> { + if self.loaded.is_none() { + loop { + match self.receiver.try_recv() { + Ok(LoaderMsg::Ui(gui, root)) => self.set_ui(gui, root), + Ok(LoaderMsg::Done(result)) => { + self.loaded = Some(result); + break; + } + Err(TryRecvError::Empty) => break, + Err(TryRecvError::Disconnected) => { + if let Some(handle) = self.handle.take() { + let _ = handle.join(); + } + return Err("resource loader stopped before finishing".into()); + } + } + } + } + self.restart_menu_resources() + } + pub(super) fn apply_menu_settings(&mut self) { + if let Some(renderer) = &mut self.renderer { + self.settings + .clamp_gui_scale([renderer.config.width as i32, renderer.config.height as i32]); + renderer.gamma = self.settings.gamma; + renderer.set_present_mode(self.settings.vsync, self.settings.horizon.present_mode); + } + horizon_client::hud::GUI_SCALE.store(self.settings.gui_scale, Ordering::Relaxed); + if let Some(gui) = &mut self.gui { + gui.atlas.font.uniform = self.settings.force_unicode; + gui.atlas.font.japanese = self.settings.japanese_glyphs; + } + if let Some(window) = &self.window + && let Some(want) = self.fullscreen.request(self.settings.fullscreen) + { + window.set_fullscreen(want.then_some(winit::window::Fullscreen::Borderless(None))); + } + self.update_menu_cursor(); + } + + fn update_menu_cursor(&mut self) { + let batch = HudBatch::new(self.menu_size()); + self.menu.cursor = ( + self.menu.pointer.0 as f32 / batch.scale, + self.menu.pointer.1 as f32 / batch.scale, + ); + } + + fn menu_size(&self) -> [u32; 2] { + self.renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]) + } + + fn save_menu_address(&mut self) { + if self + .menu + .title + .as_ref() + .is_some_and(|title| title.last_server != self.settings.file.string("lastServer")) + { + self.save_menu_settings(); + } + } + + fn save_menu_settings(&mut self) { + if let Some(title) = &self.menu.title { + self.settings.file.set( + "lastServer", + horizon_client::options_file::V::Str(title.last_server.clone()), + ); + } + self.settings.save(&Game::options_path()); + } + + fn open_menu_options(&mut self, page: Page) { + self.menu.options.open_at(false, page); + self.menu.options.languages = horizon_client::lang::available(&[&self.menu.root]); + self.menu.options.pack_infos = packs::pack_infos(&self.vanilla_root); + self.menu.options.pack_selection = self.settings.resource_packs.clone(); + self.menu.options.pack_screen = None; + self.menu.options_open = true; + } + + fn menu_option_events(&mut self, events: Vec<Event>) { + for event in events { + match event { + Event::Changed => { + self.save_menu_settings(); + self.apply_menu_settings(); + } + Event::Close if self.menu.options.resource_error.is_some() => {} + Event::Close => { + self.menu.options_open = false; + self.menu.dragging = false; + self.save_menu_settings(); + } + Event::Language(code) => { + horizon_client::lang::set(horizon_client::lang::Language::load( + &[&self.menu.root], + &code, + )); + self.save_menu_settings(); + } + Event::Packs(_) => { + self.save_menu_settings(); + self.menu.reload_packs = true; + } + Event::OpenPackFolder => { + let dir = packs::packs_dir(); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } + Event::OpenModFolder => { + let dir = Game::options_path().with_file_name(horizon_client::mod_list::DIR); + let _ = std::fs::create_dir_all(&dir); + packs::open_folder(&dir); + } + Event::ButtonClick => {} + } + } + } + + fn menu_options_click(&mut self, drag: bool, right: bool) { + let size = self.menu_size(); + let batch = HudBatch::new(size); + let Some(gui) = &self.gui else { return }; + let events = self.menu.options.click( + &mut self.settings, + &gui.atlas, + self.menu.cursor.0, + self.menu.cursor.1, + (batch.width, batch.height), + [size[0] as i32, size[1] as i32], + drag, + right, + ); + self.menu_option_events(events); + } + + fn menu_action(&mut self, event_loop: &ActiveEventLoop, action: Action) { + match action { + Action::Quit => event_loop.exit(), + Action::Options => self.open_menu_options(Page::Main), + Action::Accessibility => self.open_menu_options(Page::Accessibility), + Action::Language => self.open_menu_options(Page::Language), + action => { + let name = self + .options + .as_ref() + .map_or_else(|| "Player".into(), |o| o.player_name()); + self.menu.queue_entry(action, name); + } + } + self.save_menu_address(); + } + + pub(super) fn menu_event( + &mut self, + event_loop: &ActiveEventLoop, + event: WindowEvent, + ) -> Result<()> { + if let WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } = &event + { + horizon_client::ui_theme::set_pressed(*state == ElementState::Pressed); + } + if let WindowEvent::KeyboardInput { event, .. } = &event + && let PhysicalKey::Code(key) = event.physical_key + { + if event.state == ElementState::Pressed { + self.menu.physical_keys.insert(key); + } else { + self.menu.physical_keys.remove(&key); + } + } + match event { + WindowEvent::CloseRequested => { + self.save_menu_settings(); + event_loop.exit(); + } + WindowEvent::Resized(size) => { + if let Some(r) = &mut self.renderer { + r.resize(size.width, size.height); + } + self.apply_menu_settings(); + } + WindowEvent::RedrawRequested => self.draw(), + WindowEvent::ModifiersChanged(modifiers) => self.menu.modifiers = modifiers.state(), + WindowEvent::Focused(false) => { + self.menu.modifiers = ModifiersState::empty(); + self.menu.physical_keys.clear(); + horizon_client::ui_theme::set_pressed(false); + self.menu.dragging = false; + if let Some(title) = &mut self.menu.title { + title.release(); + title.release_field(); + } + let events = self.menu.options.release(); + self.menu_option_events(events); + } + WindowEvent::KeyboardInput { event, .. } + if event.state == ElementState::Pressed && self.menu.pending.is_some() => + { + if event.physical_key == PhysicalKey::Code(KeyCode::Escape) { + self.menu.pending = None; + self.menu.perf.cancel_world_opening(); + } + } + _ if self.gui.is_none() || self.menu.pending.is_some() => {} + WindowEvent::CursorMoved { position, .. } => { + self.menu.pointer = (position.x, position.y); + self.update_menu_cursor(); + if self.menu.options_open && self.menu.dragging { + self.menu_options_click(true, false); + } else if let Some(title) = &mut self.menu.title { + let size = self + .renderer + .as_ref() + .map_or([1280, 720], |r| [r.config.width, r.config.height]); + let b = HudBatch::new(size); + title.drag(self.menu.cursor, (b.width, b.height)); + title.drag_field(&self.gui.as_ref().unwrap().atlas, self.menu.cursor.0); + } + } + WindowEvent::MouseInput { state, button, .. } if self.menu.options_open => { + if state == ElementState::Pressed && self.menu.options.selected_key.is_some() { + let events = self.menu.options.bind_mouse(&mut self.settings, button); + self.menu_option_events(events); + } else if matches!(button, MouseButton::Left | MouseButton::Right) { + if state == ElementState::Pressed { + self.menu.dragging = button == MouseButton::Left; + self.menu_options_click(false, button == MouseButton::Right); + } else if button == MouseButton::Left { + self.menu.dragging = false; + let events = self.menu.options.release(); + self.menu_option_events(events); + } + } + } + WindowEvent::MouseInput { + state, + button: MouseButton::Left, + .. + } => { + let mut batch = HudBatch::new(self.menu_size()); + if let (Some(title), Some(gui)) = (&mut self.menu.title, &self.gui) { + if state == ElementState::Released { + title.release(); + title.release_field(); + } else { + let action = if horizon_client::ui_theme::horizon() { + let action = title.click_horizon( + &gui.atlas, + &mut batch, + self.menu.cursor.0, + self.menu.cursor.1, + ); + // Horizon's deeper world-management pages use classic fields. + title.press_field( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + self.menu.modifiers.shift_key(), + ); + action + } else { + let (action, _) = title.click( + self.menu.cursor.0, + self.menu.cursor.1, + (batch.width, batch.height), + ); + title.press_field( + &gui.atlas, + self.menu.cursor, + (batch.width, batch.height), + self.menu.modifiers.shift_key(), + ); + action + }; + self.menu_action(event_loop, action); + } + } + } + WindowEvent::MouseWheel { delta, .. } => { + let raw = match delta { + MouseScrollDelta::LineDelta(_, y) => y, + MouseScrollDelta::PixelDelta(p) => (p.y / 30.0) as f32, + }; + let amount = if self.settings.discrete_scroll { + horizon_client::mouse::java_signum(f64::from(raw)) as f32 + } else { + raw + } * self.settings.mouse_wheel_sensitivity; + let batch = HudBatch::new(self.menu_size()); + if self.menu.options_open { + self.menu.options.scroll_at( + &self.settings, + (batch.width, batch.height), + self.menu.cursor, + amount, + ); + } else if let Some(title) = &mut self.menu.title { + title.scroll_worlds(amount, self.menu.cursor, (batch.width, batch.height)); + } + } + WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => { + if event.physical_key == PhysicalKey::Code(KeyCode::F11) { + self.settings.fullscreen = !self.settings.fullscreen; + self.apply_menu_settings(); + self.save_menu_settings(); + } else if self.menu.options_open { + let shortcut = self.menu.shortcut(&event); + let atlas = &self.gui.as_ref().unwrap().atlas; + let handled = shortcut.is_some_and(|s| { + self.menu + .options + .shortcut(atlas, s, &mut self.menu.clipboard) + }); + if !handled && let PhysicalKey::Code(key) = event.physical_key { + let events = self.menu.options.key( + &mut self.settings, + atlas, + key, + event.text.as_deref(), + ); + self.menu_option_events(events); + } + } else { + self.menu.title_key(&event); + self.save_menu_address(); + } + } + _ => {} + } + Ok(()) + } + + pub(super) fn draw_menu(&mut self, batch: &mut HudBatch) { + let Some(gui) = &self.gui else { return }; + if self.menu.pending.is_some() { + horizon_client::level_loading::draw_progress( + batch, + &gui.atlas, + self.progress.line(), + self.progress.fraction(), + ); + } else if self.menu.options_open { + self.menu + .options + .draw(&self.settings, batch, &gui.atlas, self.menu.cursor); + } else if let Some(title) = &mut self.menu.title { + title.poll_backup(); + let _ = title.update_toast(self.settings.notification_display_time); + if horizon_client::ui_theme::horizon() { + let mut ui = horizon_client::ui_theme::Ui::new(&gui.atlas, batch, self.menu.cursor); + title.draw_horizon(&mut ui, 0.0); + ui.finish(); + } else { + title.draw( + &gui.atlas, + batch, + self.menu.cursor, + self.settings.file.bool("hideSplashTexts"), + ); + } + } + } + + pub(super) fn restart_menu_resources(&mut self) -> Result<()> { + if !self.menu.reload_packs || self.loaded.is_none() { + return Ok(()); + } + if let Some(Ok(loaded)) = &mut self.loaded { + if let Some(loader) = &loaded.rest_loader + && !loader.ready()? + { + return Ok(()); + } + if let Some(loader) = loaded.rest_loader.take() + && let Err(error) = loader.finish() + { + log::warn!("Horizon: replaced resource generation failed: {error}"); + } + } + self.loaded = None; + if let Some(handle) = self.handle.take() { + handle.join().map_err(|_| "resource loader panicked")?; + } + self.progress = Progress::new(); + let options = self.options.as_ref().ok_or("loading already finished")?; + let (receiver, handle) = spawn_loader( + options, + &self.settings, + &self.vanilla_root, + self.started, + &self.progress, + )?; + self.receiver = receiver; + self.handle = Some(handle); + self.menu.reload_packs = false; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn gui(root: &std::path::Path) -> UiResources { + UiResources { + atlas: HudAtlas::fonts(root).unwrap(), + panorama: Arc::new(horizon_client::gfx::panorama::Faces { + size: 1, + pixels: [96, 110, 111, 255].repeat(6), + }), + } + } + + fn loading(receiver: Receiver<LoaderMsg>) -> Loading { + Loading { + window: None, + renderer: None, + gui: None, + settings: Settings::default(), + fullscreen: horizon_client::window::FullscreenState::new(false), + options: None, + vanilla_root: PathBuf::new(), + pack_error: None, + started: Instant::now(), + progress: Progress::new(), + receiver, + loaded: None, + handle: None, + shown: false, + menu: StartupMenu::default(), + error: None, + } + } + + #[test] + fn menu_is_usable_while_the_core_worker_is_blocked() { + let root = std::env::temp_dir().join("horizon-startup-menu-no-world-resources"); + let (sender, receiver) = std::sync::mpsc::channel(); + let (release, wait) = std::sync::mpsc::channel(); + let (published, published_rx) = std::sync::mpsc::channel(); + let worker_root = root.clone(); + let worker = std::thread::spawn(move || { + sender + .send(LoaderMsg::Ui(gui(&worker_root), worker_root)) + .unwrap(); + published.send(()).unwrap(); + wait.recv().unwrap(); + sender + .send(LoaderMsg::Done(Err("core failure".into()))) + .unwrap(); + }); + published_rx.recv().unwrap(); + let mut loading = loading(receiver); + loading.poll_menu_resources().unwrap(); + assert!(loading.gui.is_some()); + assert!(loading.loaded.is_none()); + assert!(!worker.is_finished()); + // Navigate and enter a world name without a registry, biomes, pack + // tables or a Game. Replacing fallback artwork preserves this state. + let title = loading.menu.title.as_mut().unwrap(); + title.opening.set(None); + title.mode = horizon_client::title::Mode::Create { + name: String::new(), + seed: "42".into(), + creative: true, + focus: 0, + options: Default::default(), + }; + title.type_text("My world"); + loading.set_ui(gui(&root), root); + let action = loading.menu.title.as_ref().unwrap().create_action(); + loading.menu.queue_entry(action, "Player".into()); + assert!( + matches!(&loading.menu.pending, Some(PendingWorldEntry::Local { + name: Some(name), seed: Some(42), creative: true, create: Some(_), .. + }) if name == "My world") + ); + let mut batch = HudBatch::new([1280, 720]); + loading.draw_menu(&mut batch); + assert!( + !batch.vertices.is_empty(), + "queued entry draws loading progress" + ); + release.send(()).unwrap(); + worker.join().unwrap(); + loading.poll_menu_resources().unwrap(); + assert!(matches!(loading.loaded, Some(Err(ref error)) if error == "core failure")); + } + + #[test] + fn queued_server_keeps_address_and_player_identity() { + let mut menu = StartupMenu::default(); + menu.queue_entry( + Action::Connect { + address: "localhost:25565".into(), + }, + "Guest".into(), + ); + assert!( + matches!(menu.pending.take(), Some(PendingWorldEntry::Server { address, name }) + if address == "localhost:25565" && name == "Guest") + ); + assert!(menu.pending.take().is_none(), "an entry is consumed once"); + } + + #[test] + fn disconnected_core_worker_is_reported_instead_of_waiting_forever() { + let (sender, receiver) = std::sync::mpsc::channel(); + drop(sender); + let mut loading = loading(receiver); + assert_eq!( + loading.poll_menu_resources().unwrap_err().to_string(), + "resource loader stopped before finishing" + ); + } +} diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index 680939a4f..75ad9225e 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -126,7 +126,7 @@ impl Game<'_> { "enchant" => { let e = id(arg(1)?); let level: u32 = arg(2)?.parse()?; - if self.res.stations.enchantments.get(&e).is_none() { + if self.res.stations().enchantments.get(&e).is_none() { return Err(format!("unknown enchantment {e}").into()); } let held = self.inventory[self.selected] diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 7b70cb1f1..e8872b159 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -263,7 +263,7 @@ fn argb(c: i32) -> u32 { impl Game<'_> { fn data(&self) -> &stations::StationData { - &self.res.stations + self.res.stations() } pub(super) fn translate(&self, key: &str, fallback: &str) -> String { self.data() @@ -376,9 +376,13 @@ impl Game<'_> { } } fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { - let tags = &self.res.items.block_tags; + let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { - let name = &self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; tags.get(tag).is_some_and(|t| t.contains(&**name)) }; stations::bookshelf_offsets() @@ -412,8 +416,8 @@ impl Game<'_> { return; }; let creative = self.creative; - let data = &self.res.stations; - let items = &self.res.items; + let data = self.res.stations(); + let items = self.res.items(); match s.kind { Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); @@ -494,7 +498,10 @@ impl Game<'_> { self.station = Some(s); } pub(super) fn max_stack(&self, stack: &ItemStack) -> u32 { - self.res.items.get(&stack.item).map_or(64, |i| i.max_stack) + self.res + .items() + .get(&stack.item) + .map_or(64, |i| i.max_stack) } /// `Slot.mayPlace` and `getMaxStackSize` for station and brewing slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { @@ -518,7 +525,7 @@ impl Game<'_> { 3 => (data.brewing.is_reagent(stack), 64), _ => ( self.res - .items + .items() .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()), 64, @@ -548,7 +555,7 @@ impl Game<'_> { 64, ), Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(&self.res.items, stack), 64), + Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), _ => (true, 64), } @@ -667,7 +674,7 @@ impl Game<'_> { let data = self.data(); let fuel = self .res - .items + .items() .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()); let (reagent, bottle) = ( @@ -818,7 +825,7 @@ impl Game<'_> { if !self.creative && self.world.random.next_float() < 0.12 { // AnvilBlock.damage let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let next = match &*name { "minecraft:anvil" => Some("minecraft:chipped_anvil"), "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), @@ -848,7 +855,7 @@ impl Game<'_> { let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); let mut random = LegacyRandom::new(self.world.random.next_long()); let xp = stations::grindstone_experience( - &self.res.stations.enchantments, + &self.res.stations().enchantments, &mut random, a.as_ref(), b.as_ref(), @@ -945,7 +952,7 @@ impl Game<'_> { Some(c) if c.same_item_same_components(&result) && c.count + result.count - <= self.res.items.get(&c.item).map_or(64, |i| i.max_stack) => + <= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) => { c.count += result.count } @@ -988,8 +995,8 @@ impl Game<'_> { return; } let Some(enchanted) = stations::apply_enchantment( - &self.res.stations.enchantments, - &self.res.items, + &self.res.stations().enchantments, + self.res.items(), self.level.xp_seed, button, cost, @@ -1051,7 +1058,8 @@ impl Game<'_> { } } pub(super) fn station_click(&mut self, right: bool) -> bool { - if self.station.is_none() && !self.brewing_open() { + // A server's brewing stand: its slots are the server's. + if self.station.is_none() && (!self.brewing_open() || self.remote.is_some()) { return false; } let Some(size) = self @@ -1249,7 +1257,7 @@ impl Game<'_> { } /// Text in the Standard Galactic alphabet (`minecraft:alt`), cut to `max` pixels. fn galactic(&self, batch: &mut HudBatch, text: &str, x: f32, y: f32, max: f32, color: u32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let Some(sheet) = atlas.sprites.get("font/ascii_sga").copied() else { batch.text(atlas, text, x, y, color, false); return; @@ -1325,7 +1333,7 @@ impl Game<'_> { let local = (self.cursor.0 - ox, self.cursor.1 - oy); let mut tooltip: Option<Vec<(String, u32)>> = None; { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -1342,7 +1350,7 @@ impl Game<'_> { }; let (fuel, total_fuel, brew, total_brew) = (b.fuel, b.total_fuel, b.brew_time, b.total_brew_time); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; Self::part( batch, atlas, @@ -1396,6 +1404,7 @@ impl Game<'_> { .as_ref() .and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2]))) .cloned() + .or_else(|| self.remote_menu_title()) .unwrap_or(default); let tw = HudBatch::text_width(atlas, &title); batch.text( @@ -1417,7 +1426,7 @@ impl Game<'_> { if self.slot_mut(i).is_none() { let (sx, sy) = self.station_slot_position(i).unwrap_or_default(); batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/slot/{icon}"), ox + sx, oy + sy, @@ -1427,7 +1436,7 @@ impl Game<'_> { } else if let Some(kind) = self.station.as_ref().map(|s| s.kind) { let title = self.translate(kind.title_key(), ""); { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; Self::part( batch, atlas, @@ -1446,7 +1455,7 @@ impl Game<'_> { if kind == Kind::Loom { tooltip = self.draw_loom(batch, ox, oy, local); } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let s = self.station.as_ref().expect("open station"); let has_input = s.inputs.iter().any(Option::is_some); match kind { @@ -1552,7 +1561,7 @@ impl Game<'_> { ); -8323296 }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let cw = HudBatch::text_width(atlas, &cost_text); batch.text( atlas, @@ -1566,7 +1575,7 @@ impl Game<'_> { if inside(local, bx, by, bw, 17.0) && let Some((id, l)) = &offers.clues[i] { - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let (name, _) = e.full_name(id, *l); let clue = self .translate("container.enchant.clue", "%s . . . ?") @@ -1679,7 +1688,7 @@ impl Game<'_> { ) }; if let Some(line) = line { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let tw = HudBatch::text_width(atlas, &line); let tx = 176.0 - 8.0 - tw - 2.0; batch.fill( @@ -1766,7 +1775,7 @@ impl Game<'_> { i, ItemStack { count: 1, - ..self.res.stations.recipes.stonecutting[s.recipes[i]] + ..self.res.stations().recipes.stonecutting[s.recipes[i]] .result .clone() }, @@ -1788,7 +1797,7 @@ impl Game<'_> { "recipe" }; batch.sprite_scaled( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/stonecutter/{sprite}"), ox + x, oy + y - 1.0, @@ -1816,7 +1825,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -1858,7 +1867,7 @@ impl Game<'_> { /// `ItemStack.getTooltipLines` subset: name in rarity colour, potion /// effects, enchantments (gray, curses red), stored enchantments, trims. pub(super) fn stack_tooltip(&self, stack: &ItemStack) -> Vec<(String, u32)> { - let e: &Enchantments = &self.res.stations.enchantments; + let e: &Enchantments = &self.res.stations().enchantments; let props = e.props(&stack.item); let rarity = horizon_client::item_tooltip::rarity( stack, @@ -1968,7 +1977,7 @@ impl Game<'_> { // BannerPatternLayers.addToTooltip: up to six layer names. 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); + let key = self.res.stations().banners.layer_key(layer); lines.push((self.translate(&key, &key), rgba(170, 170, 170, 255))); } } @@ -1996,7 +2005,7 @@ impl Game<'_> { } } if display.shows("minecraft:attribute_modifiers") - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) { let base = |name: &str, default| { self.player @@ -2026,7 +2035,7 @@ impl Game<'_> { )); } if display.shows("minecraft:damage") - && let Some(info) = self.res.items.get(&stack.item) + && let Some(info) = self.res.items().get(&stack.item) && info.max_damage > 0 && stack.damage > 0 && self.options_advanced_tooltips() @@ -2068,7 +2077,7 @@ impl Game<'_> { _ => serde_json::Value::Null, }; }; - let recipes = &self.res.stations.recipes.stonecutting; + let recipes = &self.res.stations().recipes.stonecutting; serde_json::json!({ "costs": s.offers.costs, "clues": s.offers.clues.iter().map(|c| c.as_ref().map(|(e, l)| format!("{e} {l}"))).collect::<Vec<_>>(), @@ -2094,7 +2103,7 @@ impl Game<'_> { if lines.is_empty() { return; } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let w = lines .iter() .map(|(t, _)| HudBatch::text_width(atlas, t)) @@ -2183,9 +2192,9 @@ impl Game<'_> { return Ok(()); }; let out = b.tick( - &self.res.stations.brewing, - &self.res.items, - &self.res.providers, + &self.res.stations().brewing, + self.res.items(), + self.res.providers(), ); if out != brewing::BrewTick::default() { let (x, y, z) = pos; diff --git a/crates/horizon-client/src/game/stats.rs b/crates/horizon-client/src/game/stats.rs index c36b99eaa..7a97416ca 100644 --- a/crates/horizon-client/src/game/stats.rs +++ b/crates/horizon-client/src/game/stats.rs @@ -20,22 +20,50 @@ pub(super) struct Stats { /// Statistic changes (type, key, amount; `None` = reset) for the /// scoreboard criteria to follow. pub(super) events: Vec<(String, String, Option<i32>)>, - /// Changed since the client was last sent them (`StatsCounter`'s dirty set). - pub(super) dirty: BTreeSet<(String, String)>, + /// Changed since the client was last sent them (`StatsCounter`'s dirty + /// set), by type. + dirty: BTreeMap<String, BTreeSet<String>>, } + +/// `minecraft:` and `name`, given to `f` from the stack when short: some +/// counters go up every tick for every player, and they are found without +/// a string made for each. +fn namespaced<T>(name: &str, f: impl FnOnce(&str) -> T) -> T { + const NAMESPACE: &str = "minecraft:"; + let mut buf = [0u8; 96]; + let len = NAMESPACE.len() + name.len(); + if len > buf.len() { + return f(&format!("{NAMESPACE}{name}")); + } + buf[..NAMESPACE.len()].copy_from_slice(NAMESPACE.as_bytes()); + buf[NAMESPACE.len()..len].copy_from_slice(name.as_bytes()); + // Two strings one after the other are one. + f(std::str::from_utf8(&buf[..len]).unwrap_or_default()) +} + +/// The map under `key`, made when missing, found without an owned key +/// when there. +fn entry<'a, V: Default>(map: &'a mut BTreeMap<String, V>, key: &str) -> &'a mut V { + if !map.contains_key(key) { + map.insert(key.to_owned(), V::default()); + } + map.get_mut(key).expect("just inserted") +} + impl Stats { pub(super) fn add(&mut self, ty: &str, key: &str, n: i32) { - let v = self - .values - .entry(format!("minecraft:{ty}")) - .or_default() - .entry(key.to_owned()) - .or_insert(0); - *v = v.saturating_add(n); - self.events - .push((format!("minecraft:{ty}"), key.to_owned(), Some(n))); - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + namespaced(ty, |ty| { + let v = entry(entry(&mut self.values, ty), key); + *v = v.saturating_add(n); + self.events.push((ty.to_owned(), key.to_owned(), Some(n))); + self.mark_dirty(ty, key); + }); + } + fn mark_dirty(&mut self, ty: &str, key: &str) { + let keys = entry(&mut self.dirty, ty); + if !keys.contains(key) { + keys.insert(key.to_owned()); + } } pub(super) fn get(&self, ty: &str, key: &str) -> i32 { self.values @@ -48,20 +76,19 @@ impl Stats { if let Some(m) = self.values.get_mut(&format!("minecraft:{ty}")) { m.insert(key.to_owned(), 0); } - self.dirty - .insert((format!("minecraft:{ty}"), key.to_owned())); + self.mark_dirty(&format!("minecraft:{ty}"), key); self.events .push((format!("minecraft:{ty}"), key.to_owned(), None)); } pub(super) fn custom(&mut self, key: &str, n: i32) { - self.add("custom", &format!("minecraft:{key}"), n); + namespaced(key, |key| self.add("custom", key, n)); } /// `ServerStatsCounter.markAllDirty`: everything goes out on the next request. pub(super) fn mark_all_dirty(&mut self) { self.dirty = self .values .iter() - .flat_map(|(ty, m)| m.keys().map(|k| (ty.clone(), k.clone()))) + .map(|(ty, m)| (ty.clone(), m.keys().cloned().collect())) .collect(); } /// `ServerStatsCounter.sendStats`' entries: the dirty statistics and @@ -69,6 +96,7 @@ impl Stats { pub(super) fn take_dirty(&mut self) -> Vec<(String, String, i32)> { std::mem::take(&mut self.dirty) .into_iter() + .flat_map(|(ty, keys)| keys.into_iter().map(move |key| (ty.clone(), key))) .map(|(ty, key)| { let v = self.values.get(&ty).and_then(|m| m.get(&key)).copied(); (ty, key, v.unwrap_or(0)) @@ -216,14 +244,14 @@ impl Game<'_> { p.position.y.floor() as i32, p.position.z.floor() as i32, ]; - let eye_in_water = self.res.facts.get(self.world.block( + let eye_in_water = self.res.facts().get(self.world.block( feet[0], (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32, feet[2], )); let in_water = self .res - .facts + .facts() .get(self.world.block(feet[0], feet[1], feet[2])) .fluid == horizon_client::blocks::Fluid::Water; @@ -317,7 +345,11 @@ impl Game<'_> { pos[1] + 20 + r.next_int_bound(15).unwrap_or(0), pos[2] - 10 + r.next_int_bound(21).unwrap_or(10), ]; - if !self.res.facts.is_air(self.world.block(at[0], at[1], at[2])) { + if !self + .res + .facts() + .is_air(self.world.block(at[0], at[1], at[2])) + { return; } let group = 1 + self.world.random.next_int_bound(3).unwrap_or(0); @@ -335,8 +367,59 @@ impl Game<'_> { } fn can_see_sky(&self, pos: [i32; 3]) -> bool { (pos[1] + 1..pos[1] + 256).all(|y| { - let f = self.res.facts.get(self.world.block(pos[0], y, pos[2])); + let f = self.res.facts().get(self.world.block(pos[0], y, pos[2])); !f.full_collision && f.fluid == horizon_client::blocks::Fluid::None }) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counters_events_and_dirty_entries() { + let mut s = Stats::default(); + s.custom("play_time", 1); + s.custom("play_time", 1); + s.add("mined", "minecraft:stone", 2); + s.custom(&"x".repeat(100), 3); + assert_eq!(s.get("custom", "minecraft:play_time"), 2); + assert_eq!(s.get("mined", "minecraft:stone"), 2); + assert_eq!( + s.get("custom", &format!("minecraft:{}", "x".repeat(100))), + 3 + ); + assert_eq!(s.events.len(), 4); + assert_eq!( + s.events[1], + ( + "minecraft:custom".into(), + "minecraft:play_time".into(), + Some(1) + ) + ); + let long = format!("minecraft:{}", "x".repeat(100)); + let sent = |v: &[(&str, &str, i32)]| -> Vec<(String, String, i32)> { + v.iter() + .map(|&(t, k, n)| (t.to_owned(), k.to_owned(), n)) + .collect() + }; + assert_eq!( + s.take_dirty(), + sent(&[ + ("minecraft:custom", "minecraft:play_time", 2), + ("minecraft:custom", &long, 3), + ("minecraft:mined", "minecraft:stone", 2), + ]) + ); + assert!(s.take_dirty().is_empty()); + s.reset("mined", "minecraft:stone"); + assert_eq!( + s.take_dirty(), + sent(&[("minecraft:mined", "minecraft:stone", 0)]) + ); + s.mark_all_dirty(); + assert_eq!(s.take_dirty().len(), 3); + } +} diff --git a/crates/horizon-client/src/game/stats_screen.rs b/crates/horizon-client/src/game/stats_screen.rs index 40b151453..5505d423d 100644 --- a/crates/horizon-client/src/game/stats_screen.rs +++ b/crates/horizon-client/src/game/stats_screen.rs @@ -222,7 +222,7 @@ impl Game<'_> { } pub(super) fn draw_stats(&mut self, batch: &mut HudBatch) { let (w, h) = (batch.width, batch.height); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::menu_background(batch, atlas, 0.0, 0.0, w, h, true); let (top, bottom) = (TAB_H, h - FOOTER); ui::separators(batch, atlas, top, bottom, true); @@ -333,13 +333,13 @@ impl Game<'_> { } let stack = ItemStack::new(item, 1); batch.sprite( - &self.atlas, + &self.gui.atlas, "gui/sprites/container/slot", left + 1.0, y + 1.0, ); self.draw_item(batch, &stack, left + 2.0, y + 2.0); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let color = if (i + 1) % 2 == 0 { u32::MAX } else { @@ -347,8 +347,12 @@ impl Game<'_> { }; for (c, (ty, _)) in COLUMNS.iter().enumerate() { let x = left + 75.0 + 40.0 * c as f32; - let block = - c == 0 && self.res.items.get(item).is_some_and(|i| i.block.is_some()); + let block = c == 0 + && self + .res + .items() + .get(item) + .is_some_and(|i| i.block.is_some()); let text = if c == 0 && !block { Text::translate("stats.none", &[]).plain() } else { @@ -400,7 +404,7 @@ impl Game<'_> { } } } - let atlas = &self.atlas; + let atlas = &self.gui.atlas; ui::scrollbar( batch, atlas, @@ -413,7 +417,7 @@ impl Game<'_> { self.draw_stats_footer(batch, w, h); } fn draw_stats_footer(&self, batch: &mut HudBatch, w: f32, h: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let (bx, by) = ((w / 2.0 - 100.0).floor(), h - FOOTER + 6.0); let hover = ui::hovered(self.cursor, bx, by, 200.0, 20.0); ui::button( diff --git a/crates/horizon-client/src/game/storage.rs b/crates/horizon-client/src/game/storage.rs index 44b62e276..9b28ce26b 100644 --- a/crates/horizon-client/src/game/storage.rs +++ b/crates/horizon-client/src/game/storage.rs @@ -22,7 +22,7 @@ impl Game<'_> { (300..400).contains(&slot) && is_shulker_box(&stack.item) && self.container.is_some_and(|k| { - is_shulker_box(&self.res.facts.get(self.world.block(k.0, k.1, k.2)).name) + is_shulker_box(&self.res.facts().get(self.world.block(k.0, k.1, k.2)).name) }) } /// Opening an ender chest shows the player's ender inventory in its place. @@ -160,7 +160,7 @@ impl Game<'_> { let k = self.container?; Some( self.res - .facts + .facts() .get(self.world.block(k.0, k.1, k.2)) .name .clone(), @@ -211,7 +211,7 @@ impl Game<'_> { oy: f32, ) { use horizon_client::hud::rgba; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let grey = rgba(64, 64, 64, 255); if self .container_block() diff --git a/crates/horizon-client/src/game/subtitle_hud.rs b/crates/horizon-client/src/game/subtitle_hud.rs index cf89a4b15..f54ca874d 100644 --- a/crates/horizon-client/src/game/subtitle_hud.rs +++ b/crates/horizon-client/src/game/subtitle_hud.rs @@ -47,7 +47,7 @@ impl Game<'_> { width: batch.width as i32, height: batch.height as i32, }; - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let draws = self .subtitles .overlay diff --git a/crates/horizon-client/src/game/sulfur_cubes.rs b/crates/horizon-client/src/game/sulfur_cubes.rs index c4cee6319..d1bf9def9 100644 --- a/crates/horizon-client/src/game/sulfur_cubes.rs +++ b/crates/horizon-client/src/game/sulfur_cubes.rs @@ -52,7 +52,7 @@ impl Game<'_> { } // 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 { + let Some(state) = self.res.items().get(item).and_then(|item| item.block) else { return; }; let start = out.len(); @@ -60,7 +60,7 @@ impl Game<'_> { state, 42, block_transform(base, mob.is_baby()), - block_light(light, self.res.facts.get(state).emission), + block_light(light, self.res.facts().get(state).emission), true, out, ); diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 459aab503..70ade5595 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -16,10 +16,10 @@ impl Game<'_> { let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; let background = self.settings.text_background(0.0); - let font = &self.atlas.font; + let font = &self.gui.atlas.font; let mut draws = self.titles.overlay_message(w, h, partial, font, background); draws.extend(self.titles.title(w, h, partial, font, background)); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } /// The selected stack as `Hud.tick` compares it for the name highlight. fn held_name(&self) -> Option<HeldName> { @@ -54,9 +54,9 @@ impl Game<'_> { batch.width as i32, batch.height as i32, can_hurt, - &self.atlas.font, + &self.gui.atlas.font, self.settings.text_background(0.0), ); - hud_layout::paint(batch, &self.atlas, &draws); + hud_layout::paint(batch, &self.gui.atlas, &draws); } } diff --git a/crates/horizon-client/src/game/tnt.rs b/crates/horizon-client/src/game/tnt.rs index c47c17de9..80ad97d7f 100644 --- a/crates/horizon-client/src/game/tnt.rs +++ b/crates/horizon-client/src/game/tnt.rs @@ -156,13 +156,19 @@ impl Game<'_> { pub(super) fn tick_tnt(&mut self) -> Result<()> { let mut count = self.tnts.len(); let mut i = 0; + // ServerLevel.tick: only entities in entity-ticking chunks tick. + let ticking = self.entity_ticking_area(); while i < count { let t = &mut self.tnts[i]; + if !ticking(t.position.x.floor() as i32, t.position.z.floor() as i32) { + i += 1; + continue; + } t.tick( &self.world, self.collision, &self.pack.assets, - &self.res.facts, + self.res.facts(), )?; if t.fuse <= 0 { let center = [ @@ -189,7 +195,7 @@ impl Game<'_> { return Ok(false); }; let state = self.world.block(hit.pos[0], hit.pos[1], hit.pos[2]); - if &*self.res.facts.get(state).name != "minecraft:tnt" { + if &*self.res.facts().get(state).name != "minecraft:tnt" { return Ok(false); } let pos = BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]); @@ -219,7 +225,7 @@ impl Game<'_> { // Face sprites from the block model: up, down, north, south, west, east. let Ok(models) = self .pack - .assets + .render .model_catalog .collect(state, BlockPos::new(0, 0, 0)) else { @@ -241,7 +247,7 @@ impl Game<'_> { .pack .layer_names .get(&face.layer) - .and_then(|name| self.atlas.sprites.get(name).copied()); + .and_then(|name| self.gui.atlas.sprites.get(name).copied()); } } let range = super::entity_culling::default_range( @@ -487,9 +493,10 @@ mod tests { return; } let assets = horizon_client::assets::Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = horizon_client::blocks::BlockFacts::load(&root, assets.registry).unwrap(); let collision = horizon_client::collisions::load(&root, assets.registry).unwrap(); - let mut world = horizon_client::world::World::test_scene(&assets, 3).unwrap(); + let mut world = horizon_client::world::World::test_scene(&assets, &render, 3).unwrap(); let stone = assets.registry.default_state("minecraft:stone").unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); let mut state = assets.registry.state(water).unwrap().clone(); diff --git a/crates/horizon-client/src/game/trading.rs b/crates/horizon-client/src/game/trading.rs index ce389ac84..87e0c18c6 100644 --- a/crates/horizon-client/src/game/trading.rs +++ b/crates/horizon-client/src/game/trading.rs @@ -147,7 +147,7 @@ impl Game<'_> { variant: &str, origin: [f64; 3], ) -> Vec<MerchantOffer> { - let Some(sequence) = self.res.stations.trades.sequence(set) else { + let Some(sequence) = self.res.stations().trades.sequence(set) else { return Vec::new(); }; let mut random = self.rand_sequences.lend(&sequence, self.level.seed); @@ -160,15 +160,15 @@ impl Game<'_> { next_id: std::cell::Cell::new(next_map), }; let ctx = TradeContext { - items: &self.res.items, - enchantments: &self.res.stations.enchantments, + items: self.res.items(), + enchantments: &self.res.stations().enchantments, variant, origin, maps: Some(&maps), }; let offers = self .res - .stations + .stations() .trades .offers_from_set(&ctx, set, &mut random); let made = maps.made.into_inner(); @@ -205,7 +205,7 @@ impl Game<'_> { let profession = PROFESSIONS[m.extra.variant2 as usize % PROFESSIONS.len()]; let level = i32::from(m.extra.variant3.max(1)); let set = merchant::Trades::set_for(profession, level); - if self.res.stations.trades.sets.contains_key(&set) { + if self.res.stations().trades.sets.contains_key(&set) { self.offers_from_set(&set, &variant, origin) } else { Vec::new() @@ -284,7 +284,7 @@ impl Game<'_> { session.reputation = self.villager_reputation(id); session.hero = self.hero_amplifier(); for seq in merchant::Session::sequences_needed( - &self.res.stations.trades, + &self.res.stations().trades, &session.profession, level, ) { @@ -547,8 +547,8 @@ impl Game<'_> { m.focused, ); let offers = m.session.offers.clone(); - let costs: Vec<ItemStack> = offers.iter().map(|o| o.cost_a(&self.res.items)).collect(); - let atlas = &self.atlas; + let costs: Vec<ItemStack> = offers.iter().map(|o| o.cost_a(self.res.items())).collect(); + let atlas = &self.gui.atlas; batch.fill( atlas, 0.0, @@ -563,7 +563,7 @@ impl Game<'_> { r.v1 = r.v0 + 166.0 * dv; batch.rect_uv(ox + SHIFT, oy, 276.0, 166.0, r, u32::MAX); } - let e = &self.res.stations.enchantments; + let e = &self.res.stations().enchantments; let tr = |k: &str, f: &str| e.translate(k).unwrap_or(f).to_owned(); let name = custom.unwrap_or_else(|| { if progress { @@ -687,7 +687,7 @@ impl Game<'_> { } else { "gui/sprites/widget/button" }; - batch.sprite_scaled(&self.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); + batch.sprite_scaled(&self.gui.atlas, sprite, bx, by, 88.0, 20.0, u32::MAX); let y = oy + 16.0 + 1.0 + 20.0 * row as f32 + 2.0; let base = offer.base_cost_a.stack.clone(); let cost_a = costs[index].clone(); @@ -705,7 +705,7 @@ impl Game<'_> { x, y, ); - let atlas = &self.atlas; + let atlas = &self.gui.atlas; let t = base.count.to_string(); batch.text( atlas, @@ -740,7 +740,7 @@ impl Game<'_> { "trade_arrow" }; batch.sprite( - &self.atlas, + &self.gui.atlas, &format!("gui/sprites/container/villager/{arrow}"), ox + SHIFT + 60.0, y + 3.0, @@ -770,7 +770,7 @@ impl Game<'_> { if let Some(slot) = self.slot_at(batch, self.cursor.0, self.cursor.1) { let (sx, sy) = self.slot_position(slot); batch.fill( - &self.atlas, + &self.gui.atlas, ox + sx, oy + sy, 16.0, @@ -794,7 +794,7 @@ impl Game<'_> { } else if deprecated { let text = self .res - .stations + .stations() .enchantments .translate("merchant.deprecated") .unwrap_or("Villagers restock up to two times per day.") diff --git a/crates/horizon-client/src/game/trident.rs b/crates/horizon-client/src/game/trident.rs index 0dee8d22a..b24f4540e 100644 --- a/crates/horizon-client/src/game/trident.rs +++ b/crates/horizon-client/src/game/trident.rs @@ -98,7 +98,7 @@ impl Game<'_> { } let max = self .res - .items + .items() .get(&stack.item) .map_or(250, |i| i.max_damage); let riptide = stack.enchantment_level("minecraft:riptide") > 0; @@ -117,7 +117,7 @@ impl Game<'_> { p.position.y.floor() as i32, p.position.z.floor() as i32, ); - let water = self.res.facts.get(self.world.block(x, y, z)).fluid + let water = self.res.facts().get(self.world.block(x, y, z)).fluid == horizon_client::blocks::Fluid::Water; let sky = self.world.light(x, y + 1, z) >> 4 == 15; water || (self.world.weather.raining && sky) @@ -372,6 +372,7 @@ impl Game<'_> { return; }; let Some(uv) = self + .gui .atlas .sprites .get("entity/trident/trident") diff --git a/crates/horizon-client/src/game/tweaks.rs b/crates/horizon-client/src/game/tweaks.rs index f15aa9ea7..681368cab 100644 --- a/crates/horizon-client/src/game/tweaks.rs +++ b/crates/horizon-client/src/game/tweaks.rs @@ -323,7 +323,7 @@ impl Game<'_> { /// The sort buttons: a bordered square with three bars, lighter under /// the cursor. pub(super) fn draw_sort_buttons(&self, batch: &mut HudBatch, ox: f32, oy: f32) { - let atlas = &self.atlas; + let atlas = &self.gui.atlas; for ((x, y), _) in self.sort_buttons() { let (x, y) = (ox + x, oy + y); let (cx, cy) = self.cursor; diff --git a/crates/horizon-client/src/game/villagers.rs b/crates/horizon-client/src/game/villagers.rs index 72fa2839a..5c6bed394 100644 --- a/crates/horizon-client/src/game/villagers.rs +++ b/crates/horizon-client/src/game/villagers.rs @@ -40,7 +40,7 @@ impl Game<'_> { .position(|m| m.id == id && m.species() == Species::Villager) } fn item_max_stack(&self, item: &str) -> u32 { - self.res.items.get(item).map_or(64, |i| i.max_stack) + self.res.items().get(item).map_or(64, |i| i.max_stack) } /// `BehaviorUtils.throwItem`: toss a stack from a villager's hand toward /// a point. @@ -57,7 +57,7 @@ impl Game<'_> { return; }; let now = self.world.game_time; - let items = &self.res.items; + let items = self.res.items(); let meeting = villager::meet(&mut self.mobs, ia, ib, now, |item| { items.get(item).map_or(64, |i| i.max_stack) }); @@ -121,13 +121,13 @@ impl Game<'_> { for _ in 0..=12 { y -= 1; let here = self.world.block(x, y, z); - let f = self.res.facts.get(here); - let above_f = self.res.facts.get(above); - let air_or_liquid = self.res.facts.is_air(above) + let f = self.res.facts().get(here); + let above_f = self.res.facts().get(above); + let air_or_liquid = self.res.facts().is_air(above) || above_f.fluid != horizon_client::blocks::Fluid::None; - let solid = self.res.mob_data.state(here).flags & horizon_client::mobs::data::SOLID - != 0 - || f.name.as_ref() == "minecraft:powder_snow"; + let solid = + self.res.mob_data().state(here).flags & horizon_client::mobs::data::SOLID != 0 + || f.name.as_ref() == "minecraft:powder_snow"; if golem_floor_ok(&f.name) && air_or_liquid && solid { found = Some(y + 1); break; @@ -137,7 +137,7 @@ impl Game<'_> { let Some(y) = found else { continue }; // IronGolem.checkSpawnRules: a floor and three free blocks. let free = |g: &Self, yy: i32| { - g.res.mob_data.state(g.world.block(x, yy, z)).flags + g.res.mob_data().state(g.world.block(x, yy, z)).flags & horizon_client::mobs::data::VALID_EMPTY_SPAWN != 0 }; @@ -260,7 +260,7 @@ impl Game<'_> { } let picks_up = self .res - .items + .items() .item_tags .get("minecraft:villager_picks_up") .cloned(); diff --git a/crates/horizon-client/src/game/wandering_trader.rs b/crates/horizon-client/src/game/wandering_trader.rs index b336cdf0b..87ca5753b 100644 --- a/crates/horizon-client/src/game/wandering_trader.rs +++ b/crates/horizon-client/src/game/wandering_trader.rs @@ -6,7 +6,7 @@ use horizon_client::{ mobs::{Species, leash::Holder, spawning, trader}, save::{read_dat, write_dat}, }; -use horizon_core::random::RandomSource; +use horizon_core::{geometry::Vec3, random::RandomSource}; use horizon_world::nbt::Tag; const TICK_DELAY: i32 = 1200; @@ -83,10 +83,7 @@ impl Game<'_> { } /// `WanderingTraderSpawner.tick`. pub(super) fn tick_wandering_trader(&mut self) { - if self.dim != Dim::Overworld - || self.player.is_none() - || !self.ui.rules.bool("spawn_wandering_traders") - { + if self.dim != Dim::Overworld || !self.ui.rules.bool("spawn_wandering_traders") { return; } self.load_trader_data(); @@ -110,9 +107,23 @@ impl Game<'_> { } /// `WanderingTraderSpawner.spawn`. fn spawn_trader(&mut self) -> bool { - let Some(p) = self.player.as_ref().map(|p| p.position) else { + // ServerLevel.getRandomPlayer: one of the living players, drawn + // from the level random. + let alive: Vec<Vec3> = self + .level_players() + .into_iter() + .filter(|p| p.alive) + .map(|p| p.position) + .collect(); + if alive.is_empty() { return true; - }; + } + let pick = self + .world + .random + .next_int_bound(alive.len() as i32) + .unwrap_or(0); + let p = alive[pick as usize]; if self.world.random.next_int_bound(10).unwrap_or(1) != 0 { return false; } @@ -126,14 +137,14 @@ impl Game<'_> { } let biome = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)).map(|c| { self.res - .biomes + .biomes() .get(c.biome(pos[0], pos[1], pos[2])) .name .clone() }); if biome.is_some_and(|b| { self.res - .mob_data + .mob_data() .biome_has("minecraft:without_wandering_trader_spawns", &b) }) { return false; @@ -214,7 +225,7 @@ impl Game<'_> { (0..=1).all(|dz| { !self .res - .facts + .facts() .get(self.world.block(pos[0] + dx, pos[1] + dy, pos[2] + dz)) .full_collision }) @@ -230,7 +241,7 @@ impl Game<'_> { continue; } for y in (from[1] - range).max(horizon_client::chunk::MIN_Y)..=from[1] + range { - if &*self.res.facts.get(self.world.block(x, y, z)).name != "minecraft:bell" { + if &*self.res.facts().get(self.world.block(x, y, z)).name != "minecraft:bell" { continue; } let d = (x - from[0]).pow(2) + (y - from[1]).pow(2) + (z - from[2]).pow(2); diff --git a/crates/horizon-client/src/game/wind.rs b/crates/horizon-client/src/game/wind.rs index 07759944f..355b5b877 100644 --- a/crates/horizon-client/src/game/wind.rs +++ b/crates/horizon-client/src/game/wind.rs @@ -141,7 +141,7 @@ impl Game<'_> { fn wind_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> { let stops = self .res - .items + .items() .block_tags .get("minecraft:blocks_wind_charge_explosions") .cloned() @@ -176,7 +176,7 @@ impl Game<'_> { } let name = &self .res - .facts + .facts() .get(self.world.block(pos[0], pos[1], pos[2])) .name; if stops.contains(&**name) { @@ -402,7 +402,7 @@ impl Game<'_> { /// buttons, levers and bells react as if used; candles go out. fn wind_trigger_block(&mut self, pos: [i32; 3]) -> Result<()> { let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts.get(state).name.clone(); + let name = self.res.facts().get(state).name.clone(); let prop = |game: &Self, key: &str| { game.pack .assets @@ -478,6 +478,7 @@ impl Game<'_> { }); let Some(model) = model else { return }; let Some(r) = self + .gui .atlas .sprites .get("entity/projectiles/wind_charge") diff --git a/crates/horizon-client/src/game/wither.rs b/crates/horizon-client/src/game/wither.rs index dfd215814..7b86dc527 100644 --- a/crates/horizon-client/src/game/wither.rs +++ b/crates/horizon-client/src/game/wither.rs @@ -10,14 +10,22 @@ use horizon_client::{ impl Game<'_> { fn is_wither_skull(&self, p: [i32; 3]) -> bool { - let name = &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; matches!( name, "minecraft:wither_skeleton_skull" | "minecraft:wither_skeleton_wall_skull" ) } fn is_soul_base(&self, p: [i32; 3]) -> bool { - let name = &*self.res.facts.get(self.world.block(p[0], p[1], p[2])).name; + let name = &*self + .res + .facts() + .get(self.world.block(p[0], p[1], p[2])) + .name; matches!(name, "minecraft:soul_sand" | "minecraft:soul_soil") } /// After a wither skeleton skull is placed: the T of soul sand (or soul @@ -36,7 +44,7 @@ impl Game<'_> { && self.is_soul_base(at(1, 2)) && [0, 2].iter().all(|&c| { let p = at(c, 2); - self.res.facts.is_air(self.world.block(p[0], p[1], p[2])) + self.res.facts().is_air(self.world.block(p[0], p[1], p[2])) }); if !ok { continue; diff --git a/crates/horizon-client/src/gamepad.rs b/crates/horizon-client/src/gamepad.rs index a250f5e8c..220f74a5b 100644 --- a/crates/horizon-client/src/gamepad.rs +++ b/crates/horizon-client/src/gamepad.rs @@ -1009,6 +1009,7 @@ pub enum TriggerFeel { /// Mining a block of this hardness: a buzz, stronger and slower on harder blocks. Texture(f32), } +#[cfg(feature = "controllers")] impl TriggerFeel { /// The effect, for a trigger that presses its action at `threshold` (0..1) of its travel. pub fn effect(self, threshold: f32) -> horizon_dualsense::TriggerEffect { @@ -1044,6 +1045,7 @@ impl TriggerFeel { } } } +#[cfg(feature = "controllers")] impl PadSettings { /// The left and right triggers' effects: each feels the action bound to it, `key.use` or /// `key.attack`. @@ -1404,6 +1406,7 @@ mod tests { assert_eq!(w.observe(Some(1.0)), Some(1.0)); } + #[cfg(feature = "controllers")] #[test] fn triggers_feel_their_action() { use horizon_dualsense::{TRIGGER_OFF, trigger}; diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 22d88c770..8481fdcab 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -24,7 +24,7 @@ const CRUMBLING_BLEND: wgpu::BlendState = wgpu::BlendState { }; /// `TerrainVertex` for `vs_terrain`: position, UV, layer, light, colour. const TERRAIN_ATTRIBUTES: [wgpu::VertexAttribute; 5] = - wgpu::vertex_attr_array![0=>Float32x3,1=>Float32x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4]; + wgpu::vertex_attr_array![0=>Float32x3,1=>Uint16x2,2=>Uint16,4=>Uint8x2,3=>Unorm8x4]; /// entity.wgsl after the OverlayTexture constants it reads. fn entity_shader() -> String { @@ -58,6 +58,7 @@ pub fn outline_vertices(edges: &[[f64; 6]], camera: glam::DVec3) -> Vec<[f32; 6] } mod arena; +mod cull; mod flat; mod java_stages; mod occlusion; @@ -270,6 +271,9 @@ pub struct Renderer { flat: Option<flat::Flat>, /// `flat` draws this frame's sections (off: the per-section draws). flat_on: bool, + /// Occlusion culling of solid section draws, where multi-draw is native. + cull: Option<cull::Cull>, + cull_on: bool, sky: wgpu::RenderPipeline, dark_disc: wgpu::RenderPipeline, lines: wgpu::RenderPipeline, @@ -332,7 +336,7 @@ pub struct Renderer { animations: AnimatedSprites, uploads: upload::Uploads, /// Section meshes are staged through their own belt into - /// `section_copies`, which the next submission runs ahead of the frame: + /// `section_copies`, which the next frame records its commands after: /// `Queue::write_buffer` would make a staging buffer per write. section_uploads: upload::Uploads, section_copies: Option<wgpu::CommandEncoder>, @@ -365,6 +369,10 @@ pub struct Renderer { draws: Vec<[u32; 5]>, /// Vertex arena page and optional sorted index arena page of each draw. draw_pages: Vec<(u32, Option<u32>)>, + /// Solid draws left to occlusion culling's phase 2, while the list is + /// built, and their pages. + phase2_draws: Vec<[u32; 5]>, + phase2_pages: Vec<(u32, Option<u32>)>, /// Block-entity blocks per meshed section (world position, state id). block_entities: HashMap<SectionKey, Vec<([i32; 3], u32)>>, /// Changes whenever `block_entities` does (unique across renderers). @@ -654,6 +662,7 @@ impl Renderer { // Mappable primary buffers: section pages that no // longer fit in video memory go to system memory. required_features: timing::GpuTimer::features(&adapter) + | cull::Cull::features(&adapter) | (adapter.features() & (wgpu::Features::INDIRECT_FIRST_INSTANCE | wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)), @@ -1100,7 +1109,9 @@ impl Renderer { let instances = device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); let outline = device.create_buffer(&wgpu::BufferDescriptor { @@ -1745,6 +1756,15 @@ impl Renderer { let multi_draw = device .features() .contains(wgpu::Features::INDIRECT_FIRST_INSTANCE); + // HORIZON_GPU_CULL=0 turns occlusion culling off, `all` culls every + // frame however little it hides (A/B checks). + let cull_env = std::env::var("HORIZON_GPU_CULL"); + let cull = (cull_env.as_deref() != Ok("0") && cull::Cull::supported(&adapter, &device)) + .then(|| { + let mut cull = cull::Cull::new(&device, config.format.remove_srgb_suffix()); + cull.always = cull_env.as_deref() == Ok("all"); + cull + }); let world_post = world_post::Post::new(&device, config.format.remove_srgb_suffix()); let uploads = upload::Uploads::new(&device); let section_uploads = upload::Uploads::with_chunk(&device, SECTION_UPLOAD_CHUNK); @@ -1772,6 +1792,8 @@ impl Renderer { solid, translucent, flat_on: flat.is_some(), + cull_on: cull.is_some(), + cull, flat, sky, dark_disc, @@ -1845,6 +1867,8 @@ impl Renderer { origins: Vec::new(), draws: Vec::new(), draw_pages: Vec::new(), + phase2_draws: Vec::new(), + phase2_pages: Vec::new(), block_entities: HashMap::new(), block_entity_revision: next_block_entity_revision(), occlusion: occlusion::Occlusion::new(crate::chunk::HEIGHT / 16), @@ -1998,6 +2022,27 @@ impl Renderer { self.flat_on = on; Ok(()) } + /// Whether solid sections are occlusion culled (`cull`). + pub fn section_cull(&self) -> bool { + self.cull_on + } + /// Switches occlusion culling, for A/B checks. + pub fn set_section_cull(&mut self, on: bool) -> Result<()> { + if on && self.cull.is_none() { + return Err("occlusion culling is off on this device".into()); + } + self.cull_on = on; + Ok(()) + } + /// Of the boxes occlusion culling's last test read back drew, how many + /// it did not see and how many it drew, and the share of solid indices + /// it hid. + pub fn culled_sections(&self) -> Option<([usize; 2], f32)> { + self.cull + .as_ref() + .filter(|_| self.cull_on) + .map(|c| c.hidden) + } pub fn section_count(&self) -> usize { self.sections.len() } @@ -2117,7 +2162,15 @@ impl Renderer { /// origins bound: one indirect multi-draw, or a loop without it. /// Consecutive draws in one arena page share a vertex buffer binding, /// keeping the list's order (translucent sections go back to front). - fn draw_sections(&self, pass: &mut wgpu::RenderPass<'_>, first: u32, count: u32) { + /// `indirect` holds the list's draws from `base`. + fn draw_sections( + &self, + pass: &mut wgpu::RenderPass<'_>, + indirect: &wgpu::Buffer, + base: u32, + first: u32, + count: u32, + ) { let (mut i, end) = (first as usize, (first + count) as usize); while i < end { let (page, index_page) = self.draw_pages[i]; @@ -2129,7 +2182,8 @@ impl Renderer { let indices = index_page.map_or(&self.indices, |p| self.sorted_indices.buffer(p)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); if self.multi_draw { - pass.multi_draw_indexed_indirect(&self.indirect, i as u64 * 20, run as u32); + let offset = (i - base as usize) as u64 * 20; + pass.multi_draw_indexed_indirect(indirect, offset, run as u32); } else { for d in &self.draws[i..i + run] { pass.draw_indexed(d[2]..d[2] + d[0], d[3] as i32, d[4]..d[4] + 1); @@ -2394,14 +2448,21 @@ impl Renderer { Some(f) => f.texture.clone(), None => self.offscreen.clone().ok_or("no offscreen target")?, }; - let mut encoder = self - .device - .create_command_encoder(&wgpu::CommandEncoderDescriptor { - label: Some("Horizon frame"), - }); + // One command buffer for the frame, after the section copies staged + // since the last one: Metal commits every command buffer wgpu-core + // makes (one per run of copies and two per pass) on its own. + let section_copies = self.section_copies.take(); + let has_section_copies = section_copies.is_some(); + let mut encoder = section_copies.unwrap_or_else(|| { + self.device + .create_command_encoder(&wgpu::CommandEncoderDescriptor { + label: Some("Horizon frame"), + }) + }); if self.animated_textures { self.animate(&mut encoder, frame.ticks); - self.hud.animate_fire(&self.queue, frame.ticks); + self.hud + .animate_fire(&mut self.uploads, &mut encoder, frame.ticks); } self.update_lightmap( &mut encoder, @@ -2567,7 +2628,9 @@ impl Renderer { self.instances = self.device.create_buffer(&wgpu::BufferDescriptor { label: Some("Section origins"), size: self.instance_capacity * 16, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + usage: wgpu::BufferUsages::VERTEX + | wgpu::BufferUsages::COPY_DST + | wgpu::BufferUsages::STORAGE, mapped_at_creation: false, }); } @@ -2596,15 +2659,48 @@ impl Renderer { let eye = (frame.bob * crate::camera::view_matrix(frame.yaw, frame.pitch)) .inverse() .transform_point3(Vec3::ZERO); + // Occlusion culling leaves the sections its last result did not see + // to phase 2, after the others, with instance counts of 0. + let mut cull = self + .cull + .as_mut() + .filter(|_| { + self.cull_on + && !frame.title + && self.multi_draw + && !(self.flat_on && self.flat.is_some()) + }) + .and_then(|cull| cull.begin(&self.device).then_some(cull)); + self.phase2_draws.clear(); + self.phase2_pages.clear(); for (i, v) in visible.iter().enumerate() { let s = self.sections.get(v.slot); + let first_phase = cull.as_ref().is_none_or(|c| c.first(v.slot)); + let (draws, pages) = if first_phase { + (&mut self.draws, &mut self.draw_pages) + } else { + (&mut self.phase2_draws, &mut self.phase2_pages) + }; + let start = draws.len(); + let instances = u32::from(first_phase); + let mut indices = 0; // Only the solid groups that can face the eye. s.faces.ranges(eye - Vec3::from(v.origin), |first, quads| { let first = s.start + u64::from(first) * 4; - self.draws.push([quads * 6, 1, 0, first as u32, i as u32]); - self.draw_pages.push((s.page, None)); + draws.push([quads * 6, instances, 0, first as u32, i as u32]); + pages.push((s.page, None)); + indices += quads * 6; }); + match &mut cull { + Some(c) if first_phase => c.drawn(i, v.slot, indices), + Some(c) => c.deferred(i, v.slot, start, draws.len() - start, indices), + None => {} + } } + let phase1_draws = self.draws.len() as u32; + self.draws.extend_from_slice(&self.phase2_draws); + self.draw_pages.extend_from_slice(&self.phase2_pages); + let culling = cull.is_some(); let solid_draws = self.draws.len() as u32; // LevelRenderer: nearby sections each frame, plus a rotating eighth // (at least 15) of the visible list. Cached views avoid needless sorts. @@ -2654,6 +2750,7 @@ impl Renderer { (0..self.draws.len()) .filter(|&i| { i == 0 + || i == phase1_draws as usize || i == solid_draws as usize || self.draw_pages[i] != self.draw_pages[i - 1] }) @@ -2661,48 +2758,6 @@ impl Renderer { } 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 { - label: Some("Section draws"), - size: self.indirect_capacity * 20, - usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - } - self.uploads.buffer( - &mut encoder, - &self.indirect, - 0, - bytemuck::cast_slice(&self.draws), - ); - } let debug_depth = frame.debug_lines.len() as u32; let debug_top = frame.debug_lines_on_top.len() as u32; let crosshair = frame.debug_crosshair.len() as u32; @@ -2839,6 +2894,87 @@ impl Renderer { bytemuck::bytes_of(&uniform), ); } + // Every upload before the frame's first pass: a pass ends wgpu-core's + // command buffer, so copies between passes would need one more. + if !frame.screen.is_empty() { + let vertices: Vec<crate::screen_effects::ScreenVertex> = + frame.screen.iter().flat_map(|q| q.vertices).collect(); + if vertices.len() as u64 > self.screen_capacity { + self.screen_capacity = (vertices.len() as u64).next_power_of_two(); + self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Screen effect vertices"), + size: self.screen_capacity + * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + self.uploads.buffer( + &mut encoder, + &self.screen_buffer, + 0, + bytemuck::cast_slice(&vertices), + ); + } + self.hud.prepare( + &self.device, + &mut self.uploads, + &mut encoder, + frame.hud, + [self.config.width, self.config.height], + ); + 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 { + label: Some("Section draws"), + size: self.indirect_capacity * 20, + usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + } + self.uploads.buffer( + &mut encoder, + &self.indirect, + 0, + bytemuck::cast_slice(&self.draws), + ); + if culling && let Some(cull) = &mut self.cull { + cull.upload( + &self.device, + &mut self.uploads, + &mut encoder, + &self.draws[phase1_draws as usize..solid_draws as usize], + &self.instances, + &self.globals, + ); + } + } let view_target = target_texture.create_view(&wgpu::TextureViewDescriptor { format: Some(self.config.format.remove_srgb_suffix()), ..Default::default() @@ -2855,6 +2991,7 @@ impl Renderer { Some((color, depth)) => (color, depth), None => (&view_target, &self.depth), }; + let cull = self.cull.as_ref().filter(|_| culling && solid_draws > 0); { let attachments = [Some(wgpu::RenderPassColorAttachment { view: world_view, @@ -2883,8 +3020,9 @@ impl Renderer { view: world_depth, depth_ops: Some(wgpu::Operations { load: wgpu::LoadOp::Clear(0.0), - // A shader pack reads the world's depth. - store: if pack { + // A shader pack reads the world's depth, and + // phase 2 of occlusion culling draws over it. + store: if pack || cull.is_some() { wgpu::StoreOp::Store } else { wgpu::StoreOp::Discard @@ -2934,7 +3072,59 @@ impl Renderer { 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 cull { + Some(cull) => { + // Phase 1 and the boxes against its depth, then + // what they found in sight, in a pass that loads + // both targets (it reads the test's results). + self.draw_sections(&mut pass, &self.indirect, 0, 0, phase1_draws); + cull.test(&mut pass); + drop(pass); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: world_view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Load, + store: wgpu::StoreOp::Store, + }, + })]; + pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Horizon world, after culling"), + color_attachments: &attachments, + depth_stencil_attachment: Some( + wgpu::RenderPassDepthStencilAttachment { + view: world_depth, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Load, + store: if pack { + wgpu::StoreOp::Store + } else { + wgpu::StoreOp::Discard + }, + }), + stencil_ops: None, + }, + ), + ..Default::default() + }); + pass.set_bind_group(0, &self.group, &[]); + 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, + &cull.phase2, + phase1_draws, + phase1_draws, + solid_draws - phase1_draws, + ); + } + None => self.draw_sections(&mut pass, &self.indirect, 0, 0, solid_draws), + } } } if entity_quads > 0 { @@ -2986,7 +3176,13 @@ impl Renderer { 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); + self.draw_sections( + &mut pass, + &self.indirect, + 0, + solid_draws, + translucent_draws, + ); } } // LevelRenderer.executeClassicTransparency: translucent targets' @@ -3102,24 +3298,6 @@ impl Renderer { ); } if !frame.screen.is_empty() { - let vertices: Vec<crate::screen_effects::ScreenVertex> = - frame.screen.iter().flat_map(|q| q.vertices).collect(); - if vertices.len() as u64 > self.screen_capacity { - self.screen_capacity = (vertices.len() as u64).next_power_of_two(); - self.screen_buffer = self.device.create_buffer(&wgpu::BufferDescriptor { - label: Some("Screen effect vertices"), - size: self.screen_capacity - * std::mem::size_of::<crate::screen_effects::ScreenVertex>() as u64, - usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, - mapped_at_creation: false, - }); - } - self.uploads.buffer( - &mut encoder, - &self.screen_buffer, - 0, - bytemuck::cast_slice(&vertices), - ); let attachments = [Some(wgpu::RenderPassColorAttachment { view: &view_target, resolve_target: None, @@ -3212,15 +3390,15 @@ impl Renderer { ); } self.hud.draw( - &self.device, - &self.queue, - &mut self.uploads, &mut encoder, &view_target, &self.depth, frame.hud, [self.config.width, self.config.height], ); + if culling && let Some(cull) = &mut self.cull { + cull.end(&self.device, &mut encoder); + } if let Some(timer) = &mut self.gpu_timer { timer.end(&mut encoder); } @@ -3229,12 +3407,15 @@ impl Renderer { .take() .map(|path| (path, self.copy_frame(&mut encoder, &target_texture))); self.uploads.finish(&encoder); + if has_section_copies { + self.section_copy_bytes = 0; + self.section_uploads.finish(&encoder); + } let commands = crate::spans::time("encode", || encoder.finish()); - // The section copies run first: this frame draws what they write. - let copies = self.take_section_copies(); - let submission = crate::spans::time("submit", || { - self.queue.submit(copies.into_iter().chain([commands])) - }); + let submission = crate::spans::time("submit", || self.queue.submit([commands])); + if let Some(cull) = &mut self.cull { + cull.submitted(); + } if let Some(timer) = &mut self.gpu_timer { timer.submitted(); timer.collect(&self.device, &mut self.gpu_times); @@ -3521,7 +3702,7 @@ mod tests { (3, offset_of!(TerrainVertex, color)), ] ); - assert_eq!(std::mem::size_of::<TerrainVertex>(), 28); + assert_eq!(std::mem::size_of::<TerrainVertex>(), 24); } #[test] fn cracks_multiply_instead_of_covering_the_block() { diff --git a/crates/horizon-client/src/gfx/cull.rs b/crates/horizon-client/src/gfx/cull.rs new file mode 100644 index 000000000..bcb738de3 --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.rs @@ -0,0 +1,513 @@ +//! Occlusion culling of solid section draws, in two phases. +//! +//! Frustum and cave culling leave many sections that terrain in front hides +//! entirely (about half of the solid vertices drawn from the ground at render +//! distance 16, more at 32), and drawing fewer vertices is what helps an +//! integrated GPU. Phase 1 draws the sections that the last test read back +//! saw. Then, in the same pass, the box of every other section (and of a +//! share of phase 1's, to notice when they go out of sight) is drawn against +//! phase 1's depth with no writes but to the test's results. Phase 2, in a +//! second pass, draws the sections whose box was seen; the others' draws have +//! an instance count of 0. +//! +//! The picture stays the one without culling: the boxes (grown by a block, +//! the farthest a block model reaches out of its cell) are drawn front faces +//! only, so a fragment is the box's nearest point on its pixel, and the +//! fragment shader runs only where the depth test passes (forced early), so a +//! section is left out only where all of its fragments would fail the depth +//! test against the final depth, which is only nearer. What the CPU knows of +//! the results only sorts sections between the phases: a stale result draws +//! a hidden section in phase 1, or tests a section that is in sight. +//! +//! Every solid draw is an entry of one of the two lists, so the CPU records +//! as many draws as without culling: drivers that unroll an indirect +//! multi-draw on the CPU (Mesa's on Intel Gen9) pay per entry. Phase 2's +//! counts come from the GPU, which needs a native multi-draw and forced +//! early depth tests: Vulkan. Translucent draws are not culled. +use std::num::NonZeroU64; +use std::sync::{ + Arc, + atomic::{AtomicU8, Ordering}, +}; + +const WORDS: u64 = 5 * 4; +/// Phase 1's sections are each tested every `RETEST` frames. +const RETEST: u32 = 8; +/// Culling runs while the last result read back hid at least this share of +/// the frame's solid indices: below it the test and the second pass cost +/// more than they save. Else one frame in `PROBE` tests every section. +const MIN_SHARE: f32 = 0.1; +const PROBE: u32 = 64; +/// Boxes over more than this share of the screen count as seen untested. +const BIG: f32 = 0.25; +/// Results read back at once, some frames late so the CPU never waits. +const READBACKS: usize = 3; +const FREE: u8 = 0; +const PENDING: u8 = 1; +const MAPPED: u8 = 2; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Params { + stamp: u32, + big: f32, + pad: [u32; 2], +} + +/// One frame's results on their way back. +struct Readback { + buffer: wgpu::Buffer, + capacity: u64, + state: Arc<AtomicU8>, + stamp: u32, + /// The resident slot of each test, and its section's solid indices. + slots: Vec<u32>, + indices: Vec<u32>, + /// The frame's solid indices. + total: u64, +} + +/// The bind group and the buffers from outside it was made with. +struct Group { + origins: wgpu::Buffer, + globals: wgpu::Buffer, + group: wgpu::BindGroup, +} + +pub struct Cull { + pipeline: wgpu::RenderPipeline, + layout: wgpu::BindGroupLayout, + group: Option<Group>, + params: wgpu::Buffer, + /// Phase 2's draws: the solid draws after phase 1's in the frame's list. + pub phase2: wgpu::Buffer, + phase2_capacity: u64, + tests: wgpu::Buffer, + tests_capacity: u64, + /// This frame's tests: visible index, first phase 2 draw, phase 2 draws. + test_data: Vec<[u32; 4]>, + test_slots: Vec<u32>, + test_indices: Vec<u32>, + total: u64, + /// The frame tests every section, as culling was off. + probe: bool, + results: wgpu::Buffer, + readbacks: Vec<Readback>, + next: usize, + current: Option<usize>, + /// Per resident slot: whether the last result read back saw it. + seen: Vec<bool>, + stamp: u32, + /// Of the boxes the last test read back drew, how many it did not see + /// and how many it drew, and the share of solid indices hidden. + pub hidden: ([usize; 2], f32), + /// Cull every frame, whatever the hidden share (A/B checks). + pub always: bool, +} + +fn buffer( + device: &wgpu::Device, + label: &str, + size: u64, + usage: wgpu::BufferUsages, +) -> wgpu::Buffer { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size, + usage, + mapped_at_creation: false, + }) +} + +const PHASE2_USAGE: wgpu::BufferUsages = wgpu::BufferUsages::INDIRECT + .union(wgpu::BufferUsages::STORAGE) + .union(wgpu::BufferUsages::COPY_DST); +const TESTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_DST); +const RESULTS_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::STORAGE.union(wgpu::BufferUsages::COPY_SRC); +const READBACK_USAGE: wgpu::BufferUsages = + wgpu::BufferUsages::MAP_READ.union(wgpu::BufferUsages::COPY_DST); + +impl Cull { + /// The device feature culling needs, where the adapter has it. + pub fn features(adapter: &wgpu::Adapter) -> wgpu::Features { + adapter.features() & wgpu::Features::SHADER_EARLY_DEPTH_TEST + } + /// Whether the device draws an indirect multi-draw natively and runs + /// fragment shaders that write storage only past an early depth test. + pub fn supported(adapter: &wgpu::Adapter, device: &wgpu::Device) -> bool { + adapter.get_info().backend == wgpu::Backend::Vulkan + && device.features().contains( + wgpu::Features::SHADER_EARLY_DEPTH_TEST | wgpu::Features::INDIRECT_FIRST_INSTANCE, + ) + && adapter.get_downlevel_capabilities().flags.contains( + wgpu::DownlevelFlags::VERTEX_STORAGE + | wgpu::DownlevelFlags::FRAGMENT_WRITABLE_STORAGE, + ) + } + /// `color` is the world pass's colour format. + pub fn new(device: &wgpu::Device, color: wgpu::TextureFormat) -> Self { + let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { + binding, + visibility, + ty, + count: None, + }; + let storage = |read_only| wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Storage { read_only }, + has_dynamic_offset: false, + min_binding_size: None, + }; + let uniform = wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }; + let both = wgpu::ShaderStages::VERTEX_FRAGMENT; + let vertex = wgpu::ShaderStages::VERTEX; + let fragment = wgpu::ShaderStages::FRAGMENT; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Section culling"), + entries: &[ + entry(0, both, storage(true)), + entry(1, fragment, storage(false)), + entry(2, fragment, storage(false)), + entry(3, vertex, storage(true)), + entry(4, vertex, uniform), + entry(5, both, uniform), + ], + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Section culling"), + source: wgpu::ShaderSource::Wgsl(include_str!("cull.wgsl").into()), + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Section culling"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Section culling"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &module, + entry_point: Some("vs_box"), + compilation_options: Default::default(), + buffers: &[], + }, + primitive: wgpu::PrimitiveState { + cull_mode: Some(wgpu::Face::Back), + ..Default::default() + }, + // The world pass's reversed depth test, without writes. + depth_stencil: Some(wgpu::DepthStencilState { + format: wgpu::TextureFormat::Depth32Float, + depth_write_enabled: Some(false), + depth_compare: Some(wgpu::CompareFunction::GreaterEqual), + stencil: Default::default(), + bias: Default::default(), + }), + multisample: Default::default(), + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs_box"), + compilation_options: Default::default(), + targets: &[Some(wgpu::ColorTargetState { + format: color, + blend: None, + write_mask: wgpu::ColorWrites::empty(), + })], + }), + multiview_mask: None, + cache: None, + }); + Self { + pipeline, + layout, + group: None, + params: buffer( + device, + "Section culling parameters", + std::mem::size_of::<Params>() as u64, + wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + ), + phase2: buffer(device, "Section draws, phase 2", WORDS, PHASE2_USAGE), + phase2_capacity: 1, + tests: buffer(device, "Section tests", 16, TESTS_USAGE), + tests_capacity: 1, + test_data: Vec::new(), + test_slots: Vec::new(), + test_indices: Vec::new(), + total: 0, + probe: false, + results: buffer(device, "Section test results", 4, RESULTS_USAGE), + readbacks: (0..READBACKS) + .map(|_| Readback { + buffer: buffer(device, "Section test readback", 4, READBACK_USAGE), + capacity: 1, + state: Arc::new(AtomicU8::new(FREE)), + stamp: 0, + slots: Vec::new(), + indices: Vec::new(), + total: 0, + }) + .collect(), + next: 0, + current: None, + seen: Vec::new(), + stamp: 0, + hidden: ([0; 2], 1.0), + always: false, + } + } + + /// Start a frame: take in the results that came back, and tell whether + /// the frame culls. + pub fn begin(&mut self, device: &wgpu::Device) -> bool { + let _ = device.poll(wgpu::PollType::Poll); + for i in 0..READBACKS { + let r = &mut self.readbacks[(self.next + i) % READBACKS]; + if r.state.load(Ordering::Acquire) != MAPPED { + continue; + } + let mapped = r.buffer.slice(..r.slots.len() as u64 * 4); + if let Ok(data) = mapped.get_mapped_range() { + // The mapping isn't guaranteed to be 4-byte aligned (a Vega 11 + // on Windows panicked in cast_slice), so copy the words out. + let results: Vec<u32> = bytemuck::pod_collect_to_vec(&data); + let (mut hidden, mut indices) = (0, 0u64); + for (&result, &n) in results.iter().zip(&r.indices) { + if result != r.stamp { + hidden += 1; + indices += u64::from(n); + } + } + let share = indices as f32 / r.total.max(1) as f32; + self.hidden = ([hidden, results.len()], share); + for (&slot, &result) in r.slots.iter().zip(&results) { + let slot = slot as usize; + if slot >= self.seen.len() { + self.seen.resize(slot + 1, false); + } + self.seen[slot] = result == r.stamp; + } + } + r.buffer.unmap(); + r.state.store(FREE, Ordering::Release); + } + self.stamp = self.stamp.wrapping_add(1).max(1); + self.test_data.clear(); + self.test_slots.clear(); + self.test_indices.clear(); + self.total = 0; + self.probe = !self.always && self.hidden.1 < MIN_SHARE; + !self.probe || self.stamp.is_multiple_of(PROBE) + } + + /// Whether phase 1 draws the section in resident `slot`. + pub fn first(&self, slot: u32) -> bool { + self.seen.get(slot as usize).copied().unwrap_or(false) + } + + /// A section phase 1 draws, `index` in the visible list, with `indices` + /// solid indices: tested in turn. + pub fn drawn(&mut self, index: usize, slot: u32, indices: u32) { + self.total += u64::from(indices); + if indices > 0 && (self.probe || slot.wrapping_add(self.stamp).is_multiple_of(RETEST)) { + self.push([index as u32, 0, 0, 0], slot, indices); + } + } + + /// A section left to phase 2: its `draws` from phase 2's `first`. + pub fn deferred(&mut self, index: usize, slot: u32, first: usize, draws: usize, indices: u32) { + self.total += u64::from(indices); + if draws > 0 { + self.push([index as u32, first as u32, draws as u32, 0], slot, indices); + } + } + + fn push(&mut self, test: [u32; 4], slot: u32, indices: u32) { + self.test_data.push(test); + self.test_slots.push(slot); + self.test_indices.push(indices); + } + + /// Stage this frame's inputs: phase 2's draws, with instance counts of 0, + /// and the tests, which read the frame's camera-relative `origins` and + /// view projection (the start of `globals`). + pub fn upload( + &mut self, + device: &wgpu::Device, + uploads: &mut super::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + phase2: &[[u32; 5]], + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) { + let draws = phase2.len() as u64; + if draws > self.phase2_capacity { + self.phase2_capacity = draws.next_power_of_two(); + self.phase2 = buffer( + device, + "Section draws, phase 2", + self.phase2_capacity * WORDS, + PHASE2_USAGE, + ); + self.group = None; + } + let tests = self.test_data.len() as u64; + if tests > self.tests_capacity { + self.tests_capacity = tests.next_power_of_two(); + self.tests = buffer( + device, + "Section tests", + self.tests_capacity * 16, + TESTS_USAGE, + ); + self.results = buffer( + device, + "Section test results", + self.tests_capacity * 4, + RESULTS_USAGE, + ); + self.group = None; + } + if draws > 0 { + uploads.buffer(encoder, &self.phase2, 0, bytemuck::cast_slice(phase2)); + } + if tests > 0 { + uploads.buffer( + encoder, + &self.tests, + 0, + bytemuck::cast_slice(&self.test_data), + ); + } + let params = Params { + stamp: self.stamp, + big: BIG, + pad: [0; 2], + }; + uploads.buffer(encoder, &self.params, 0, bytemuck::bytes_of(¶ms)); + if !self + .group + .as_ref() + .is_some_and(|g| g.origins == *origins && g.globals == *globals) + { + self.group = Some(self.make_group(device, origins, globals)); + } + } + + /// In the world pass after phase 1: draw the tested boxes against its + /// depth. Leaves the pass's pipeline and group 0 changed. + pub fn test(&self, pass: &mut wgpu::RenderPass<'_>) { + let Some(Group { group, .. }) = &self.group else { + return; + }; + if self.test_data.is_empty() { + return; + } + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, group, &[]); + pass.draw(0..36, 0..self.test_data.len() as u32); + } + + /// After the world passes: copy the results for reading back, when a + /// readback buffer is free. + pub fn end(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder) { + let tests = self.test_data.len() as u64; + let r = &mut self.readbacks[self.next]; + if tests == 0 || r.state.load(Ordering::Acquire) != FREE { + return; + } + if tests > r.capacity { + r.capacity = tests.next_power_of_two(); + r.buffer = buffer( + device, + "Section test readback", + r.capacity * 4, + READBACK_USAGE, + ); + } + encoder.copy_buffer_to_buffer(&self.results, 0, &r.buffer, 0, tests * 4); + r.stamp = self.stamp; + r.slots.clear(); + r.slots.extend_from_slice(&self.test_slots); + r.indices.clear(); + r.indices.extend_from_slice(&self.test_indices); + r.total = self.total; + self.current = Some(self.next); + } + + /// After the frame's submission: start reading its results back. + pub fn submitted(&mut self) { + let Some(i) = self.current.take() else { + return; + }; + let r = &self.readbacks[i]; + let state = r.state.clone(); + state.store(PENDING, Ordering::Release); + r.buffer + .slice(..r.slots.len() as u64 * 4) + .map_async(wgpu::MapMode::Read, move |result| { + state.store( + if result.is_ok() { MAPPED } else { FREE }, + Ordering::Release, + ); + }); + self.next = (i + 1) % READBACKS; + } + + fn make_group( + &self, + device: &wgpu::Device, + origins: &wgpu::Buffer, + globals: &wgpu::Buffer, + ) -> Group { + fn whole(binding: u32, buffer: &wgpu::Buffer) -> wgpu::BindGroupEntry<'_> { + wgpu::BindGroupEntry { + binding, + resource: buffer.as_entire_binding(), + } + } + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Section culling"), + layout: &self.layout, + entries: &[ + whole(0, &self.tests), + whole(1, &self.results), + whole(2, &self.phase2), + whole(3, origins), + wgpu::BindGroupEntry { + binding: 4, + resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer: globals, + offset: 0, + size: NonZeroU64::new(64), + }), + }, + whole(5, &self.params), + ], + }); + Group { + origins: origins.clone(), + globals: globals.clone(), + group, + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("cull.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } +} diff --git a/crates/horizon-client/src/gfx/cull.wgsl b/crates/horizon-client/src/gfx/cull.wgsl new file mode 100644 index 000000000..faa495caf --- /dev/null +++ b/crates/horizon-client/src/gfx/cull.wgsl @@ -0,0 +1,101 @@ +// Occlusion culling of solid section draws (gfx/cull.rs). + +struct Params { + // This frame's test: a test that sees its box stores the number. + stamp: u32, + // Boxes covering more than this share of the screen count as seen. + big: f32, +} +// The leading member of terrain.wgsl's Globals. +struct Globals { + view_proj: mat4x4<f32>, +} + +// One test per section: its visible index (which names its origin), its +// first draw in `phase2` and how many draws it has there (0: phase 1 drew +// it, and the test only tells whether it is still in sight). +@group(0) @binding(0) var<storage, read> tests: array<vec4<u32>>; +// Per test: the stamp of the frame whose test saw the box. +@group(0) @binding(1) var<storage, read_write> results: array<u32>; +// Phase 2's draws, 5 words each, with instance counts of 0 until seen. +@group(0) @binding(2) var<storage, read_write> phase2: array<u32>; +// Camera-relative origin of each visible section. +@group(0) @binding(3) var<storage, read> origins: array<vec4<f32>>; +@group(0) @binding(4) var<uniform> globals: Globals; +@group(0) @binding(5) var<uniform> params: Params; + +// The corners (bit 0: x, bit 1: y, bit 2: z) of the box's 12 triangles, +// counter-clockwise seen from outside. +const CORNERS = array<u32, 36>( + 0u, 6u, 2u, 0u, 4u, 6u, 1u, 3u, 7u, 1u, 7u, 5u, 0u, 1u, 5u, 0u, 5u, 4u, + 2u, 7u, 3u, 2u, 6u, 7u, 0u, 3u, 1u, 0u, 2u, 3u, 4u, 5u, 7u, 4u, 7u, 6u, +); + +struct Box { + @builtin(position) position: vec4<f32>, + @location(0) @interpolate(flat) test: u32, +} + +fn corner(origin: vec3<f32>, c: u32) -> vec3<f32> { + return origin + vec3( + select(-1.0, 17.0, (c & 1u) != 0u), + select(-1.0, 17.0, (c & 2u) != 0u), + select(-1.0, 17.0, (c & 4u) != 0u), + ); +} + +// Each tested section's box, grown by a block (block models reach one block +// out of their cell), drawn after phase 1 against its depth with back faces +// culled: a front face fragment that passes the depth test is the box's +// nearest point on that pixel in front of phase 1's depth, so the section +// may show there. A box failing everywhere would have every fragment of its +// section fail the depth test against the final depth, which is only nearer. +@vertex +fn vs_box(@builtin(vertex_index) v: u32, @builtin(instance_index) t: u32) -> Box { + let origin = origins[tests[t].x].xyz; + var out: Box; + out.test = t; + // The box's screen rectangle, from the corners in front of the camera. + var lo = vec2(1e30); + var hi = vec2(-1e30); + var behind = false; + for (var c = 0u; c < 8u; c++) { + let p = globals.view_proj * vec4(corner(origin, c), 1.0); + behind = behind || p.w <= 0.0; + let q = p.xy / max(p.w, 1e-6); + lo = min(lo, q); + hi = max(hi, q); + } + let size = max(min(hi, vec2(1.0)) - max(lo, vec2(-1.0)), vec2(0.0)); + // A box within a block of the camera may cross the near plane, which + // clips its front faces away, and a box over a large part of the screen + // is nearly always in sight and costly to test: both count as seen, + // through a small triangle in the top left corner at the nearest depth. + let near = all(origin < vec3(2.0)) && all(origin > vec3(-18.0)); + if near || (!behind && size.x * size.y > params.big * 4.0) { + var p = vec2(-1.0, 1.0); + if v == 1u { + p.y -= 0.05; + } else if v == 2u { + p.x += 0.05; + } + out.position = select(vec4(0.0, 0.0, 0.0, 1.0), vec4(p, 1.0, 1.0), v < 3u); + return out; + } + out.position = globals.view_proj * vec4(corner(origin, CORNERS[v]), 1.0); + return out; +} + +// Runs only for fragments that pass the depth test (forced early). +@fragment +@early_depth_test(force) +fn fs_box(in: Box) -> @location(0) vec4<f32> { + if results[in.test] != params.stamp { + results[in.test] = params.stamp; + let test = tests[in.test]; + for (var k = 0u; k < test.z; k++) { + phase2[(test.y + k) * 5u + 1u] = 1u; + } + } + return vec4(0.0); +} diff --git a/crates/horizon-client/src/gfx/timing.rs b/crates/horizon-client/src/gfx/timing.rs index 5d2354234..8f8eee6ee 100644 --- a/crates/horizon-client/src/gfx/timing.rs +++ b/crates/horizon-client/src/gfx/timing.rs @@ -147,7 +147,8 @@ impl GpuTimer { continue; } if let Ok(data) = slot.buffer.slice(..).get_mapped_range() { - let stamps: &[u64] = bytemuck::cast_slice(&data); + // Read unaligned: the mapping isn't guaranteed to be 8-byte aligned. + let stamps: [u64; 2] = bytemuck::pod_read_unaligned(&data[..16]); let ticks = stamps[1].saturating_sub(stamps[0]); out.push((ticks as f64 * f64::from(self.period_ns) / 1e6) as f32); } diff --git a/crates/horizon-client/src/gfx/upload.rs b/crates/horizon-client/src/gfx/upload.rs index a60791d4c..0d56c73a0 100644 --- a/crates/horizon-client/src/gfx/upload.rs +++ b/crates/horizon-client/src/gfx/upload.rs @@ -36,7 +36,9 @@ impl Uploads { let row = width as usize * 4; debug_assert_eq!(pixels.len(), row * height as usize); let padded = row.next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as usize); - let size = NonZeroU64::new((padded * height as usize) as u64).expect("non-empty texture"); + let Some(size) = NonZeroU64::new((padded * height as usize) as u64) else { + return; + }; let alignment = NonZeroU64::new(u64::from(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)) .expect("non-zero alignment"); let slice = self.belt.allocate(size, alignment); diff --git a/crates/horizon-client/src/hud.rs b/crates/horizon-client/src/hud.rs index be4bdb52e..0cc99b07b 100644 --- a/crates/horizon-client/src/hud.rs +++ b/crates/horizon-client/src/hud.rs @@ -977,7 +977,12 @@ impl HudRenderer { capacity, }) } - pub fn animate_fire(&mut self, queue: &wgpu::Queue, tick: u64) { + pub fn animate_fire( + &mut self, + uploads: &mut crate::gfx::upload::Uploads, + encoder: &mut wgpu::CommandEncoder, + tick: u64, + ) { let Some(texture) = &self.atlas_texture else { return; }; @@ -987,7 +992,8 @@ impl HudRenderer { continue; } let pixels = animation.resized_pixels(frame, rect.w, rect.h); - queue.write_texture( + uploads.texture( + encoder, wgpu::TexelCopyTextureInfo { texture, mip_level: 0, @@ -998,35 +1004,27 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, + rect.w, + rect.h, &pixels, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(rect.w * 4), - rows_per_image: Some(rect.h), - }, - wgpu::Extent3d { - width: rect.w, - height: rect.h, - depth_or_array_layers: 1, - }, ); *previous = frame; } } - pub fn draw( + /// Stage the batch's atlas patches, vertices and uniform: before the + /// frame's first pass, so the copies share one command buffer. + pub fn prepare( &mut self, device: &wgpu::Device, - queue: &wgpu::Queue, uploads: &mut crate::gfx::upload::Uploads, encoder: &mut wgpu::CommandEncoder, - target: &wgpu::TextureView, - depth: &wgpu::TextureView, batch: &HudBatch, size: [u32; 2], ) { if let Some(texture) = &self.atlas_texture { for p in &batch.patches { - queue.write_texture( + uploads.texture( + encoder, wgpu::TexelCopyTextureInfo { texture, mip_level: 0, @@ -1037,17 +1035,9 @@ impl HudRenderer { }, aspect: wgpu::TextureAspect::All, }, + p.width, + p.height, &p.rgba, - wgpu::TexelCopyBufferLayout { - offset: 0, - bytes_per_row: Some(p.width * 4), - rows_per_image: None, - }, - wgpu::Extent3d { - width: p.width, - height: p.height, - depth_or_array_layers: 1, - }, ); } } @@ -1078,6 +1068,19 @@ impl HudRenderer { size: [size[0] as f32, size[1] as f32, batch.scale, 0.0], }), ); + } + /// Draw the batch `prepare` staged. + pub fn draw( + &self, + encoder: &mut wgpu::CommandEncoder, + target: &wgpu::TextureView, + depth: &wgpu::TextureView, + batch: &HudBatch, + size: [u32; 2], + ) { + if batch.vertices.is_empty() || size.contains(&0) { + return; + } let attachments = [Some(wgpu::RenderPassColorAttachment { view: target, resolve_target: None, diff --git a/crates/horizon-client/src/interaction_input.rs b/crates/horizon-client/src/interaction_input.rs new file mode 100644 index 000000000..d17cb938c --- /dev/null +++ b/crates/horizon-client/src/interaction_input.rs @@ -0,0 +1,186 @@ +//! The mouse-key portion of Minecraft.handleKeybinds. Events only count clicks; +//! the client tick consumes them before player movement and CLIENT_TICK_END. +#[derive(Default)] +pub struct InteractionInput { + clicks: [u32; 3], +} + +#[derive(Clone, Copy)] +pub enum Button { + Attack, + Use, + Pick, +} + +pub trait InteractionWorld { + fn using_item(&self) -> bool; + fn release_using(&mut self); + fn start_attack(&mut self) -> bool; + fn start_use(&mut self); + fn pick(&mut self); + fn use_delay(&self) -> u32; + fn continue_attack(&mut self, down: bool); +} + +/// Minecraft.startUseItem dispatches one hit result per hand. A passing +/// entity interaction falls back to the item, without trying a block behind it. +pub trait TargetUseWorld { + fn use_entity(&mut self) -> bool; + fn use_block(&mut self) -> bool; + fn use_item(&mut self); +} + +pub fn use_on_target(world: &mut impl TargetUseWorld, entity: bool) { + let consumed = if entity { + world.use_entity() + } else { + world.use_block() + }; + if !consumed { + world.use_item(); + } +} + +impl InteractionInput { + pub fn press(&mut self, button: Button) { + self.clicks[button as usize] += 1; + } + + pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) { + let [attack, use_item, pick] = std::mem::take(&mut self.clicks); + let mut instant = false; + if world.using_item() { + if !use_down { + world.release_using(); + } + // Vanilla drains all three click queues while using an item, + // including the tick that releases it. + } else { + for _ in 0..attack { + instant |= world.start_attack(); + } + for _ in 0..use_item { + world.start_use(); + } + for _ in 0..pick { + world.pick(); + } + } + if use_down && world.use_delay() == 0 && !world.using_item() { + world.start_use(); + } + world.continue_attack(!instant && attack_down); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[derive(Default)] + struct World { + using: bool, + destroying: bool, + delay: u32, + begin_using: bool, + events: Vec<&'static str>, + } + impl InteractionWorld for World { + fn using_item(&self) -> bool { + self.using + } + fn release_using(&mut self) { + self.events.push("release"); + self.using = false; + } + fn start_attack(&mut self) -> bool { + self.events.push("attack"); + false + } + fn start_use(&mut self) { + if !self.destroying { + self.events.push("use"); + self.delay = 4; + self.using = self.begin_using; + } + } + fn pick(&mut self) { + self.events.push("pick"); + } + fn use_delay(&self) -> u32 { + self.delay + } + fn continue_attack(&mut self, _: bool) { + self.events.push("continue"); + } + } + + #[test] + fn quick_clicks_wait_for_a_tick_and_follow_keybind_order() { + let mut input = InteractionInput::default(); + let mut world = World::default(); + input.press(Button::Use); + input.press(Button::Pick); + input.press(Button::Attack); + assert!(world.events.is_empty()); + // Both edges can arrive between ticks; the press still acts once. + input.tick(&mut world, false, false); + assert_eq!(world.events, ["attack", "use", "pick", "continue"]); + world.events.clear(); + input.tick(&mut world, false, false); + assert_eq!( + world.events, + ["continue"], + "no spurious release or repeated click" + ); + } + + #[test] + fn releasing_actual_item_use_discards_clicks_for_that_tick() { + let mut input = InteractionInput::default(); + let mut world = World { + using: true, + ..Default::default() + }; + for button in [Button::Attack, Button::Use, Button::Pick] { + input.press(button); + } + input.tick(&mut world, true, false); + assert_eq!(world.events, ["release", "continue"]); + } + + #[test] + fn holding_use_respects_the_delay_and_active_digging() { + let mut input = InteractionInput::default(); + let mut world = World { + destroying: true, + ..Default::default() + }; + input.press(Button::Use); + input.tick(&mut world, true, true); + assert_eq!(world.events, ["continue"]); + world.destroying = false; + world.events.clear(); + input.tick(&mut world, false, true); + assert_eq!(world.events, ["use", "continue"]); + world.events.clear(); + input.tick(&mut world, false, true); + assert_eq!(world.events, ["continue"]); + } + + #[test] + fn a_quick_use_click_releases_on_the_following_tick() { + let mut input = InteractionInput::default(); + let mut world = World { + begin_using: true, + ..Default::default() + }; + input.press(Button::Use); + input.tick(&mut world, false, false); + assert_eq!(world.events, ["use", "continue"]); + assert!(world.using); + world.events.clear(); + input.tick(&mut world, false, false); + assert_eq!(world.events, ["release", "continue"]); + } +} diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 2782d254f..7f2782c72 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -54,7 +54,8 @@ pub enum ConsumeEffect { }, ClearAllEffects, RemoveEffects(Vec<String>), - TeleportRandomly, + /// `TeleportRandomlyConsumeEffect`. + TeleportRandomly(horizon_world::teleport_consume::TeleportConsume), PlaySound(String), } @@ -67,10 +68,15 @@ pub struct ItemInfo { pub block: Option<BlockStateId>, pub tool: Vec<ToolRule>, pub tool_default_speed: f32, + /// The `tool` component's `damage_per_block`, when the item has the + /// component (a mace or trident has one without rules). + pub tool_damage_per_block: Option<u32>, pub food: Option<(u32, f32)>, pub can_always_eat: bool, - pub consumable: bool, - pub consume_effects: Vec<ConsumeEffect>, + /// `consumable`: its timing, sound, particles and `on_consume_effects`. + pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>, + /// `use_remainder`: what a finished use leaves (`UseRemainder`). + pub use_remainder: Option<String>, pub model: String, /// Main-hand `attack_damage` / `attack_speed` modifier amounts. pub attack_damage: f32, @@ -504,7 +510,18 @@ impl Items { consume_effects.push(ConsumeEffect::RemoveEffects(targets)); } Some("minecraft:teleport_randomly") => { - consume_effects.push(ConsumeEffect::TeleportRandomly); + consume_effects.push(ConsumeEffect::TeleportRandomly( + horizon_world::teleport_consume::TeleportConsume { + diameter: effect + .get("diameter") + .and_then(Value::as_f64) + .map_or(16.0, |d| d as f32), + directional_particles: effect + .get("directional_particles") + .and_then(Value::as_bool) + .unwrap_or(true), + }, + )); } Some("minecraft:play_sound") => { if let Some(sound) = effect.get("sound").and_then(|s| s.as_str()) { @@ -528,10 +545,27 @@ impl Items { tool_default_speed: c["minecraft:tool"]["default_mining_speed"] .as_f64() .unwrap_or(1.0) as f32, + tool_damage_per_block: c + .get("minecraft:tool") + .map(|t| t["damage_per_block"].as_u64().unwrap_or(1) as u32), food, can_always_eat, - consumable: c.get("minecraft:consumable").is_some(), - consume_effects, + // Consumable.CODEC's defaults. + consumable: c.get("minecraft:consumable").map(|cons| { + horizon_world::consumable::Consumable { + seconds: cons["consume_seconds"].as_f64().map_or(1.6, |s| s as f32), + animation: crate::first_person::consumable_animation(cons), + sound: cons["sound"] + .as_str() + .unwrap_or("minecraft:entity.generic.eat") + .to_owned(), + particles: cons["has_consume_particles"].as_bool().unwrap_or(true), + effects: std::mem::take(&mut consume_effects), + } + }), + use_remainder: c["minecraft:use_remainder"]["id"] + .as_str() + .map(str::to_owned), model: c["minecraft:item_model"] .as_str() .unwrap_or(name) @@ -694,6 +728,10 @@ impl Items { songs: HashMap::new(), } } + /// Whether `block` is in the block tag `tag` (`minecraft:fire`, no `#`). + pub fn block_in_tag(&self, tag: &str, block: &str) -> bool { + self.block_tags.get(tag).is_some_and(|s| s.contains(block)) + } fn block_matches(&self, spec: &str, block: &str) -> bool { match spec.strip_prefix('#') { Some(tag) => self.block_tags.get(tag).is_some_and(|s| s.contains(block)), @@ -1607,18 +1645,63 @@ mod tests { 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()); + assert!(!apple.consumable.as_ref().unwrap().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()); + assert!(!enchanted.consumable.as_ref().unwrap().effects.is_empty()); let beef = items.get("minecraft:cooked_beef").expect("cooked beef"); assert!(!beef.can_always_eat); assert!(beef.food.is_some()); + + // Consumables without food, their style and their remainders. + use horizon_world::consumable::UseAnimation; + let milk = items.get("minecraft:milk_bucket").expect("milk bucket"); + let drink = milk.consumable.as_ref().unwrap(); + assert!(milk.food.is_none()); + assert_eq!(drink.effects, [ConsumeEffect::ClearAllEffects]); + assert_eq!((drink.ticks(), drink.animation), (32, UseAnimation::Drink)); + assert_eq!(drink.sound, "minecraft:entity.generic.drink"); + assert!(!drink.particles); + assert_eq!(milk.use_remainder.as_deref(), Some("minecraft:bucket")); + let honey = items.get("minecraft:honey_bottle").expect("honey bottle"); + let sip = honey.consumable.as_ref().unwrap(); + assert_eq!(sip.ticks(), 40); + assert_eq!(sip.sound, "minecraft:item.honey_bottle.drink"); + assert_eq!( + sip.effects, + [ConsumeEffect::RemoveEffects(vec![ + "minecraft:poison".into() + ])] + ); + assert_eq!( + honey.use_remainder.as_deref(), + Some("minecraft:glass_bottle") + ); + let kelp = items.get("minecraft:dried_kelp").unwrap(); + let bite = kelp.consumable.as_ref().unwrap(); + assert_eq!((bite.ticks(), bite.animation), (16, UseAnimation::Eat)); + assert_eq!(bite.sound, "minecraft:entity.generic.eat"); + assert!(bite.particles && kelp.use_remainder.is_none()); + let chorus = items.get("minecraft:chorus_fruit").unwrap(); + assert_eq!( + chorus.consumable.as_ref().unwrap().effects, + [ConsumeEffect::TeleportRandomly( + horizon_world::teleport_consume::TeleportConsume { + diameter: 16.0, + directional_particles: true, + } + )] + ); + let chicken = items.get("minecraft:chicken").unwrap(); + assert!(matches!( + chicken.consumable.as_ref().unwrap().effects[..], + [ConsumeEffect::ApplyEffects { probability, .. }] if probability == 0.3 + )); } } diff --git a/crates/horizon-client/src/lan/attributes.rs b/crates/horizon-client/src/lan/attributes.rs new file mode 100644 index 000000000..bc208b6f9 --- /dev/null +++ b/crates/horizon-client/src/lan/attributes.rs @@ -0,0 +1,143 @@ +//! `ClientboundUpdateAttributesPacket`: the attribute instances a server syncs +//! to its clients. `ServerEntity.sendPairingData` sends every client-syncable +//! instance an entity has (`AttributeMap.getSyncableAttributes`: the instances +//! created so far, not the type's defaults), `sendDirtyEntityData` the ones +//! changed since (`getAttributesToSync`), to the trackers and the player itself. +use horizon_protocol::packets::play::{AttributeModifier, AttributeSnapshot}; +use horizon_world::attributes::{ + Instance, Operation, + entity::{AttributeId, EntityAttributes}, + live::LiveAttributes, +}; + +/// `AttributeModifier.Operation.id`. +pub fn operation_id(op: Operation) -> i32 { + match op { + Operation::AddValue => 0, + Operation::AddMultipliedBase => 1, + Operation::AddMultipliedTotal => 2, + } +} + +/// An `Operation`'s serialized name (`add_value` ...) as its id. +pub fn operation_named(name: &str) -> i32 { + match name { + "add_multiplied_base" => 1, + "add_multiplied_total" => 2, + _ => 0, + } +} + +/// `AttributeSnapshot`: the base and every modifier, in the order they were added. +pub fn snapshot(attribute: AttributeId, instance: &Instance) -> AttributeSnapshot { + AttributeSnapshot { + attribute: attribute.registry_id(), + base: instance.base_value(), + modifiers: instance + .modifiers() + .iter() + .map(|m| AttributeModifier { + id: m.id().to_owned(), + amount: m.amount(), + operation: operation_id(m.operation()), + }) + .collect(), + } +} + +/// `AttributeMap.getSyncableAttributes` of a live map (a player's). +pub fn syncable<G: FnMut() -> i32>(map: &LiveAttributes<G>) -> Vec<AttributeSnapshot> { + let catalog = map.catalog(); + map.instances() + .filter(|(_, key, _)| catalog.attribute(key.attribute()).syncable) + .map(|(_, key, instance)| snapshot(key.attribute(), instance)) + .collect() +} + +/// `getAttributesToSync`, cleared once read (`ServerEntity.sendDirtyEntityData`). +pub fn take_dirty<G: FnMut() -> i32>(map: &mut LiveAttributes<G>) -> Vec<AttributeSnapshot> { + if map.sync().is_empty() { + return Vec::new(); + } + let handles: Vec<_> = map.sync().values().flatten().cloned().collect(); + map.sync_mut().clear(); + handles + .iter() + .filter_map(|h| { + let key = map.attribute(h).ok()?; + Some(snapshot(key.attribute(), map.instance(h).ok()?)) + }) + .collect() +} + +/// The client-syncable instances of a generic attribute map. +pub fn generic_syncable(map: &EntityAttributes) -> impl Iterator<Item = AttributeSnapshot> + '_ { + let catalog = map.catalog(); + catalog + .attributes() + .filter(|(_, a)| a.syncable) + .filter_map(move |(id, _)| map.instance(id).map(|i| snapshot(id, i))) +} + +/// Adds a modifier to the snapshot of `attribute`, creating it with `base`. +pub fn add_modifier( + out: &mut Vec<AttributeSnapshot>, + attribute: i32, + base: f64, + modifier: AttributeModifier, +) { + let snapshot = instance(out, attribute, base); + match snapshot.modifiers.iter_mut().find(|m| m.id == modifier.id) { + Some(m) => *m = modifier, + None => snapshot.modifiers.push(modifier), + } +} + +/// The snapshot of `attribute`, created with `base` if it isn't there yet. +pub fn instance( + out: &mut Vec<AttributeSnapshot>, + attribute: i32, + base: f64, +) -> &mut AttributeSnapshot { + let i = match out.iter().position(|a| a.attribute == attribute) { + Some(i) => i, + None => { + out.push(AttributeSnapshot { + attribute, + base, + modifiers: Vec::new(), + }); + out.len() - 1 + } + }; + &mut out[i] +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn modifiers_replace_by_id_and_instances_are_created_once() { + let mut out = Vec::new(); + let m = |id: &str, amount| AttributeModifier { + id: id.into(), + amount, + operation: 0, + }; + add_modifier(&mut out, 1, 0.0, m("minecraft:armor.helmet", 3.0)); + add_modifier(&mut out, 1, 5.0, m("minecraft:armor.chestplate", 8.0)); + add_modifier(&mut out, 1, 5.0, m("minecraft:armor.helmet", 2.0)); + assert_eq!(out.len(), 1); + assert_eq!(out[0].base, 0.0); + assert_eq!( + out[0].modifiers, + [ + m("minecraft:armor.helmet", 2.0), + m("minecraft:armor.chestplate", 8.0) + ] + ); + instance(&mut out, 26, 0.7); + assert_eq!(out.len(), 2); + } +} diff --git a/crates/horizon-client/src/lan/chunks.rs b/crates/horizon-client/src/lan/chunks.rs index a9cf57a7d..35339a05c 100644 --- a/crates/horizon-client/src/lan/chunks.rs +++ b/crates/horizon-client/src/lan/chunks.rs @@ -15,7 +15,13 @@ use horizon_protocol::{ registry::{Builtin, ceil_log2}, }; use horizon_world::nbt::Tag; -use std::{collections::HashMap, sync::Arc}; +use std::{ + collections::HashMap, + sync::{ + Arc, OnceLock, + atomic::{AtomicUsize, Ordering}, + }, +}; const NON_AIR: u8 = 1; const FLUID: u8 = 2; @@ -83,12 +89,10 @@ pub fn block_entity_type(name: &str) -> Option<&'static str> { /// Per-state facts and registry ids for encoding chunks. pub struct ChunkEncoder { - flags: Vec<u8>, + /// What encoding a section needs, shared with the warm-up threads. + coder: Arc<SectionCoder>, /// Block entity type id per state (-1 for none). entity_types: Vec<i16>, - /// Network biome id per internal biome index. - pub biome_ids: Vec<i32>, - biome_bits: u8, /// The block registry id of each state's block, for BlockEvent. pub block_ids: Vec<i32>, /// The save's tables, for the heightmaps. @@ -104,6 +108,14 @@ pub struct ChunkEncoder { sky: bool, } +/// Per-state flags and biome ids: all a section's encoding reads. +struct SectionCoder { + flags: Vec<u8>, + /// Network biome id per internal biome index. + biome_ids: Vec<i32>, + biome_bits: u8, +} + /// A column's client heightmaps, valid while it holds the same sections. struct Heights { sections: Vec<std::sync::Weak<Section>>, @@ -170,8 +182,151 @@ impl Layers { } } +impl SectionCoder { + /// LevelChunkSection.write, and its block entity blocks. + fn wire(&self, section: &Section) -> (Arc<[u8]>, Entities) { + let (encoded, entities) = self.section(section); + let mut w = horizon_protocol::buf::Writer::new(); + encoded.write(&mut w); + (w.data.into(), entities.into()) + } + + 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, 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 { + fluids += n; + } + } + f & ENTITY != 0 + }; + // One block everywhere (all air, mostly): what from_values would give. + let uniform = section.blocks.uniform(); + if let Some(v) = uniform { + if count(v, BLOCKS as i16) { + entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); + } + } else { + let mut unpacked = [0u32; BLOCKS]; + section.unpack(&mut unpacked); + 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<i32> = (0..BIOMES) + .map(|j| { + let internal = section.biomes.get(j) as u16; + self.biome_ids + .get(usize::from(internal)) + .copied() + .unwrap_or(0) + }) + .collect(); + ( + horizon_protocol::chunk::Section { + non_empty, + fluids, + states: match uniform { + Some(v) => Paletted { + bits: 0, + palette: vec![v as i32], + data: Vec::new(), + }, + None => Paletted::from_values( + &values, + Strategy::Blocks, + crate::chunk::block_strategy().global_bits, + ), + }, + biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), + }, + entities, + ) + } +} + /// Sections kept before the ones no longer resident are dropped. const CACHE_SWEEP: usize = 1 << 15; + +/// Uncached sections below which a batch is encoded on the tick's thread +/// alone: waking the warm-up threads costs more than a few sections. +const WARM_MIN: usize = 16; + +/// Sections a batch needs, each taken by whichever thread is free first, +/// and what each gave: its wire bytes and, with varying light, its layers. +struct Warm { + coder: Arc<SectionCoder>, + sections: Vec<Arc<Section>>, + next: AtomicUsize, + done: Vec<OnceLock<Warmed>>, +} +type Warmed = ((Arc<[u8]>, Entities), Option<Arc<Layers>>); +impl Warm { + /// Encode sections until none is left to take. + fn run(&self) { + loop { + let i = self.next.fetch_add(1, Ordering::Relaxed); + let Some(s) = self.sections.get(i) else { + return; + }; + let light = matches!(s.light, Light::Full(_)).then(|| Arc::new(Layers::of(&s.light))); + let _ = self.done[i].set((self.coder.wire(s), light)); + } + } +} + +/// The warm-up threads (one per core besides the tick's) and the job they +/// take: its number, and the job while it has sections left to take. +struct WarmPool { + job: std::sync::Mutex<(u64, Option<Arc<Warm>>)>, + ready: std::sync::Condvar, +} + +/// The warm-up threads, started the first time; none on a single core or +/// when no thread could start. +fn warm_pool() -> Option<&'static WarmPool> { + static POOL: OnceLock<Option<Arc<WarmPool>>> = OnceLock::new(); + POOL.get_or_init(|| { + let threads = std::thread::available_parallelism().map_or(1, |n| n.get()) - 1; + let pool = Arc::new(WarmPool { + job: Default::default(), + ready: Default::default(), + }); + let started = (0..threads) + .filter(|i| { + let pool = pool.clone(); + std::thread::Builder::new() + .name(format!("horizon-chunk-encode-{i}")) + .spawn(move || { + let mut done = 0; + loop { + let job = { + let mut slot = pool.job.lock().unwrap(); + while slot.0 == done { + slot = pool.ready.wait(slot).unwrap(); + } + done = slot.0; + slot.1.clone() + }; + if let Some(job) = job { + job.run(); + } + } + }) + .is_ok() + }) + .count(); + (started > 0).then_some(pool) + }) + .as_deref() +} impl ChunkEncoder { /// `biome_names`: the internal biome list in order; `biome_registry`: /// the synchronized biome entries in network order. @@ -218,10 +373,12 @@ impl ChunkEncoder { }) .collect(); Self { - flags, + coder: Arc::new(SectionCoder { + flags, + biome_ids, + biome_bits: ceil_log2(biome_registry.len()), + }), entity_types, - biome_ids, - biome_bits: ceil_log2(biome_registry.len()), block_ids, tables: None, cache: Default::default(), @@ -297,7 +454,8 @@ impl ChunkEncoder { /// LevelChunkSection.hasOnlyAir, negated. fn non_air(&self, section: &Section) -> bool { - let non_air = |v: u32| self.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; + let non_air = + |v: u32| self.coder.flags.get(v as usize).copied().unwrap_or(0) & NON_AIR != 0; // The palette first: most sections are all air, or one block. if !section.blocks.maybe_has(non_air) { false @@ -314,10 +472,7 @@ impl ChunkEncoder { 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]>, Entities) = (w.data.into(), entities.into()); + let wire = self.coder.wire(section); self.cached(section, |e| e.wire = Some(wire.clone())); wire } @@ -340,71 +495,12 @@ impl ChunkEncoder { .map(|t| i32::from(*t)) } pub fn is_air(&self, state: u32) -> bool { - self.flags + self.coder + .flags .get(state as usize) .is_none_or(|f| f & NON_AIR == 0) } - 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, 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 { - fluids += n; - } - } - f & ENTITY != 0 - }; - // One block everywhere (all air, mostly): what from_values would give. - let uniform = section.blocks.uniform(); - if let Some(v) = uniform { - if count(v, BLOCKS as i16) { - entities = (0..BLOCKS as u16).map(|i| (i, v)).collect(); - } - } else { - let mut unpacked = [0u32; BLOCKS]; - section.unpack(&mut unpacked); - 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<i32> = (0..BIOMES) - .map(|j| { - let internal = section.biomes.get(j) as u16; - self.biome_ids - .get(usize::from(internal)) - .copied() - .unwrap_or(0) - }) - .collect(); - ( - horizon_protocol::chunk::Section { - non_empty, - fluids, - states: match uniform { - Some(v) => Paletted { - bits: 0, - palette: vec![v as i32], - data: Vec::new(), - }, - None => Paletted::from_values( - &values, - Strategy::Blocks, - crate::chunk::block_strategy().global_bits, - ), - }, - biomes: Paletted::from_values(&biome_values, Strategy::Biomes, self.biome_bits), - }, - entities, - ) - } - /// The chunk column with its light and block entities. /// The non-air sections of a column as bits (LevelChunkSection.hasOnlyAir). fn occupied(&self, chunk: &Chunk) -> u64 { @@ -442,6 +538,65 @@ impl ChunkEncoder { self.body(chunk, &world.block_entities, self.around(chunk, world)) } + /// Encode the sections of these columns not cached yet before their + /// bodies are made, shared out to the warm-up threads: a batch of new + /// terrain costs mostly its sections' first encoding. This thread takes + /// sections too until none is left, then caches what is done; it never + /// waits for the other threads (they keep their results to themselves + /// until then), and a section one of them is still on is encoded again + /// by `body_in`, with the same bytes. + pub fn warm(&self, columns: &[&Chunk]) { + let sections: Vec<Arc<Section>> = { + let cache = self.cache.lock().unwrap(); + columns + .iter() + .flat_map(|c| &c.sections[self.sections.clone()]) + .filter(|s| { + cache + .get(&(Arc::as_ptr(s) as usize)) + .is_none_or(|e| e.wire.is_none()) + }) + .cloned() + .collect() + }; + if sections.len() < WARM_MIN { + return; + } + let Some(pool) = warm_pool() else { + return; + }; + let job = Arc::new(Warm { + coder: self.coder.clone(), + done: sections.iter().map(|_| OnceLock::new()).collect(), + sections, + next: AtomicUsize::new(0), + }); + { + let mut slot = pool.job.lock().unwrap(); + slot.0 += 1; + slot.1 = Some(job.clone()); + } + pool.ready.notify_all(); + job.run(); + // Every section is claimed: the job leaves the slot. + { + let mut slot = pool.job.lock().unwrap(); + if slot.1.as_ref().is_some_and(|j| Arc::ptr_eq(j, &job)) { + slot.1 = None; + } + } + let mut cache = self.cache.lock().unwrap(); + for (s, done) in job.sections.iter().zip(&job.done) { + if let Some((wire, light)) = done.get() { + let e = self.entry(&mut cache, s); + e.wire = Some(wire.clone()); + if light.is_some() { + e.light = light.clone(); + } + } + } + } + fn body( &self, chunk: &Chunk, @@ -930,7 +1085,7 @@ mod tests { /// The bytes on the wire for a section, encoded afresh. fn fresh(encoder: &ChunkEncoder, section: &Section) -> Vec<u8> { let mut w = horizon_protocol::buf::Writer::new(); - encoder.section(section).0.write(&mut w); + encoder.coder.section(section).0.write(&mut w); w.data } @@ -1077,6 +1232,67 @@ mod tests { ); } + /// Columns whose sections the warm-up threads encoded give the bytes + /// each gives on its own, also with a column twice and its neighbours' + /// sections deciding the light layers. + #[test] + fn warmed_columns_give_the_same_bodies() { + let builtin = Builtin::parse( + r#"{"minecraft:block_entity_type": {"entries": { + "minecraft:sign": {"protocol_id": 7}}}}"#, + ) + .unwrap(); + let states = [ + "minecraft:air", + "minecraft:stone", + "minecraft:water", + "minecraft:oak_sign", + ] + .map(|n| (Arc::<str>::from(n), n.ends_with("water"))); + let mut world = crate::world::World::new(horizon_world::registry::BlockStateId(0), 0); + for x in -2..2 { + for z in -2..2 { + let mut chunk = Chunk::empty(x, z); + let n = (x * 7 + z * 13).rem_euclid(17); + for i in 0..40 + n * 30 { + let (bx, bz) = ((i * 5 + n) % 16, (i * 11) % 16); + chunk.set(bx, MIN_Y + (i * 37 + n * 50) % 384, bz, 1 + (i % 3) as u32); + } + let mut light = Box::new([0u8; 4096]); + for (i, v) in light.iter_mut().enumerate() { + *v = (i * 31 + n as usize) as u8; + } + Arc::make_mut(&mut chunk.sections[(n % 24) as usize]).light = Light::Full(light); + world.block_entities.insert( + (x * 16 + 2, 70, z * 16 + 3), + BlockEntity::Sign(crate::signs::SignData::default()), + ); + chunk.set(2, 70, 3, 3); + world.chunks.insert((x, z), Arc::new(chunk)); + } + } + let mut keys: Vec<(i32, i32)> = + (-2..2).flat_map(|x| (-2..2).map(move |z| (x, z))).collect(); + keys.push(keys[5]); + let chunks: Vec<&Chunk> = keys + .iter() + .map(|k| &**world.chunks.get(k).unwrap()) + .collect(); + let alone = ChunkEncoder::new(states.clone(), &builtin, &[], &[]); + let expected: Vec<Vec<u8>> = chunks.iter().map(|c| alone.body_in(c, &world)).collect(); + let warmed = ChunkEncoder::new(states, &builtin, &[], &[]); + let bodies = |encoder: &ChunkEncoder| -> Vec<Vec<u8>> { + chunks.iter().map(|c| encoder.body_in(c, &world)).collect() + }; + assert!(chunks.len() * SECTIONS >= WARM_MIN); + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + // Again, from the cache, with nothing left to warm. + warmed.warm(&chunks); + assert_eq!(bodies(&warmed), expected); + warmed.warm(&[]); + } + #[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/containers.rs b/crates/horizon-client/src/lan/containers.rs index 3ecd58b80..66fbfe4b6 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -109,6 +109,33 @@ impl Hub { ); } + /// `ServerLevel.broadcastDamageEvent`: the clients around show the hurt + /// entity's flash and hear its hurt sound. + pub fn damage_event( + &self, + id: i32, + kind: &str, + cause: Option<i32>, + direct: Option<i32>, + at: [f64; 3], + ) { + let Some(source_type) = self.sync.id("minecraft:damage_type", kind) else { + return; + }; + self.broadcast_near( + at, + 128.0, + &C::DamageEvent(play::DamageEvent { + id, + source_type, + cause, + direct, + position: None, + }), + None, + ); + } + pub fn swing(&self, id: i32, hand: i32, at: [f64; 3], except: Option<u32>) { self.broadcast_near( at, @@ -428,15 +455,17 @@ impl Hub { let Slots::Block(pos) = m.slots else { return; }; - let Some(BlockEntity::Furnace(f)) = world.block_entities.get(&pos) else { - return; - }; - let data = [ - f.lit_remaining, - f.lit_total, - f.cooking_timer, - f.cooking_total, - ] + // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess. + let data = match world.block_entities.get(&pos) { + Some(BlockEntity::Furnace(f)) => [ + f.lit_remaining, + f.lit_total, + f.cooking_timer, + f.cooking_total, + ], + Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel], + _ => return, + } .map(|v| v as i16); m.sent_data.resize(data.len(), i16::MIN); let window = m.window; diff --git a/crates/horizon-client/src/lan/entity.rs b/crates/horizon-client/src/lan/entity.rs index 3d8090267..9082e01fa 100644 --- a/crates/horizon-client/src/lan/entity.rs +++ b/crates/horizon-client/src/lan/entity.rs @@ -8,15 +8,31 @@ use super::tracking; use horizon_protocol::{ buf::pack_degrees, - entity_data::Value, + entity_data::{Value, serializer}, item::Stack, packets::play::{ - self, AddEntity, EntityPositionSync, MoveEntity, MoveEntityPos, MoveEntityPosRot, - MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, SetEquipment, - SetPassengers, VecDelta, + self, AddEntity, AttributeSnapshot, EntityPositionSync, MoveEntity, MoveEntityPos, + MoveEntityPosRot, MoveEntityRot, PositionPath, RotateHead, SetEntityData, SetEntityMotion, + SetEquipment, SetPassengers, UpdateAttributes, VecDelta, }, }; +/// The attribute instances of `now` that differ from what `sent` held (an +/// instance is never removed: one that disappears is left as it was sent). +pub fn changed_attributes( + now: &[AttributeSnapshot], + sent: &[AttributeSnapshot], +) -> Vec<AttributeSnapshot> { + now.iter() + .filter(|a| { + sent.iter() + .find(|b| b.attribute == a.attribute) + .is_none_or(|b| b != *a) + }) + .cloned() + .collect() +} + /// What the game says about one entity this tick. #[derive(Clone, Debug)] pub struct EntityState { @@ -37,6 +53,9 @@ 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<Stack>)>, + /// A living entity's client-syncable attribute instances + /// (`AttributeMap.getSyncableAttributes`), by registry id. + pub attributes: Vec<AttributeSnapshot>, /// `Entity.getRequiresPrecisePosition` (primed TNT and falling blocks /// touching a block): moves are sent as full position syncs. pub precise: bool, @@ -117,6 +136,8 @@ struct ServerEntity { /// trackedDataValues: the entity data the clients hold. meta: Vec<(u8, i32, Value)>, equipment: Vec<(u8, Option<Stack>)>, + /// The attribute instances the clients hold. + attributes: Vec<AttributeSnapshot>, was_on_ground: bool, tick: u32, teleport_delay: u32, @@ -129,6 +150,14 @@ struct ServerEntity { seen: u32, index: usize, added: bool, + /// TrackedEntity.lastSectionPos: its pairs are checked again when it + /// moves to another section. + section: [i32; 3], +} + +/// SectionPos.of(entity). +fn section_of(position: [f64; 3]) -> [i32; 3] { + position.map(|v| (v.floor() as i32) >> 4) } /// VecDeltaCodec.encode. @@ -153,6 +182,7 @@ impl ServerEntity { velocity: e.velocity, meta: e.meta.clone(), equipment: e.equipment.clone(), + attributes: e.attributes.clone(), was_on_ground: e.on_ground, tick: 0, teleport_delay: 0, @@ -161,6 +191,7 @@ impl ServerEntity { seen: 0, index: 0, added: true, + section: section_of(e.position), } } @@ -190,6 +221,13 @@ impl ServerEntity { values: self.meta.clone(), })); } + // getSyncableAttributes: the instances as they are now. + if !e.attributes.is_empty() { + out.push(play::Clientbound::UpdateAttributes(UpdateAttributes { + id: e.id, + values: e.attributes.clone(), + })); + } if !self.equipment.is_empty() { out.push(play::Clientbound::SetEquipment(SetEquipment { id: e.id, @@ -342,24 +380,48 @@ impl ServerEntity { self.send_equipment(e, out); } - /// ServerEntity.sendDirtyEntityData. + /// ServerEntity.sendDirtyEntityData: the changed entity data, then the + /// attribute instances that changed since they were last sent + /// (`AttributeMap.getAttributesToSync`). fn send_dirty(&mut self, e: &EntityState, dirty: bool, out: &mut Vec<play::Clientbound>) { - if !dirty { - return; + if dirty { + let mut changed: Vec<_> = e + .meta + .iter() + .filter(|m| !self.meta.contains(m)) + .cloned() + .collect(); + // A value back at its default is left out of the state, but the + // clients still hold the old one: Entity's shared flags and pose go + // back to 0 (a player standing up again, a mob no longer on fire). + for (index, kind, _) in &self.meta { + let default = match (*index, *kind) { + (0, serializer::BYTE) => Value::Byte(0), + (6, serializer::POSE) => Value::Id(0), + _ => continue, + }; + if !e.meta.iter().any(|m| m.0 == *index) { + changed.push((*index, *kind, default)); + } + } + if !changed.is_empty() { + out.push(play::Clientbound::SetEntityData(SetEntityData { + id: e.id, + values: changed, + })); + } + self.meta.clone_from(&e.meta); } - let changed: Vec<_> = e - .meta - .iter() - .filter(|m| !self.meta.contains(m)) - .cloned() - .collect(); - if !changed.is_empty() { - out.push(play::Clientbound::SetEntityData(SetEntityData { - id: e.id, - values: changed, - })); + if e.attributes != self.attributes { + let changed = changed_attributes(&e.attributes, &self.attributes); + if !changed.is_empty() { + out.push(play::Clientbound::UpdateAttributes(UpdateAttributes { + id: e.id, + values: changed, + })); + } + self.attributes.clone_from(&e.attributes); } - self.meta.clone_from(&e.meta); } fn send_head(&mut self, e: &EntityState, out: &mut Vec<play::Clientbound>) { @@ -416,6 +478,11 @@ impl Tracker { pub fn clear(&mut self) { self.seen.clear(); } + /// Stop tracking `id` without a packet: the caller removes it from the + /// client, and the next tick pairs it again if it is still in range. + pub fn forget(&mut self, id: i32) -> bool { + self.seen.remove(&id) + } pub fn len(&self) -> usize { self.seen.len() } @@ -428,6 +495,9 @@ impl Tracker { /// view distance and chunks. pub struct Viewer<'a> { pub entity_id: i32, + /// It accepted a move since the last tick (ChunkMap.move): every pair + /// of it is checked again. + pub moved: bool, pub position: [f64; 3], pub view_distance: i32, pub chunks: &'a crate::fast_hash::FxHashSet<(i32, i32)>, @@ -436,22 +506,32 @@ pub struct Viewer<'a> { pub out: &'a mut Vec<Vec<u8>>, } -/// TrackedEntity.updatePlayer: within the type's range (capped by the view -/// distance) horizontally, in a chunk the client has. -fn sees( - position: [f64; 3], - view_distance: i32, - chunks: &crate::fast_hash::FxHashSet<(i32, i32)>, - e: &EntityState, +/// One entity as this tick's range checks read it: where it is +/// horizontally, its id, its type's tracking range in chunks and the chunk +/// it is in (an index into the tick's chunks). +#[derive(Clone, Copy)] +struct Probe { + x: f64, + z: f64, + id: i32, range: i32, -) -> bool { - let range = f64::from(range.min(view_distance) * 16); - let (dx, dz) = (position[0] - e.position[0], position[2] - e.position[2]); - let chunk = ( - (e.position[0].floor() as i32) >> 4, - (e.position[2].floor() as i32) >> 4, - ); - dx * dx + dz * dz <= range * range && chunks.contains(&chunk) + chunk: u32, +} + +/// TrackedEntity.updatePlayer: within the type's range (capped by the view +/// distance) horizontally, in a chunk the client has. `held` remembers for +/// each of the tick's chunks whether the client has it (0: not looked up +/// yet, 1: no, 2: yes), so each chunk is looked up once per client. +fn sees(v: &Viewer, p: &Probe, chunks: &[(i32, i32)], held: &mut [u8]) -> bool { + let range = f64::from(p.range.min(v.view_distance) * 16); + let (dx, dz) = (v.position[0] - p.x, v.position[2] - p.z); + dx * dx + dz * dz <= range * range && { + let held = &mut held[p.chunk as usize]; + if *held == 0 { + *held = 1 + u8::from(v.chunks.contains(&chunks[p.chunk as usize])); + } + *held == 2 + } } /// One level's tracked entities (ChunkMap.entityMap). @@ -460,10 +540,22 @@ pub struct Entities { states: crate::fast_hash::FxHashMap<i32, ServerEntity>, /// The level tick, stamped on every entity still in the level. tick: u32, - /// This tick's tracking range of each entity, and what each client - /// makes of each entity ([`SEES`], [`TRACKS`]), kept between ticks. - ranges: Vec<i32>, + /// This tick's entities as the range checks read them, the chunks they + /// are in (and each one's index), whether the client being checked has + /// each chunk, and what each client makes of each entity ([`SEES`], + /// [`TRACKS`]), kept between ticks. + probes: Vec<Probe>, + chunks: Vec<(i32, i32)>, + chunk_index: crate::fast_hash::FxHashMap<(i32, i32), u32>, + held: Vec<u8>, flags: Vec<Vec<u8>>, + /// Whether a client starts tracking each entity this tick. + pairs: Vec<bool>, + /// The entities that appeared or moved to another section this tick + /// (their pairs with every client are checked again), in order and as a + /// flag per entity. + moved: Vec<usize>, + is_moved: Vec<bool>, /// One entity's packets and their bodies, kept between entities. packets: Vec<play::Clientbound>, bodies: Vec<Vec<u8>>, @@ -501,30 +593,118 @@ impl Entities { ) { self.tick = self.tick.wrapping_add(1); let now = self.tick; - self.ranges.clear(); + self.probes.clear(); + self.chunks.clear(); + self.chunk_index.clear(); + self.moved.clear(); + self.is_moved.clear(); + self.is_moved.resize(entities.len(), false); for (index, e) in entities.iter().enumerate() { - let s = self - .states - .entry(e.id) - .or_insert_with(|| ServerEntity::new(e, kind(&e.kind), riding)); + let mut added = false; + let s = self.states.entry(e.id).or_insert_with(|| { + added = true; + ServerEntity::new(e, kind(&e.kind), riding) + }); s.seen = now; s.index = index; - self.ranges.push(s.range); + // ChunkMap.addEntity, and ChunkMap.tick's section change: + // updatePlayers. + let section = section_of(e.position); + if added || section != s.section { + s.section = section; + self.moved.push(index); + self.is_moved[index] = true; + } + let at = ( + (e.position[0].floor() as i32) >> 4, + (e.position[2].floor() as i32) >> 4, + ); + let next = self.chunks.len() as u32; + let chunk = *self.chunk_index.entry(at).or_insert(next); + if chunk == next { + self.chunks.push(at); + } + self.probes.push(Probe { + x: e.position[0], + z: e.position[2], + id: e.id, + range: s.range, + chunk, + }); } self.flags.resize_with(viewers.len(), Vec::new); + self.pairs.clear(); + self.pairs.resize(entities.len(), false); for (v, flags) in viewers.iter_mut().zip(&mut self.flags) { flags.clear(); + self.held.clear(); + self.held.resize(self.chunks.len(), 0); + let (chunks, held, pairs) = (&self.chunks, &mut self.held, &mut self.pairs); let mut kept = 0; - flags.extend(entities.iter().zip(&self.ranges).map(|(e, &range)| { - if e.id == v.entity_id || !sees(v.position, v.view_distance, v.chunks, e, range) { - 0 - } else if v.tracker.seen.contains(&e.id) { - kept += 1; - SEES | TRACKS - } else { - SEES + // A client that moved (ChunkMap.move), or whose own entity + // appeared or changed section (ChunkMap.tick's movedPlayers), has + // every pair checked again. + let all = v.moved + || self + .states + .get(&v.entity_id) + .is_none_or(|s| s.seen != now || self.is_moved[s.index]); + if all { + flags.extend(self.probes.iter().zip(pairs.iter_mut()).map(|(p, pairs)| { + if p.id == v.entity_id || !sees(v, p, chunks, held) { + 0 + } else if v.tracker.seen.contains(&p.id) { + kept += 1; + SEES | TRACKS + } else { + *pairs = true; + SEES + } + })); + } else if v.tracker.seen.len() * 4 > self.probes.len() { + // Otherwise its pairs stay as they were, but for the entities + // that appeared or changed section; a client tracking much + // of the level goes through it in order. + let is_moved = &self.is_moved; + flags.extend(self.probes.iter().zip(pairs.iter_mut()).zip(is_moved).map( + |((p, pairs), &moved)| { + let tracks = v.tracker.seen.contains(&p.id); + if p.id == v.entity_id || (moved && !sees(v, p, chunks, held)) { + 0 + } else if tracks { + kept += 1; + SEES | TRACKS + } else if moved { + *pairs = true; + SEES + } else { + 0 + } + }, + )); + } else { + // One tracking little of it, from what it tracks. + flags.resize(self.probes.len(), 0); + for id in &v.tracker.seen { + if let Some(s) = self.states.get(id).filter(|s| s.seen == now) { + flags[s.index] = SEES | TRACKS; + kept += 1; + } } - })); + for &index in &self.moved { + let p = &self.probes[index]; + let tracks = flags[index] & TRACKS != 0; + if p.id != v.entity_id && sees(v, p, chunks, held) { + if !tracks { + flags[index] = SEES; + pairs[index] = true; + } + } else if tracks { + flags[index] = 0; + kept -= 1; + } + } + } // Usually the client still sees all it tracks. let mut removed = Vec::new(); if kept != v.tracker.seen.len() { @@ -553,6 +733,10 @@ impl Entities { s.send_changes(e, riding, &mut self.packets); } s.added = false; + // Nothing to send: no changes, and nobody starts tracking it. + if self.packets.is_empty() && !self.pairs[index] { + continue; + } let mut encoded = false; let mut pairing: Option<Vec<Vec<u8>>> = None; for (v, flags) in viewers.iter_mut().zip(&self.flags) { @@ -601,6 +785,7 @@ mod tests { data: 0, meta: Vec::new(), equipment: Vec::new(), + attributes: Vec::new(), precise: false, } } @@ -697,6 +882,71 @@ mod tests { )); } + #[test] + fn attributes_pair_whole_then_send_the_changed_instances_when_due() { + let speed = |base| AttributeSnapshot { + attribute: 26, + base, + modifiers: Vec::new(), + }; + let armor = AttributeSnapshot { + attribute: 1, + base: 0.0, + modifiers: Vec::new(), + }; + let mut e = state(0.0); + e.attributes = vec![speed(0.23), armor]; + let mut s = added(&e); + let mut spawn = Vec::new(); + s.pairing(&e, 100, &Riding::default(), &mut spawn); + let Some(play::Clientbound::UpdateAttributes(p)) = spawn.get(1) else { + panic!("expected the attributes after the add"); + }; + assert_eq!(p.values, e.attributes); + changes(&mut s, &e); + e.attributes[0] = speed(0.3); + // Not due (a zombie's interval is 3): sendDirtyEntityData waits for the update. + assert!(changes(&mut s, &e).is_empty()); + assert!(changes(&mut s, &e).is_empty()); + let out = changes(&mut s, &e); + let Some(play::Clientbound::UpdateAttributes(p)) = out + .iter() + .find(|p| matches!(p, play::Clientbound::UpdateAttributes(_))) + else { + panic!("expected the changed attribute"); + }; + assert_eq!(p.values, vec![speed(0.3)]); + } + + #[test] + fn cleared_flags_and_pose_go_back_to_their_default() { + let mut e = state(0.0); + let mut s = added(&e); + changes(&mut s, &e); + // A crouching player: the crouch flag and the crouching pose. + e.meta = vec![ + (0, serializer::BYTE, Value::Byte(2)), + (6, serializer::POSE, Value::Id(5)), + ]; + changes(&mut s, &e); + e.meta.clear(); + let data = changes(&mut s, &e) + .into_iter() + .find_map(|p| match p { + play::Clientbound::SetEntityData(d) => Some(d), + _ => None, + }) + .expect("standing up is sent"); + assert_eq!( + data.values, + vec![ + (0, serializer::BYTE, Value::Byte(0)), + (6, serializer::POSE, Value::Id(0)), + ] + ); + assert!(changes(&mut s, &e).is_empty()); + } + #[test] fn metadata_and_equipment_send_only_the_changes() { let mut e = state(0.0); @@ -728,6 +978,7 @@ mod tests { trackers: [Tracker; 2], out: [Vec<Vec<u8>>; 2], positions: [[f64; 3]; 2], + moved: [bool; 2], } impl Clients { @@ -737,6 +988,7 @@ mod tests { trackers: Default::default(), out: Default::default(), positions: [[0.0, 64.0, 0.0]; 2], + moved: [false; 2], } } fn tick(&mut self, level: &mut Entities, entities: &[&EntityState]) { @@ -748,6 +1000,7 @@ mod tests { let mut viewers = [ Viewer { entity_id: 1, + moved: self.moved[0], position: self.positions[0], view_distance: 10, chunks: &self.chunks, @@ -756,6 +1009,7 @@ mod tests { }, Viewer { entity_id: 2, + moved: self.moved[1], position: self.positions[1], view_distance: 10, chunks: &self.chunks, @@ -771,6 +1025,39 @@ mod tests { p.encode() } + /// ChunkMap checks a pair again only when one side moves: a zombie + /// walking into range within its section isn't paired with a client + /// standing still until the client moves, and one walking out stays + /// tracked until it changes section. + #[test] + fn pairs_are_checked_again_when_a_side_moves() { + let mut level = Entities::default(); + let mut clients = Clients::new(); + clients.positions[0] = [-108.0, 64.0, 0.0]; + let mut me = state(-108.0); + (me.id, me.kind) = (1, "minecraft:player".into()); + // 128.5 blocks away: past a zombie's 8 chunks. + let tracks = |clients: &Clients| clients.trackers[0].is_tracking(7); + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(!tracks(&clients)); + // 127.5 blocks away, in the same section: not checked again. + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(!tracks(&clients)); + // The client's move checks every pair of it. + clients.moved[0] = true; + clients.tick(&mut level, &[&me, &state(19.5)]); + assert!(tracks(&clients)); + clients.moved[0] = false; + clients.tick(&mut level, &[&me, &state(20.5)]); + assert!(tracks(&clients)); + // Into the next section, out of range: no longer tracked. + clients.tick(&mut level, &[&me, &state(40.0)]); + assert!(!tracks(&clients)); + // The other client (at the origin, its entity not in the level) + // checks every pair each tick. + assert!(clients.trackers[1].is_tracking(7)); + } + #[test] fn every_client_gets_the_same_changes_and_late_ones_are_paired() { let mut level = Entities::default(); @@ -828,4 +1115,58 @@ mod tests { assert_eq!(c.out[0].first(), Some(&removed)); assert_eq!(level.len(), 1); } + + #[test] + fn entities_in_chunks_a_client_lacks_wait_for_them() { + let mut level = Entities::default(); + let mut c = Clients::new(); + // Two zombies in range in chunk (4, 0), which the clients don't have + // yet, and one in chunk (0, 0). + let mut far = state(70.0); + let mut near = state(66.0); + near.id = 8; + let mut home = state(1.0); + home.id = 9; + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(!t.is_tracking(7) && !t.is_tracking(8) && t.is_tracking(9)); + } + // The chunk arrives: both are paired, in order. + c.chunks.insert((4, 0)); + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(t.is_tracking(7) && t.is_tracking(8) && t.is_tracking(9)); + } + // One walks back into chunk (3, 0) and the other out of range. + far.position[0] = 200.0; + near.position[0] = 60.0; + c.tick(&mut level, &[&far, &near, &home]); + for t in &c.trackers { + assert!(!t.is_tracking(7) && t.is_tracking(8) && t.is_tracking(9)); + } + } + + #[test] + fn a_forgotten_entity_is_paired_again_at_the_next_tick() { + // A respawned player: the hub removes it from the other clients and + // forgets it, and the next tick pairs it again as a new entity. + let mut level = Entities::default(); + let mut c = Clients::new(); + let mut player = state(0.0); + player.id = 1; + player.kind = "minecraft:player".into(); + c.tick(&mut level, &[&player]); + c.tick(&mut level, &[&player]); + assert!(c.trackers[1].forget(1)); + assert!(!c.trackers[1].forget(1)); + c.tick(&mut level, &[&player]); + assert!(c.trackers[1].is_tracking(1)); + let paired = c.out[1] + .first() + .and_then(|p| play::Clientbound::decode(i32::from(p[0]), &p[1..]).ok()); + assert!( + matches!(paired, Some(play::Clientbound::AddEntity(ref a)) if a.id == 1), + "{paired:?}" + ); + } } diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 1a699bc45..91bf2709f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -75,6 +75,9 @@ pub struct Guest { pub fall_flying: bool, pub flying: bool, pub sleeping: bool, + /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS`: 1 while using an item, 2 if + /// it is in the off hand. + pub living_flags: i8, /// 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]>, @@ -99,6 +102,9 @@ pub struct Guest { /// A position move arrived since the client's last ClientTickEnd /// (receivedPositionThisTick): a second one is a protocol error. pub position_this_tick: bool, + /// It accepted a move since the last entity range checks + /// (ServerChunkCache.move), which then check all of its pairs again. + pub moved: bool, /// The client finished loading terrain (ServerboundPlayerLoadedPacket). pub loaded: bool, // Chunks. @@ -222,6 +228,7 @@ impl Guest { fall_flying: false, flying: false, sleeping: false, + living_flags: 0, bed: None, sleep_timer: 0, sent_bed: None, @@ -233,6 +240,7 @@ impl Guest { received_moves: 0, known_moves: 0, position_this_tick: false, + moved: false, loaded: false, center: None, sent_chunks: Default::default(), diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 5d593be2d..625f18eff 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -12,6 +12,7 @@ use super::{ guest::{Guest, SentEffect, stack_to_network}, }; use crate::{ + chunk::Chunk, collisions::SceneCollisions, effects::{EffectInstance, PlayerEffects}, items::ItemStack, @@ -80,6 +81,10 @@ pub struct HostState { pub sprinting: bool, pub equipment: [Option<ItemStack>; 6], pub health: f32, + /// The host player's client-syncable attribute instances. + pub attributes: Vec<play::AttributeSnapshot>, + /// `LivingEntity.DATA_LIVING_ENTITY_FLAGS` (the item in use). + pub living_flags: i8, } /// Everything the hub needs from the game for one tick. @@ -132,6 +137,9 @@ pub struct Hub { /// The `player_movement_check` and `elytra_movement_check` game rules, /// set by the game before each tick. pub movement_checks: (bool, bool), + /// An integrated server's owner (`MinecraftServer.isSingleplayerOwner`), + /// whose moves are never checked. + pub singleplayer_owner: Option<u128>, /// Who rides what, set by the game before each tick. pub riding: super::entity::Riding, last_clock: i64, @@ -265,6 +273,7 @@ impl Hub { sync, ticks: 0, movement_checks: (true, true), + singleplayer_owner: None, riding: Default::default(), last_clock: i64::MIN, last_rate: 0.0, @@ -682,6 +691,16 @@ impl Hub { /// onEffectsRemoved, from what changed since the client was told: an /// effect that only counted down is not sent again, except at every /// 600 ticks left (`LivingEntity.tickEffects`). + /// `sync_effects` for every player at once: what a command changed + /// leaves with its feedback (ServerPlayer.onEffectAdded sends at once), + /// not after the tick's countdown. + pub fn sync_all_effects(&mut self) { + for i in 0..self.guests.len() { + if self.guests[i].placed { + self.sync_effects(i); + } + } + } fn sync_effects(&mut self, i: usize) { let g = &self.guests[i]; if g.effects.list.is_empty() && g.sent_effects.is_empty() { @@ -994,6 +1013,12 @@ impl Hub { } } if !self.guests.iter().any(|g| self.here(g)) { + // ServerTickRateManager broadcasts a change to the players there + // are; one who joins later is sent the state as it is then + // (`updateJoiningPlayer`). + if !self.guests.iter().any(|g| g.placed) { + self.ticking = (ctx.tick_rate, ctx.tick_frozen); + } if !self .guests .iter() @@ -1011,11 +1036,7 @@ impl Hub { ctx.world.light_log = Some(Default::default()); } self.sync_world(ctx); - for i in 0..self.guests.len() { - if self.here(&self.guests[i]) { - self.update_chunks(i, ctx); - } - } + crate::spans::time("lan_chunks", || self.update_chunks(ctx)); self.broadcast_light_changes(ctx.world); self.broadcast_block_changes(ctx.world); // ServerGamePacketListenerImpl.tick: the actions handled since the last tick are @@ -1154,86 +1175,140 @@ impl Hub { // ---- chunks -------------------------------------------------------- - fn update_chunks(&mut self, i: usize, ctx: &TickCtx) { + /// Every player's chunks here: their views, then the next batch of each + /// (PlayerChunkSender.sendNextChunks). The batches are chosen first, the + /// columns in them encoded once each, their new sections on the warm-up + /// threads too (`ChunkEncoder::warm`), then sent: nothing changes the + /// level in between, and each player's packets keep their order. + fn update_chunks(&mut self, ctx: &TickCtx) { + let world = &*ctx.world; + let mut batches = Vec::new(); + for i in 0..self.guests.len() { + if self.here(&self.guests[i]) { + self.update_view(i); + if let Some(batch) = self.next_batch(i, world) { + batches.push((i, batch)); + } + } + } + if batches.is_empty() { + return; + } + // Each column once, however many players it goes to, with the + // number of batches that take it. + let (mut columns, mut uses): (Vec<&Chunk>, Vec<usize>) = Default::default(); + let mut index = crate::fast_hash::FxHashMap::default(); + let batches: Vec<(usize, Vec<usize>, Vec<usize>)> = batches + .into_iter() + .map(|(i, batch)| { + let (taken, bodies) = batch + .into_iter() + .map(|(idx, chunk)| { + let j = *index.entry((chunk.x, chunk.z)).or_insert_with(|| { + columns.push(chunk); + uses.push(0); + columns.len() - 1 + }); + uses[j] += 1; + (idx, j) + }) + .unzip(); + (i, taken, bodies) + }) + .collect(); + self.encoder.warm(&columns); + let mut bodies: Vec<Vec<u8>> = columns + .iter() + .map(|c| self.encoder.body_in(c, world)) + .collect(); + for (i, taken, batch) in batches { + let g = &mut self.guests[i]; + let size = batch.len(); + g.batch_quota -= size as f32; + g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); + g.sender.send_many(batch.into_iter().map(|j| { + uses[j] -= 1; + if uses[j] == 0 { + std::mem::take(&mut bodies[j]) + } else { + bodies[j].clone() + } + })); + g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { + size: size as i32, + })); + g.unacknowledged += 1; + for idx in taken.into_iter().rev() { + let key = g.chunk_queue.remove(idx); + g.sent_chunks.insert(key); + } + } + } + + /// ChunkMap.move's view change: the new centre, the chunks that left + /// the view forgotten and the ones that entered it queued, closest first. + fn update_view(&mut self, i: usize) { let (cx, cz) = self.guests[i].chunk(); let r = self.guests[i].view_distance; let g = &mut self.guests[i]; - if g.center != Some((cx, cz)) { - g.center = Some((cx, cz)); - if g.center_sent.take() != Some((cx, cz)) { - g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { - x: cx, - z: cz, - })); - } - // Chunks that left the view. - let forget: Vec<_> = g - .sent_chunks - .iter() - .copied() - .filter(|&(x, z)| !tracked(cx, cz, r, x, z)) - .collect(); - for (x, z) in forget { - g.sent_chunks.remove(&(x, z)); - g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); - } - g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); - for dz in -r - 2..=r + 2 { - for dx in -r - 2..=r + 2 { - let key = (cx + dx, cz + dz); - if tracked(cx, cz, r, key.0, key.1) - && !g.sent_chunks.contains(&key) - && !g.chunk_queue.contains(&key) - { - g.chunk_queue.push(key); - } + if g.center == Some((cx, cz)) { + return; + } + g.center = Some((cx, cz)); + if g.center_sent.take() != Some((cx, cz)) { + g.send(&C::SetChunkCacheCenter(play::SetChunkCacheCenter { + x: cx, + z: cz, + })); + } + // Chunks that left the view. + let forget: Vec<_> = g + .sent_chunks + .iter() + .copied() + .filter(|&(x, z)| !tracked(cx, cz, r, x, z)) + .collect(); + for (x, z) in forget { + g.sent_chunks.remove(&(x, z)); + g.send(&C::ForgetLevelChunk(play::ForgetLevelChunk { pos: [x, z] })); + } + g.chunk_queue.retain(|&(x, z)| tracked(cx, cz, r, x, z)); + for dz in -r - 2..=r + 2 { + for dx in -r - 2..=r + 2 { + let key = (cx + dx, cz + dz); + if tracked(cx, cz, r, key.0, key.1) + && !g.sent_chunks.contains(&key) + && !g.chunk_queue.contains(&key) + { + g.chunk_queue.push(key); } } - g.chunk_queue - .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); } - // PlayerChunkSender.sendNextChunks: ready chunks, closest first, in - // batches the client's acknowledgements pace. + g.chunk_queue + .sort_by_key(|&(x, z)| i64::from(x - cx).pow(2) + i64::from(z - cz).pow(2)); + } + + /// PlayerChunkSender.sendNextChunks' choice: ready chunks, closest first, + /// as many as the batch quota the client's acknowledgements pace allows, + /// with their places in the queue. + fn next_batch<'w>(&mut self, i: usize, world: &'w World) -> Option<Vec<(usize, &'w Chunk)>> { + let g = &mut self.guests[i]; if self.ticks <= g.placed_at + 1 || g.unacknowledged >= g.max_unacknowledged { - return; + return None; } 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; + return None; } 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() { - if packets.len() >= budget { - break; - } - let Some(chunk) = ctx.world.chunks.get(key) else { - continue; - }; - if !chunk.lit { - continue; - } - packets.push(self.encoder.body_in(chunk, ctx.world)); - taken.push(idx); - } - if packets.is_empty() { - return; - } - let size = packets.len(); - g.batch_quota -= size as f32; - g.send(&C::ChunkBatchStart(horizon_protocol::packets::Empty)); - for body in packets { - g.sender.send(body); - } - g.send(&C::ChunkBatchFinished(play::ChunkBatchFinished { - size: size as i32, - })); - g.unacknowledged += 1; - for idx in taken.into_iter().rev() { - let key = g.chunk_queue.remove(idx); - g.sent_chunks.insert(key); - } + let batch: Vec<_> = g + .chunk_queue + .iter() + .enumerate() + .filter_map(|(idx, key)| Some((idx, &**world.chunks.get(key).filter(|c| c.lit)?))) + .take(budget) + .collect(); + (!batch.is_empty()).then_some(batch) } /// Resend a chunk to everyone who has it (a block entity changed, relight). @@ -1375,9 +1450,11 @@ impl Hub { rot: (f32, f32, f32), on_ground: bool, flags: (bool, bool, bool, bool), + living_flags: i8, skin: u8, health: f32, equipment: Vec<(u8, Option<horizon_protocol::item::Stack>)>, + attributes: Vec<play::AttributeSnapshot>, ) -> EntityState { let (sneaking, sprinting, gliding, sleeping) = flags; let mut shared = 0i8; @@ -1406,6 +1483,9 @@ impl Hub { if pose != 0 { meta.push((6, serializer::POSE, Value::Id(pose))); } + // Always there: the trackers send the entries that changed, and an + // item no longer in use is a change back to 0. + meta.push((8, serializer::BYTE, Value::Byte(living_flags))); if (health - 1.0).abs() > f32::EPSILON && health != 20.0 { meta.push((9, serializer::FLOAT, Value::Float(health))); } @@ -1425,6 +1505,7 @@ impl Hub { data: 0, meta, equipment, + attributes, precise: false, } } @@ -1469,9 +1550,11 @@ impl Hub { (h.yaw, h.pitch, h.head_yaw), h.on_ground, (h.sneaking, h.sprinting, false, false), + h.living_flags, 0x7F, h.health, equipment, + h.attributes.clone(), )); } let placed: Vec<usize> = (0..self.guests.len()) @@ -1498,9 +1581,14 @@ impl Hub { (g.yaw, g.pitch, g.head_yaw), g.on_ground, (g.sneaking, g.sprinting, g.fall_flying, g.sleeping), + g.living_flags, g.info.model_customisation, g.health, equipment, + g.motion + .as_ref() + .map(|m| super::attributes::syncable(&m.attributes)) + .unwrap_or_default(), ) }) .collect(); @@ -1522,6 +1610,7 @@ impl Hub { .zip(outs.iter_mut()) .map(|(g, out)| Viewer { entity_id: g.entity_id, + moved: std::mem::take(&mut g.moved), position: g.position, view_distance: g.view_distance, chunks: &g.sent_chunks, @@ -1611,6 +1700,19 @@ impl Hub { self.flush_advancements(i, true); } } + // ServerEntity.sendDirtyEntityData: the player's changed attribute + // instances go to the player too (its trackers get them from + // track_entities). + let g = &mut self.guests[i]; + if let Some(m) = g.motion.as_mut() { + let values = super::attributes::take_dirty(&mut m.attributes); + if !values.is_empty() { + g.send(&C::UpdateAttributes(play::UpdateAttributes { + id: g.entity_id, + values, + })); + } + } // 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]; @@ -1893,6 +1995,7 @@ impl Hub { ) { let (frozen, (check, elytra_check)) = (self.ticking.1, self.movement_checks); let g = &mut self.guests[i]; + let owner = self.singleplayer_owner == Some(g.uuid); let to = [ to[0].clamp(-3.0E7, 3.0E7), to[1].clamp(-2.0E7, 2.0E7), @@ -1916,9 +2019,10 @@ impl Hub { 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) { + // shouldCheckPlayerMovement (never the single-player owner). + // The server holds no velocity for a guest (getDeltaMovement), + // so nothing is expected. + if !owner && 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!( @@ -1948,6 +2052,8 @@ impl Hub { let g = &mut self.guests[i]; g.previous_position = g.position; g.position = to; + // ServerChunkCache.move: its pairs are checked again. + g.moved = true; 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; @@ -2106,6 +2212,18 @@ impl Hub { .map(str::to_owned) } + /// ServerLevel.removePlayerImmediately, then addRespawnedPlayer: the other players + /// lose the dead player's entity (ServerEntity.removePairing) and are sent the + /// respawned one as a new entity at the next tick. Their clients would otherwise keep + /// the dead body, lying down, wherever the player goes. + pub fn respawned(&mut self, id: i32) { + for g in &mut self.guests { + if g.entity_id != id && g.tracker.forget(id) { + g.send(&C::RemoveEntities(play::RemoveEntities { ids: vec![id] })); + } + } + } + /// PlayerList.respawn: back to `at` with a fresh start. The vanilla client waits on its /// level loading screen from the Respawn packet until the level info's "level chunks load /// start" event and the chunk under the player, so the packets follow vanilla's order. @@ -2132,6 +2250,9 @@ impl Hub { g.tracker.clear(); g.sent_chunks.clear(); g.chunk_queue.clear(); + let id = g.entity_id; + self.respawned(id); + let g = &mut self.guests[i]; // ServerPlayer.restoreFrom: the game mode again (onUpdateAbilities). g.send(&C::PlayerAbilities(play::PlayerAbilities { flags: g.ability_flags(), diff --git a/crates/horizon-client/src/lan/mod.rs b/crates/horizon-client/src/lan/mod.rs index afe188699..c2f35bc8e 100644 --- a/crates/horizon-client/src/lan/mod.rs +++ b/crates/horizon-client/src/lan/mod.rs @@ -5,6 +5,7 @@ //! ever exchanges decoded packets with these threads through channels, so a //! world that is not open to the network pays nothing. mod advancements; +pub mod attributes; pub mod chunks; mod command_order; pub mod command_suggestions; diff --git a/crates/horizon-client/src/lan/waypoints.rs b/crates/horizon-client/src/lan/waypoints.rs index e3067871c..852cfc4fb 100644 --- a/crates/horizon-client/src/lan/waypoints.rs +++ b/crates/horizon-client/src/lan/waypoints.rs @@ -160,7 +160,7 @@ struct Tick<'a> { out: Vec<(u32, C)>, } -impl Tick<'_> { +impl<'a> Tick<'a> { fn send( &mut self, receiver: u128, @@ -172,16 +172,8 @@ impl Tick<'_> { 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, - }), - )); + self.out + .push((conn, waypoint(source, operation, icon, target))); } fn connect(&mut self, receiver: u128, source: u128, c: &Connection) { let target = match c.kind { @@ -230,11 +222,13 @@ impl Tick<'_> { let d = [0, 1, 2].map(|k| receiver.position[k] - source.position[k]); horizon_core::geometry::trig::atan2(d[0], -d[2]) as f32 } + /// The source and the receiver, if both are in the level this tick. + fn pair(&self, source: u128, receiver: u128) -> Option<(&'a Player, &'a Player)> { + Some((*self.players.get(&source)?, *self.players.get(&receiver)?)) + } /// `LivingEntity.makeWaypointConnectionWith`. - fn make(&self, source: u128, receiver: u128) -> Option<Connection> { - 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) - { + fn make(&self, (s, r): (&Player, &Player)) -> Option<Connection> { + if s.first_tick || self.fresh.contains(&s.uuid) || s.uuid == r.uuid || self.ignores(s, r) { return None; } // Waypoint.Icon.cloneAndAssignStyle: the icon's colour, else the team's. @@ -244,7 +238,7 @@ impl Tick<'_> { } let kind = if Self::really_far(s, r) { Kind::Azimuth(Self::azimuth(s, r)) - } else if !self.chunk_visible(s.chunk(), receiver) { + } else if !self.chunk_visible(s.chunk(), r.uuid) { Kind::Chunk(s.chunk()) } else { Kind::Block(s.block()) @@ -252,10 +246,8 @@ impl Tick<'_> { 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; - }; + fn broken(&self, c: &Connection, (s, r): (&Player, &Player)) -> bool { + let receiver = r.uuid; match c.kind { Kind::Block(last) => { let now = s.block(); @@ -274,10 +266,7 @@ impl Tick<'_> { } } /// `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; - }; + fn update(&mut self, c: &mut Connection, (s, r): (&Player, &Player)) { let target = match &mut c.kind { Kind::Block(last) => { let now = s.block(); @@ -304,24 +293,26 @@ impl Tick<'_> { WaypointTarget::Azimuth(now) } }; - self.send( - receiver, - source, - waypoint_operation::UPDATE, - &c.icon, - target, - ); + if let Some(conn) = r.conn { + self.out.push(( + conn, + waypoint(s.uuid, waypoint_operation::UPDATE, &c.icon, target), + )); + } } } +fn waypoint(source: u128, operation: i32, icon: &Icon, target: WaypointTarget) -> C { + C::TrackedWaypoint(TrackedWaypoint { + operation, + id: WaypointId::Uuid(source), + style: icon.style.clone(), + color: icon.color, + 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) { @@ -340,7 +331,7 @@ impl Waypoints { if receiver == source || !t.enabled { return; } - match t.make(source, receiver) { + match t.pair(source, receiver).and_then(|pair| t.make(pair)) { Some(c) => { t.connect(receiver, source, &c); self.put(receiver, source, c); @@ -352,23 +343,28 @@ impl Waypoints { } } } - /// `updateConnection`, on the connection in its place. - fn update_connection(&mut self, t: &mut Tick, receiver: u128, source: u128) { + /// The receiver's connection to the source updated in its place + /// (`updateConnection`), or made if it has none (`createConnection`). + fn update_or_create(&mut self, t: &mut Tick, receiver: u128, source: u128) { if receiver == source || !t.enabled { return; } let Some(row) = self.connections.get_mut(&receiver) else { - return; + return self.create_connection(t, receiver, source); }; let Some(i) = row.iter().position(|(s, _)| *s == source) else { - return; + return self.create_connection(t, receiver, source); }; let c = &mut row[i].1; - if !t.broken(c, source, receiver) { - t.update(c, source, receiver); + // A connection to a player who isn't in the level is broken. + let pair = t.pair(source, receiver); + if let Some(pair) = pair + && !t.broken(c, pair) + { + t.update(c, pair); return; } - match t.make(source, receiver) { + match pair.and_then(|pair| t.make(pair)) { Some(new) => { t.connect(receiver, source, &new); *c = new; @@ -379,14 +375,6 @@ impl Waypoints { } } } - /// The receiver's connection to the source updated, or made if it has none. - fn update_or_create(&mut self, t: &mut Tick, receiver: u128, source: u128) { - if self.connection(receiver, source).is_some() { - self.update_connection(t, receiver, source); - } else { - self.create_connection(t, receiver, source); - } - } /// `trackWaypoint`. fn track(&mut self, t: &mut Tick, source: u128) { if !self.waypoints.contains(&source) { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 1e2c8c331..a3b4be279 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -85,6 +85,7 @@ pub mod hud_layout; pub mod hud_overlays; pub mod hunger; pub mod input; +pub mod interaction_input; pub mod inv_sort; pub mod inventory_effects; pub mod item_data; @@ -133,6 +134,7 @@ pub mod particles; pub mod patrol; pub mod perf_overlay; pub mod pick_item; +pub mod player_sync; pub mod poi_sections; pub mod portal_sections; pub mod pose; @@ -172,6 +174,7 @@ pub mod telemetry; pub mod testgen; pub mod text; pub mod tick_chunk_membership; +pub mod ticket_levels; pub mod title; pub mod title_edition; pub mod toasts; diff --git a/crates/horizon-client/src/light.rs b/crates/horizon-client/src/light.rs index 2ef7af301..d7ea7d7fd 100644 --- a/crates/horizon-client/src/light.rs +++ b/crates/horizon-client/src/light.rs @@ -14,6 +14,7 @@ //! most 15 blocks, so the 48-wide region determines the centre exactly. //! `relight_block` applies vanilla's incremental decrease/increase passes //! directly to resident chunks after a block change. +use crate::fast_hash::FxHashMap; use crate::{ blocks::BlockFacts, chunk::{Chunk, HEIGHT, Light, MIN_Y, SECTIONS, index}, @@ -464,10 +465,8 @@ pub fn apply_lighting(chunk: &mut Chunk, lights: Vec<Light>) { } /// `apply_lighting` for a chunk lit before: writes only the sections whose -/// light changed and returns the block positions that changed. -pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>) -> Vec<(i32, i32, i32)> { - let mut changed = Vec::new(); - let (bx, bz) = (chunk.x * 16, chunk.z * 16); +/// light changed and adds the cells that changed to `changed`. +pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>, changed: &mut LightChanges) { for (sy, (section, light)) in chunk.sections.iter_mut().zip(lights).enumerate() { let old = §ion.light; if let (Light::Uniform(a), Light::Uniform(b)) = (old, &light) @@ -475,18 +474,18 @@ pub fn apply_relighting(chunk: &mut Chunk, lights: Vec<Light>) -> Vec<(i32, i32, { continue; } - let before = changed.len(); + let mut classes = 0; for i in 0..4096 { if old.get(i) != light.get(i) { - let y = MIN_Y + sy as i32 * 16 + (i >> 8) as i32; - changed.push((bx + (i & 15) as i32, y, bz + (i >> 4 & 15) as i32)); + let (x, y, z) = (i as i32 & 15, (i >> 8) as i32, (i >> 4) as i32 & 15); + classes |= 1 << LightChanges::class(x, y, z); } } - if changed.len() > before { + if classes != 0 { + changed.add((chunk.x, sy as i32, chunk.z), classes); Arc::make_mut(section).light = light; } } - changed } /// `DataLayer.get`: the nibble at index `i` (`y << 8 | z << 4 | x`), low first. @@ -607,6 +606,90 @@ impl<S: std::hash::BuildHasher> LightWorld for HashMap<(i32, i32), Arc<Chunk>, S } } type Pos = (i32, i32, i32); +/// Changed light by section, as vanilla's light engine reports it to +/// `LevelRenderer` (`setSectionDirty`) instead of cell by cell: for each +/// section (x, section index, z), a bit per class of position the changed +/// cells take in it, `3 * 3 * 3` classes for the low face, the inside and the +/// high face of each axis. Meshes sample light one block across a face, so the +/// class says which neighbouring sections a change dirties too. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct LightChanges { + sections: FxHashMap<Pos, u32>, +} +impl LightChanges { + /// A cell whose stored light changed. + #[inline] + pub fn push(&mut self, (x, y, z): Pos) { + let key = (x >> 4, (y - MIN_Y) >> 4, z >> 4); + *self.sections.entry(key).or_default() |= 1 << Self::class(x, y, z); + } + /// Cells of section `key` (x, section index, z) in the given classes. + fn add(&mut self, key: Pos, classes: u32) { + *self.sections.entry(key).or_default() |= classes; + } + /// The class of a cell in its section: per axis 0 on the low face, 1 + /// inside, 2 on the high face. + fn class(x: i32, y: i32, z: i32) -> u32 { + let axis = |v: i32| match v & 15 { + 0 => 0, + 15 => 2, + _ => 1, + }; + axis(x) + 3 * axis(y) + 9 * axis(z) + } + pub fn is_empty(&self) -> bool { + self.sections.is_empty() + } + /// The sections (x, section index, z) holding changed cells. + pub fn sections(&self) -> impl Iterator<Item = Pos> + '_ { + self.sections.keys().copied() + } + /// Every section (x, section index, z) whose cells lie within one block + /// of a changed cell, section indexes outside `0..SECTIONS` left out (a + /// section next to several changed ones comes once for each). + pub fn dirty_sections(&self, mut out: impl FnMut(Pos)) { + // Per class, the bit set of neighbour offsets (dx, dy, dz in -1..=1, + // bit (dx + 1) + 3 (dy + 1) + 9 (dz + 1)) its cells reach. + const REACH: [u32; 27] = { + let mut reach = [0; 27]; + let mut class = 0; + while class < 27 { + let axis = [class % 3, class / 3 % 3, class / 9]; + let mut offset = 0; + while offset < 27 { + let d = [offset % 3, offset / 3 % 3, offset / 9]; + // Every class reaches its own section (d = 1, offset 0); + // the low face also -1 (d = 0), the high face +1 (d = 2). + if (d[0] == 1 || d[0] == axis[0]) + && (d[1] == 1 || d[1] == axis[1]) + && (d[2] == 1 || d[2] == axis[2]) + { + reach[class] |= 1 << offset; + } + offset += 1; + } + class += 1; + } + reach + }; + for (&(x, sy, z), &classes) in &self.sections { + let mut offsets = 0; + let mut rest = classes; + while rest != 0 { + offsets |= REACH[rest.trailing_zeros() as usize]; + rest &= rest - 1; + } + while offsets != 0 { + let o = offsets.trailing_zeros() as i32; + offsets &= offsets - 1; + let s = sy + o / 3 % 3 - 1; + if (0..SECTIONS as i32).contains(&s) { + out((x + o % 3 - 1, s, z + o / 9 - 1)); + } + } + } + } +} fn level(world: &impl LightWorld, sky: bool, p: Pos) -> Option<u8> { world .light(p.0, p.1, p.2) @@ -645,8 +728,8 @@ pub fn lowest_sky_source(world: &impl LightWorld, tables: &LightTables, x: i32, /// Vanilla's `checkBlock` + `runLightUpdates` for changed positions on /// resident, lit chunks: clear the light that may have come through or from /// the old states (decrease pass), then re-seed sources and propagate back in -/// from the brighter boundary (increase pass). Returns every position whose -/// stored light changed, for remeshing. `force` clears around each position +/// from the brighter boundary (increase pass). Adds every position whose +/// stored light changed to `changed`, for remeshing. `force` clears around each position /// as if it had been fully lit, for light computed from outdated blocks. pub fn relight( world: &mut impl LightWorld, @@ -654,16 +737,9 @@ pub fn relight( sky_light: bool, positions: &[Pos], force: bool, -) -> Vec<Pos> { - let mut changed = Vec::new(); - relight_layer( - world, - tables, - false, - positions.to_vec(), - force, - &mut changed, - ); + changed: &mut LightChanges, +) { + relight_layer(world, tables, false, positions.to_vec(), force, changed); if sky_light { let mut seeds = positions.to_vec(); let mut columns: HashMap<(i32, i32), i32> = HashMap::new(); @@ -686,11 +762,8 @@ pub fn relight( y -= 1; } } - relight_layer(world, tables, true, seeds, force, &mut changed); + relight_layer(world, tables, true, seeds, force, changed); } - changed.sort_unstable(); - changed.dedup(); - changed } fn relight_layer( world: &mut impl LightWorld, @@ -698,7 +771,7 @@ fn relight_layer( sky: bool, seeds: Vec<Pos>, force: bool, - changed: &mut Vec<Pos>, + changed: &mut LightChanges, ) { let mut decrease: VecDeque<(Pos, u8)> = VecDeque::new(); let mut cleared: Vec<Pos> = Vec::new(); @@ -894,7 +967,14 @@ mod tests { ]; for ((x, y, z), state) in edits { Arc::make_mut(w.get_mut(&(0, 0)).unwrap()).set(x, y, z, state); - relight(&mut w, &tables(), true, &[(x, y, z)], false); + relight( + &mut w, + &tables(), + true, + &[(x, y, z)], + false, + &mut LightChanges::default(), + ); } let region: [[Option<&Chunk>; 3]; 3] = std::array::from_fn(|dz| { std::array::from_fn(|dx| w.get(&(dx as i32 - 1, dz as i32 - 1)).map(|c| &**c)) @@ -940,7 +1020,16 @@ mod tests { assert_eq!(edited_snapshot.sections[0].light(index(8, MIN_Y, 8)), 0xF0); let mut world = HashMap::from([((0, 0), Arc::new(current))]); // Streaming replays edits made after the job snapshot with force=true. - relight(&mut world, &tables(), true, &[(8, MIN_Y, 8)], true); + let mut changed = LightChanges::default(); + relight( + &mut world, + &tables(), + true, + &[(8, MIN_Y, 8)], + true, + &mut changed, + ); + assert!(!changed.is_empty()); let region = [[None; 3], [None, Some(&*world[&(0, 0)]), None], [None; 3]]; let fresh = light_chunk(®ion, &tables(), true); for (section, light) in world[&(0, 0)].sections.iter().zip(fresh) { @@ -963,7 +1052,9 @@ mod tests { let sections: Vec<_> = chunk.sections.iter().map(Arc::as_ptr).collect(); // The same light again: nothing changes and no section is copied. let light = lit(&chunk); - assert!(apply_relighting(&mut chunk, light).is_empty()); + let mut changed = LightChanges::default(); + apply_relighting(&mut chunk, light, &mut changed); + assert!(changed.is_empty()); assert_eq!( sections, chunk.sections.iter().map(Arc::as_ptr).collect::<Vec<_>>() @@ -971,8 +1062,8 @@ mod tests { let before = chunk.clone(); chunk.set(3, MIN_Y + 20, 5, STONE); let light = lit(&chunk); - let changed = apply_relighting(&mut chunk, light); - let mut expected = Vec::new(); + apply_relighting(&mut chunk, light, &mut changed); + let mut expected = LightChanges::default(); for (sy, (old, new)) in before.sections.iter().zip(&chunk.sections).enumerate() { for i in 0..4096 { if old.light(i) != new.light(i) { @@ -992,6 +1083,57 @@ mod tests { assert!(copied <= 3, "{copied} sections copied"); } + #[test] + fn changes_dirty_the_sections_within_a_block_of_each_cell() { + // Cells inside sections, on each face and corner, at the bottom and + // top of the world, on negative coordinates. + let mut cells = Vec::new(); + for x in [-17, -16, -1, 0, 7, 15, 16, 31] { + for y in [ + MIN_Y, + MIN_Y + 15, + MIN_Y + 16, + 70, + 79, + 80, + MIN_Y + HEIGHT - 1, + ] { + for z in [-33, -32, 5, 15] { + cells.push((x, y, z)); + } + } + } + for n in [1, 2, cells.len()] { + for start in 0..cells.len().min(8) { + let some: Vec<Pos> = cells.iter().copied().cycle().skip(start).take(n).collect(); + let mut changes = LightChanges::default(); + some.iter().for_each(|&c| changes.push(c)); + let mut dirty = std::collections::BTreeSet::new(); + changes.dirty_sections(|s| { + dirty.insert(s); + }); + let mut expected = std::collections::BTreeSet::new(); + for &(x, y, z) in &some { + for (dx, dy, dz) in (-1..=1) + .flat_map(|a| (-1..=1).flat_map(move |b| (-1..=1).map(move |c| (a, b, c)))) + { + let s = (y + dy - MIN_Y) >> 4; + if (0..SECTIONS as i32).contains(&s) { + expected.insert(((x + dx) >> 4, s, (z + dz) >> 4)); + } + } + } + assert_eq!(dirty, expected, "{some:?}"); + let sections: std::collections::BTreeSet<_> = changes.sections().collect(); + let own: std::collections::BTreeSet<_> = some + .iter() + .map(|&(x, y, z)| (x >> 4, (y - MIN_Y) >> 4, z >> 4)) + .collect(); + assert_eq!(sections, own); + } + } + } + #[test] fn stored_layers_fill_the_column_as_vanilla_reads_them() { // Section 10's sky layer is 7 on its bottom row and 3 above; no diff --git a/crates/horizon-client/src/logging.rs b/crates/horizon-client/src/logging.rs index c434c8efb..cb7638f26 100644 --- a/crates/horizon-client/src/logging.rs +++ b/crates/horizon-client/src/logging.rs @@ -330,6 +330,14 @@ pub fn write_only(level: log::Level, message: &str) { } } +/// Writes `message` to the log file only, under the thread vanilla names for it (`Server thread` for +/// a login refused on a connection's own thread), as the console line beside it shows. +pub fn write_as(thread: &str, level: log::Level, message: &str) { + if let Some(logger) = LOGGER.get() { + logger.write(thread, level, message); + } +} + /// The last lines written, oldest first (for crash reports). pub fn recent_lines() -> Vec<String> { LOGGER.get().map_or_else(Vec::new, |l| { diff --git a/crates/horizon-client/src/mesher.rs b/crates/horizon-client/src/mesher.rs index c3990f598..2a4efd592 100644 --- a/crates/horizon-client/src/mesher.rs +++ b/crates/horizon-client/src/mesher.rs @@ -7,7 +7,7 @@ mod facing; mod fluid; mod lighting; use crate::{ - assets::Assets, + assets::{Assets, RenderAssets}, biome::Biomes, blocks::{BlockFacts, RenderShape}, chunk::{Chunk, MIN_Y}, @@ -39,16 +39,22 @@ pub struct Vertex { /// RGBA8_SNORM face normal; w = -127 for two-sided lighting, 0 to keep baked/unlit colour. pub normal: [i8; 4], } -/// A section vertex, 28 bytes like vanilla's `DefaultVertexFormat.BLOCK` -/// (position, colour, UV0, UV2) with the sprite's array layer beside the -/// light. Terrain has no normal: `ModelBlockRenderer` bakes the face shade -/// into the colour and `terrain.vsh` only multiplies it by the lightmap. +/// A section vertex: vanilla's `DefaultVertexFormat.BLOCK` (position, colour, +/// UV0, UV2) with the sprite's array layer beside the light, in 24 bytes +/// rather than vanilla's 28: the UV is fixed point, which holds model UVs +/// (multiples of 1/16 and their halves) exactly. The position stays a float: +/// fixed point would move the edges of offset plants and rotated elements by +/// a fraction of a pixel. Terrain has no normal: `ModelBlockRenderer` bakes +/// the face shade into the colour and `terrain.vsh` only multiplies it by the +/// lightmap. #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct TerrainVertex { /// Section-relative position. pub pos: [f32; 3], - pub uv: [f32; 2], + /// UV within the sprite, `UV_STEPS` per unit (`TerrainVertex::new`, + /// `terrain.wgsl`'s `terrain_uv`). + pub(crate) uv: [u16; 2], /// Sprite array layer, with `OPAQUE_LAYER` for opaque leaves. pub layer: u16, /// Smooth light, 16x fixed point: sky in the low byte, block in the high one. @@ -56,6 +62,44 @@ pub struct TerrainVertex { /// RGBA8: tint multiplied by directional shade and ambient occlusion. pub color: u32, } +/// Fixed-point steps per unit of `TerrainVertex` UVs, which span `[0, 2)`. +pub const UV_STEPS: f32 = 32768.0; +impl TerrainVertex { + pub fn new(pos: [f32; 3], uv: [f32; 2], layer: u16, color: u32, light: u16) -> Self { + Self { + pos, + uv: uv.map(|v| (v * UV_STEPS).round().clamp(0.0, f32::from(u16::MAX)) as u16), + layer, + light, + color, + } + } + /// The UV the GPU samples. + pub fn uv(&self) -> [f32; 2] { + self.uv.map(|v| f32::from(v) / UV_STEPS) + } +} +#[cfg(test)] +mod vertex_tests { + use super::TerrainVertex; + #[test] + fn model_uvs_pack_exactly() { + for i in 0..=32 { + let u = i as f32 / 32.0; + let v = TerrainVertex::new([0.0; 3], [u, 1.0 - u], 0, 0, 0); + assert_eq!(v.uv(), [u, 1.0 - u]); + } + } + #[test] + fn other_uvs_round_within_a_step() { + // A flowing fluid's rotated UV. + let uv = [0.5 + 0.25 * 0.3f32.sin(), 0.5 - 0.25 * 0.3f32.cos()]; + let packed = TerrainVertex::new([0.0; 3], uv, 0, 0, 0).uv(); + for (a, b) in packed.iter().zip(uv) { + assert!((a - b).abs() <= 0.5 / 32768.0, "{a} {b}"); + } + } +} pub struct SectionMesh { pub solid: Vec<TerrainVertex>, /// `solid`'s quads by the side they face (`facing`). @@ -258,18 +302,19 @@ fn redstone_color(power: u8) -> u32 { impl MeshTables { pub fn new( assets: &Assets, + render: &RenderAssets, facts: &BlockFacts, visibility: FaceVisibility, ) -> crate::Result<Self> { // Terrain vertices keep the sprite layer below `OPAQUE_LAYER`. - let layers = assets.sprite_layers.values().max().map_or(0, |l| l + 1); + let layers = render.sprite_layers.values().max().map_or(0, |l| l + 1); if layers > u32::from(OPAQUE_LAYER) { return Err( format!("{layers} block sprites, terrain vertices index {OPAQUE_LAYER}").into(), ); } let layer = |name: &str| -> crate::Result<u16> { - assets + render .sprite_layers .get(name) .map(|&l| l as u16) @@ -594,6 +639,7 @@ pub struct Mesher<'a> { /// CardinalLighting.NETHER: brighter up/down faces. pub nether_shading: bool, pub assets: &'a Assets, + pub render: &'a RenderAssets, pub tables: &'a MeshTables, pub biomes: &'a Biomes, pub visibility: FaceVisibility, @@ -663,7 +709,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), world) + let Ok(models) = self.render.model_catalog.collect(BlockStateId(id), world) else { continue; }; @@ -786,18 +832,18 @@ impl Mesher<'_> { None => [g; 3], }; let p = q.positions[i]; - target.push(TerrainVertex { - pos: [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], - uv: q.uv[i], + target.push(TerrainVertex::new( + [p[0] + origin[0], p[1] + origin[1], p[2] + origin[2]], + q.uv[i], // Opaque leaves (forceOpaque) draw in the solid layer: no alpha cutout. - layer: if !self.cutout_leaves && state.leaves { + if !self.cutout_leaves && state.leaves { face.layer as u16 | OPAQUE_LAYER } else { face.layer as u16 }, - color: pack_rgb(rgb), - light: pack_coords(lighting::with_emission(coords[i], q.light_emission)), - }); + pack_rgb(rgb), + pack_coords(lighting::with_emission(coords[i], q.light_emission)), + )); } } } diff --git a/crates/horizon-client/src/mesher/facing.rs b/crates/horizon-client/src/mesher/facing.rs index 2a7f0ba61..e82ad6a06 100644 --- a/crates/horizon-client/src/mesher/facing.rs +++ b/crates/horizon-client/src/mesher/facing.rs @@ -175,13 +175,7 @@ mod tests { use super::*; fn vertex(pos: [f32; 3], layer: u16) -> TerrainVertex { - TerrainVertex { - pos, - uv: [0.0; 2], - layer, - light: 0, - color: 0, - } + TerrainVertex::new(pos, [0.0; 2], layer, 0, 0) } /// A unit quad in the plane `axis = plane`, wound to face `sign`, tagged /// with `layer` so tests can follow it. diff --git a/crates/horizon-client/src/mesher/fluid.rs b/crates/horizon-client/src/mesher/fluid.rs index c29f2b92c..6e42685ba 100644 --- a/crates/horizon-client/src/mesher/fluid.rs +++ b/crates/horizon-client/src/mesher/fluid.rs @@ -306,13 +306,7 @@ pub(super) fn tesselate( }; let mut quad = |v: [([f32; 3], [f32; 2]); 4], layer: u16, color: u32, light: u16, back: bool| { - let vertex = |(pos, uv): ([f32; 3], [f32; 2])| TerrainVertex { - pos, - uv, - layer, - color, - light, - }; + let vertex = |(pos, uv)| TerrainVertex::new(pos, uv, layer, color, light); target.extend(v.map(vertex)); if back { target.extend([v[0], v[3], v[2], v[1]].map(vertex)); diff --git a/crates/horizon-client/src/mesher/leaf_culling_tests.rs b/crates/horizon-client/src/mesher/leaf_culling_tests.rs index 9369a1ba2..679b19090 100644 --- a/crates/horizon-client/src/mesher/leaf_culling_tests.rs +++ b/crates/horizon-client/src/mesher/leaf_culling_tests.rs @@ -9,9 +9,10 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = crate::models::load_visibility(&root, assets.registry).unwrap(); - let tables = MeshTables::new(&assets, &facts, visibility.clone()).unwrap(); + let tables = MeshTables::new(&assets, &render, &facts, visibility.clone()).unwrap(); let biomes = Biomes::load(&root).unwrap(); let state = |name| assets.registry.default_state(name).unwrap().0; let oak = state("minecraft:oak_leaves"); @@ -31,6 +32,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { Mesher { nether_shading: false, assets: &assets, + render: &render, tables: &tables, biomes: &biomes, visibility: visibility.clone(), @@ -49,7 +51,7 @@ fn leaf_culling_removes_only_internal_leaf_and_root_faces() { // preserving every other quad and its full vertex attributes. let without_face = |at: [i32; 3], id, direction| { let vertices = mesh(&[(at, id)], false, true); - let models = assets + let models = render .model_catalog .collect(BlockStateId(id), BlockPos::new(at[0], at[1], at[2])) .unwrap(); diff --git a/crates/horizon-client/src/mobs.rs b/crates/horizon-client/src/mobs.rs index 3fe743fab..c8155984c 100644 --- a/crates/horizon-client/src/mobs.rs +++ b/crates/horizon-client/src/mobs.rs @@ -1412,6 +1412,9 @@ pub struct MobWorld<'a> { pub collision: &'a BlockCollisionRegistry<'a>, pub data: &'a MobData, pub player: Option<PlayerView>, + /// `getNearestPlayer(mob, -1)`: where the nearest non-spectator of every + /// player in the level stands, alive or not (the despawn distance). + pub nearest_player: Option<Vec3>, pub others: &'a [Seen], /// `others` by position, when the caller keeps one (the mob ticks). pub others_grid: Option<&'a seen_grid::SeenGrid>, diff --git a/crates/horizon-client/src/mobs/ai.rs b/crates/horizon-client/src/mobs/ai.rs index f74a3c7d1..34276ddda 100644 --- a/crates/horizon-client/src/mobs/ai.rs +++ b/crates/horizon-client/src/mobs/ai.rs @@ -429,7 +429,7 @@ pub fn tick( true } /// LivingEntity.updateSwingTime (6-tick swing duration). -fn tick_swing(m: &mut Mob) { +pub fn tick_swing(m: &mut Mob) { if m.ai.swinging { m.ai.swing_time += 1; if m.ai.swing_time >= 6 { @@ -1018,22 +1018,21 @@ pub fn despawn_check(m: &mut Mob, w: &MobWorld) -> bool { /// Mob.checkDespawn, before the tick (players are the only despawn /// reference). Returns false when the mob is discarded. fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { - let Some(p) = &w.player else { return true }; - let d = m.distance_sqr(p.position); + let Some(p) = w.nearest_player else { + return true; + }; + let d = m.distance_sqr(p); // requiresCustomPersistence: raiders in a raid, a tame nautilus, a sulfur // cube holding a block or let out of a bucket. let persistent = m.persistent || super::nautilus::is_nautilus(m.species()) && m.extra.tame || m.species() == Species::SulfurCube && (super::sulfur_cube::has_body(m) || m.extra.scratch[3] != 0); - // removeWhenFarAway: animals, wardens, allays, patrols and raiders, - // zombie villagers being cured and ridden mobs stay; the wither's - // checkDespawn never removes it for distance. + // removeWhenFarAway: animals, villagers, golems, patrols and raiders, + // zombie villagers being cured and ridden mobs stay. let creature = m.kind.category == "creature"; - let removable = !(matches!( - m.species(), - Species::Warden | Species::Allay | Species::Wither - ) || creature && m.kind.flags.animal && !m.extra.jockey + let removable = !(never_removed_when_far(m.species()) + || creature && m.kind.flags.animal && !m.extra.jockey || super::raider::keeps_alive(m, d) || super::zombie_villager::keeps_alive(m) || super::riders::keeps_alive(m)); @@ -1059,6 +1058,24 @@ fn check_despawn(m: &mut Mob, w: &MobWorld) -> bool { } true } +/// The types whose `removeWhenFarAway` is always false (`Villager`, +/// `WanderingTrader`, `AbstractGolem`: iron, snow and copper golems and +/// shulkers; `Allay`, `Warden`), and the wither, whose `checkDespawn` never +/// removes it for distance. +fn never_removed_when_far(s: Species) -> bool { + matches!( + s, + Species::Villager + | Species::WanderingTrader + | Species::IronGolem + | Species::SnowGolem + | Species::CopperGolem + | Species::Shulker + | Species::Allay + | Species::Warden + | Species::Wither + ) +} /// Movement speed bonus multiplier (baby zombies are 50% faster, etc.). pub fn speed_bonus(m: &Mob) -> f64 { match m.species() { @@ -1579,3 +1596,25 @@ mod bucket_axolotl_tests { assert_eq!(family(Species::Axolotl), Family::Aquatic); } } +#[cfg(test)] +mod despawn_tests { + use super::*; + /// Village villagers are placed without PersistenceRequired (unlike the + /// village's iron golem), so they must never despawn for distance. + #[test] + fn villagers_traders_and_golems_never_despawn_for_distance() { + for s in [ + Species::Villager, + Species::WanderingTrader, + Species::IronGolem, + Species::SnowGolem, + Species::CopperGolem, + Species::Shulker, + ] { + assert!(never_removed_when_far(s), "{s:?}"); + } + for s in [Species::Zombie, Species::ZombieVillager, Species::Pillager] { + assert!(!never_removed_when_far(s), "{s:?}"); + } + } +} diff --git a/crates/horizon-client/src/mobs/cube.rs b/crates/horizon-client/src/mobs/cube.rs index 3986ffb93..ea8a05392 100644 --- a/crates/horizon-client/src/mobs/cube.rs +++ b/crates/horizon-client/src/mobs/cube.rs @@ -47,14 +47,24 @@ pub fn register(m: &mut Mob) { m.extra.vector[0] = f64::from(180.0 * m.yaw / std::f32::consts::PI); set_size(m, 1); } -/// AbstractCubeMob.setSize: health size^2, speed 0.2 + 0.1 * size, damage size. +/// AbstractCubeMob.setSize(size, true): the max health (size^2), movement +/// speed (0.2 + 0.1 * size, in floats) and attack damage (size) bases, a +/// magma cube's armor (size * 3), then the health back to the max. pub fn set_size(m: &mut Mob, size: i32) { + use super::finalize::{Attr, set_base}; let size = size.clamp(1, 127); m.extra.size = size; - m.attrs.max_health = (size * size) as f32; - m.attrs.speed = 0.2 + 0.1 * f64::from(size); - m.attrs.attack_damage = size as f32; - m.health = m.attrs.max_health; + set_base(m, Attr::MaxHealth, f64::from(size * size)); + set_base( + m, + Attr::MovementSpeed, + f64::from(0.2f32 + 0.1f32 * size as f32), + ); + set_base(m, Attr::AttackDamage, f64::from(size)); + if m.species() == super::Species::MagmaCube { + set_base(m, Attr::Armor, f64::from(size * 3)); + } + m.health = super::finalize::max_health(m); } /// AbstractCubeMob.setSpawnSize: 1, 2 or 4 (normal difficulty special multiplier 0). pub fn finalize(m: &mut Mob) { diff --git a/crates/horizon-client/src/mobs/finalize.rs b/crates/horizon-client/src/mobs/finalize.rs index a3db1ee52..ae6a864cc 100644 --- a/crates/horizon-client/src/mobs/finalize.rs +++ b/crates/horizon-client/src/mobs/finalize.rs @@ -483,7 +483,7 @@ pub fn base_value(m: &Mob, a: Attr) -> f64 { .unwrap_or(if a == Attr::BurningTime { 1.0 } else { 0.0 }) } /// The transient modifiers of the mob's state (`SPEED_MODIFIER_BABY`). -fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { +pub fn transient(m: &Mob, a: Attr) -> Option<(f64, Op)> { if a != Attr::MovementSpeed || !m.is_baby() { return None; } @@ -1961,19 +1961,7 @@ fn sulfur_size(m: &mut Mob, size: i32) { m.health = max_health(m); } fn cube_size(m: &mut Mob, size: i32) { - let size = size.clamp(1, 127); - m.extra.size = size; - set_base(m, Attr::MaxHealth, f64::from(size * size)); - set_base( - m, - Attr::MovementSpeed, - f64::from(0.2f32 + 0.1f32 * size as f32), - ); - set_base(m, Attr::AttackDamage, f64::from(size)); - if m.species() == Species::MagmaCube { - set_base(m, Attr::Armor, f64::from(size * 3)); - } - m.health = max_health(m); + super::cube::set_size(m, size); } /// The index the game keeps for a variant registry entry. pub fn variant_index(s: Species, name: &str) -> u8 { diff --git a/crates/horizon-client/src/mobs/spawn_rules.rs b/crates/horizon-client/src/mobs/spawn_rules.rs index 22f9206af..1cdca41b9 100644 --- a/crates/horizon-client/src/mobs/spawn_rules.rs +++ b/crates/horizon-client/src/mobs/spawn_rules.rs @@ -589,11 +589,7 @@ impl SpawnLevel for super::MobWorld<'_> { self.sea_level } fn world_surface(&self, x: i32, z: i32) -> i32 { - let top = crate::chunk::MIN_Y + crate::chunk::HEIGHT; - (crate::chunk::MIN_Y..top) - .rev() - .find(|&y| !self.facts.is_air(self.world.block(x, y, z))) - .map_or(crate::chunk::MIN_Y, |y| y + 1) + self.world.world_surface(x, z, |id| self.facts.is_air(id)) } fn peaceful(&self) -> bool { self.difficulty.effective == 0.0 diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index 1cd155297..c396c3333 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -697,6 +697,78 @@ fn worldgen_entry(file: &str) -> Option<(&'static str, String)> { Some((bundle, format!("{ns}:{}", path.strip_suffix(".json")?))) } +/// The key of a mod's structure set or template pool file that adds its +/// entries to other sets or pools (vanilla's, another mod's) instead of +/// being one of its own. Vanilla data never has it. +const ADD_TO: &str = "horizon:add_to"; +/// The bundles a mod may add to, and the list each entry goes into. +const ADDABLE: [(&str, &str); 2] = [ + ("worldgen/structure_sets.json", "structures"), + ("worldgen/template_pools.json", "elements"), +]; + +/// A mod file's additions (`horizon:add_to`): its entries appended to the +/// list of each set or pool it names, as lithostitched's +/// `add_structure_set_entries` and `add_template_pool_elements` do for +/// NeoForge and Fabric packs. +struct Addition { + targets: Vec<String>, + list: &'static str, + entries: Vec<J>, +} +impl Addition { + /// What a mod file of `bundle` adds, if it is an addition file. + fn read(bundle: &str, text: &str) -> Result<Option<Self>> { + let Some((_, list)) = ADDABLE.iter().find(|(b, _)| *b == bundle) else { + return Ok(None); + }; + if !text.contains(ADD_TO) { + return Ok(None); + } + let doc: J = serde_json::from_str(text)?; + let Some(targets) = doc.get(ADD_TO) else { + return Ok(None); + }; + let targets = match targets { + J::Str(s) => vec![s.clone()], + J::Arr(a) => a + .iter() + .map(|v| match v { + J::Str(s) => Some(s.clone()), + _ => None, + }) + .collect::<Option<_>>() + .ok_or(format!("{ADD_TO}: not a list of ids"))?, + _ => return Err(format!("{ADD_TO}: not an id or a list of ids").into()), + }; + let Some(J::Arr(entries)) = doc.get(list) else { + return Err(format!("{ADD_TO} without a {list} list").into()); + }; + Ok(Some(Self { + targets, + list, + entries: entries.clone(), + })) + } + /// Appends the entries to each target in the bundle `doc` (id → the + /// file's text). A target nobody defines is skipped, as a tag entry + /// naming an unknown id is. + fn apply(&self, doc: &mut J) -> Result<()> { + for target in &self.targets { + let Some(J::Str(text)) = doc.get(target) else { + continue; + }; + let mut v: J = serde_json::from_str(text).map_err(|e| format!("{target}: {e}"))?; + let Some(J::Arr(list)) = v.get_mut(self.list) else { + continue; + }; + list.extend(self.entries.iter().cloned()); + doc.set(target, J::Str(serde_json::to_string(&v)?)); + } + Ok(()) + } +} + /// The overlay being written: `out` mirrors `base` through links, and a /// directory becomes real only when something inside it is written. struct Overlay<'a> { @@ -904,6 +976,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<String, Vec<J>> = BTreeMap::new(); let mut worldgen: BTreeMap<&str, Vec<(String, String)>> = BTreeMap::new(); + let mut additions: BTreeMap<&str, Vec<Addition>> = BTreeMap::new(); for m in mods { let declarations = format!("data/{}/horizon/", m.id); for file in &m.content.files { @@ -928,7 +1001,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { 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)); + let entries = worldgen.entry(bundle).or_default(); + match Addition::read(bundle, &text).map_err(|e| format!("{file}: {e}"))? { + Some(addition) => additions.entry(bundle).or_default().push(addition), + None => entries.push((id, text)), + } } else if let Some(template) = file .strip_prefix("data/") .and_then(|r| r.split_once("/structure/")) @@ -1002,7 +1079,8 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { } overlay.write(BIOME_TAGS, &serde_json::to_vec(&doc)?)?; } - // Structures and the pools, sets, processors and features they use. + // Structures and the pools, sets, processors and features they use, then + // what mods add to sets and pools, in mod and file order. for (bundle, entries) in &worldgen { if !base.join(bundle).exists() { continue; @@ -1011,6 +1089,11 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { for (id, text) in entries { doc.set(id, J::Str(text.clone())); } + for addition in additions.get(bundle).into_iter().flatten() { + addition + .apply(&mut doc) + .map_err(|e| format!("{bundle}: {e}"))?; + } overlay.write(bundle, &serde_json::to_vec(&doc)?)?; } // A block without its own blockstate looks like its template, so every diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index 614705562..c80b45c3e 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -576,6 +576,18 @@ fn content_root_carries_a_structure_mod() { "data/huts/tags/worldgen/biome/has_hut.json", r##"{"values": ["#minecraft:is_overworld", "#c:is_plains", "othermod:glade", "minecraft:plains"]}"##, ), + // Additions to vanilla's set and pool; a target nobody defines is skipped. + ( + "data/huts/worldgen/structure_set/added/villages.json", + r#"{"horizon:add_to": "minecraft:villages", + "structures": [{"structure": "huts:hut", "weight": 3}]}"#, + ), + ( + "data/huts/worldgen/template_pool/added/houses.json", + r#"{"horizon:add_to": ["othermod:houses", "minecraft:village/plains/houses"], + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}]}"#, + ), ]; for (name, text) in files { let path = dir.join(name); @@ -601,6 +613,37 @@ fn content_root_carries_a_structure_mod() { hut["values"], serde_json::json!(["#minecraft:is_overworld", "minecraft:plains"]) ); + // The additions join vanilla's entries at the end and are no set or pool + // of their own. + let bundle = |name: &str, base: &Path| -> BTreeMap<String, String> { + serde_json::from_slice(&fs::read(base.join("worldgen").join(name)).unwrap()).unwrap() + }; + for (name, id, list, added) in [ + ( + "structure_sets.json", + "minecraft:villages", + "structures", + serde_json::json!({"structure": "huts:hut", "weight": 3}), + ), + ( + "template_pools.json", + "minecraft:village/plains/houses", + "elements", + serde_json::json!({"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "huts:hut", "projection": "rigid", "processors": "minecraft:empty"}}), + ), + ] { + let (ours, vanilla) = (bundle(name, &root), bundle(name, &base)); + let entries = |text: &str| -> Vec<serde_json::Value> { + let v: serde_json::Value = serde_json::from_str(text).unwrap(); + v[list].as_array().unwrap().clone() + }; + let mut expected = entries(&vanilla[id]); + expected.push(added); + assert_eq!(entries(&ours[id]), expected, "{id}"); + assert!(!ours.keys().any(|k| k.starts_with("huts:added/")), "{name}"); + assert!(!ours.contains_key("othermod:houses")); + } let assets = Assets::load(&root).unwrap(); let biomes = crate::biome::Biomes::load(&root).unwrap(); diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index bb94898e9..6fca66c1d 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -224,6 +224,8 @@ pub struct PlayerMotion { /// Spectator mode: no physics, always flying (`Player.tick`). pub spectator: bool, pub flying: bool, + /// Client-side `Abilities.flyingSpeed`, adjusted by the spectator scroll wheel. + pub flying_speed: f32, /// The jump key last tick (LocalPlayer.aiStep's wasJumping). pub was_jumping: bool, /// `LocalPlayer.autoJumpEnabled` (the Auto-Jump option) and @@ -387,6 +389,7 @@ impl PlayerMotion { invulnerable: false, spectator: false, flying: false, + flying_speed: 0.05, was_jumping: false, auto_jump_enabled: false, auto_jump_time: 0, @@ -649,7 +652,8 @@ impl MotionWorld<'_, '_, '_> { entities: self.entities, } } - pub(crate) fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> { + /// `Level.noCollision(player, bounds)`: blocks and the host's entity boxes. + pub fn no_player_collision(&mut self, bounds: Aabb) -> Result<bool> { let context = self.context(); Ok(world_movement::no_world_collision( &mut self.movement_collisions(), @@ -788,7 +792,7 @@ impl MotionWorld<'_, '_, '_> { // Vertical flight: jump up, shift down, three times the flying speed. let ya = i32::from(jumping) - i32::from(self.player.shift_key_down); if ya != 0 { - self.player.velocity.y += f64::from(ya as f32 * 0.05 * 3.0); + self.player.velocity.y += f64::from(ya as f32 * self.player.flying_speed * 3.0); } } self.dry_tick(TickInput::PreparedLocal { @@ -1862,8 +1866,8 @@ impl LivingAirWorld for MotionWorld<'_, '_, '_> { } fn flying_speed(&mut self) -> Result<f32> { if self.player.flying { - // Abilities.flyingSpeed 0.05, doubled when sprinting. - return Ok(if self.player.sprinting { 0.1 } else { 0.05 }); + // Player.getFlyingSpeed: abilities speed, doubled when sprinting. + return Ok(self.player.flying_speed * if self.player.sprinting { 2.0 } else { 1.0 }); } Ok(if self.player.sprinting { 0.025999999 @@ -2058,9 +2062,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 1).unwrap(); + let mut scene = World::test_scene(&assets, &render, 1).unwrap(); let entities = [Aabb::new( Vec3::new(10.0, 80.0, 10.0), Vec3::new(14.0, 84.0, 14.0), @@ -2121,6 +2126,47 @@ mod tests { assert!(player.position.y < 84.0); } + #[test] + fn spectator_scroll_speed_controls_horizontal_and_vertical_flight() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); + if !root.join("movement-properties.nbt").exists() { + return; + } + let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); + let binding = crate::collisions::load(&root, assets.registry).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + let run = |steps| { + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); + let start = Vec3::new(20.5, 12.0, 20.5); + let mut player = PlayerMotion::new(&resources, start).unwrap(); + player.spectator = true; + player.flying_speed = crate::mouse::spectator_flying_speed(player.flying_speed, steps); + MotionWorld { + entities: &[], + player: &mut player, + scene: &mut scene, + assets: &assets, + collision_binding: &binding, + resources: &resources, + } + .controlled_simulation_tick(crate::sprint::Keys { + forward: true, + jump: true, + ..Default::default() + }) + .unwrap(); + player.position.subtract(start) + }; + let stopped = run(-100); + assert_eq!(stopped, Vec3::ZERO); + let normal = run(0); + let fast = run(10); + assert!(normal.y > 0.0 && normal.z > 0.0); + assert!((fast.y - normal.y * 2.0).abs() < 1e-6); + assert!((fast.z - normal.z * 2.0).abs() < 1e-6); + } + #[test] fn resident_spectator_flight_ignores_solid_and_climbable_blocks() { let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3"); @@ -2128,10 +2174,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); let run = |name: &str, spectator: bool| { - let mut scene = World::test_scene(&assets, 2).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); let state = assets.registry.default_state(name).unwrap(); for x in 19..=23 { for y in 10..=17 { @@ -2367,10 +2414,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for wet in [false, true] { - let mut scene = World::test_scene(&assets, 2).unwrap(); + let mut scene = World::test_scene(&assets, &render, 2).unwrap(); if wet { let water = assets.registry.default_state("minecraft:water").unwrap(); for x in 19..=21 { @@ -2413,9 +2461,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); for x in 19..=21 { @@ -2667,9 +2716,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); for y in 4..=6 { scene.set(20, y, 20, water).unwrap(); @@ -2739,10 +2789,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for name in ["minecraft:lava", "minecraft:water"] { - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let fluid = assets.registry.default_state(name).unwrap(); scene.set(20, 4, 20, fluid).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); @@ -2790,9 +2841,10 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let water = assets.registry.default_state("minecraft:water").unwrap(); scene.set(20, 4, 20, water).unwrap(); scene.set(20, 5, 20, water).unwrap(); @@ -2859,10 +2911,11 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); + let render = assets.reload(&root).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); for (water_level, lava_level, ground_jump) in [(0, 6, true), (6, 0, false)] { - let mut scene = World::test_scene(&assets, 3).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); for (name, level, x) in [ ("minecraft:water", water_level, 20), ("minecraft:lava", lava_level, 21), @@ -2907,7 +2960,8 @@ mod tests { return; } let assets = Assets::load(&root).unwrap(); - let mut scene = World::test_scene(&assets, 3).unwrap(); + let render = assets.reload(&root).unwrap(); + let mut scene = World::test_scene(&assets, &render, 3).unwrap(); let binding = crate::collisions::load(&root, assets.registry).unwrap(); let resources = MotionResources::load(&root, &assets).unwrap(); let mut player = PlayerMotion::new(&resources, Vec3::new(20.5, 4.0, 20.5)).unwrap(); diff --git a/crates/horizon-client/src/mouse.rs b/crates/horizon-client/src/mouse.rs index d2794d790..1cee2be87 100644 --- a/crates/horizon-client/src/mouse.rs +++ b/crates/horizon-client/src/mouse.rs @@ -80,6 +80,12 @@ impl ScrollWheelHandler { } } +/// `MouseHandler.onScroll` with the spectator menu closed. Only vertical whole +/// wheel steps adjust `Abilities.flyingSpeed`; horizontal scrolling does not. +pub fn spectator_flying_speed(speed: f32, vertical_steps: i32) -> f32 { + (speed + vertical_steps as f32 * 0.005).clamp(0.0, 0.2) +} + /// Entity rotation as `Entity.turn` keeps it. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Rotation { diff --git a/crates/horizon-client/src/net.rs b/crates/horizon-client/src/net.rs index f9ad5992a..74f1b0b6d 100644 --- a/crates/horizon-client/src/net.rs +++ b/crates/horizon-client/src/net.rs @@ -1,7 +1,8 @@ //! Multiplayer session: a network thread that connects to a server, logs in, //! runs the configuration phase and then forwards decoded play packets to the -//! game thread. Keep-alives and pings are answered on the network thread like -//! vanilla's connection handlers so a busy frame never times the client out. +//! game thread. Keep-alives are answered on the network thread; pings wait for +//! the game thread, like ClientCommonPacketListenerImpl.handlePing, so a pong +//! cannot overtake an earlier world update or teleport acknowledgement. //! Online-mode servers need the Microsoft account the launcher signed in //! (crate::auth): the login joins the server through the session service and //! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello). @@ -382,8 +383,17 @@ fn run( uuid: profile.uuid, name: profile.name, }); + receive_play(&mut reader, shared_writer, lang, send) +} + +fn receive_play( + reader: &mut ConnReader, + shared_writer: &Mutex<Option<ConnWriter>>, + lang: &Language, + send: &Sender<Event>, +) -> Result<String, String> { loop { - let (id, payload) = reader.recv().map_err(e)?; + let (id, payload) = reader.recv().map_err(|e| e.to_string())?; let packet = match play::Clientbound::decode(id, &payload) { Ok(p) => p, Err(err) => { @@ -404,7 +414,6 @@ fn run( }; match packet { play::Clientbound::KeepAlive(k) => reply(play::Serverbound::KeepAlive(k)), - play::Clientbound::Ping(p) => reply(play::Serverbound::Pong(p)), play::Clientbound::BundleDelimiter(_) => {} play::Clientbound::ResourcePackPush(p) => { // Declined: Horizon has no server resource packs. @@ -415,7 +424,7 @@ fn run( } play::Clientbound::StartConfiguration(_) => { reply(play::Serverbound::ConfigurationAcknowledged(Empty)); - let registries = configure(&mut reader, shared_writer, lang, send)?; + let registries = configure(reader, shared_writer, lang, send)?; let _ = send.send(Event::Reconfigured(Arc::new(registries))); } play::Clientbound::Disconnect(d) => return Ok(plain(&d.reason, lang)), @@ -585,6 +594,50 @@ pub fn ping(address: &str, timeout: Duration) -> Result<(serde_json::Value, u128 mod tests { use super::*; + #[test] + fn pings_wait_behind_teleports_but_keepalives_do_not_wait_for_the_game() { + let (client, server) = horizon_protocol::connection::Pipe::pair(); + let (mut reader, writer) = Connection::local(client).split(); + let writer = Arc::new(Mutex::new(Some(writer))); + let (send, events) = channel(); + let thread_writer = writer.clone(); + let thread = std::thread::spawn(move || { + receive_play(&mut reader, &thread_writer, &Language::new(), &send) + }); + let mut server = Connection::local(server); + let teleport = play::Clientbound::PlayerPosition(play::PlayerPosition { + teleport: 42, + position: [10.0, 64.0, 10.0], + delta: [0.0; 3], + yaw: 90.0, + pitch: 0.0, + relatives: 0, + }); + server.send(&teleport.encode()).unwrap(); + server + .send(&play::Clientbound::Ping(cfg::Ping { id: 7 }).encode()) + .unwrap(); + // A reply to this proves the receive loop has passed the ping. The + // old implementation instead replies with Pong before this keepalive. + server + .send(&play::Clientbound::KeepAlive(cfg::KeepAlive { id: 9 }).encode()) + .unwrap(); + let (id, body) = server.recv().unwrap(); + assert_eq!( + play::Serverbound::decode(id, &body).unwrap(), + play::Serverbound::KeepAlive(cfg::KeepAlive { id: 9 }) + ); + let timeout = Duration::from_secs(5); + assert!( + matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == teleport) + ); + assert!( + matches!(events.recv_timeout(timeout).unwrap(), Event::Packet(p) if *p == play::Clientbound::Ping(cfg::Ping { id: 7 })) + ); + writer.lock().unwrap().take().unwrap().shutdown(); + assert!(thread.join().unwrap().is_err()); + } + #[test] fn server_brand_payload_is_decoded_and_invalid_or_unrelated_payloads_are_ignored() { let (send, events) = channel(); diff --git a/crates/horizon-client/src/particles.rs b/crates/horizon-client/src/particles.rs index 57d9e60d7..938e8d72d 100644 --- a/crates/horizon-client/src/particles.rs +++ b/crates/horizon-client/src/particles.rs @@ -1264,12 +1264,21 @@ impl ParticleEngine { } self.create(options, p, v); } - /// `LevelEventHandler.singleBlockTeleportationParticles` (event 2015). - pub fn block_teleportation(&mut self, from: [i32; 3], data: i32, particle_level: u8) { + /// `LevelEventHandler.singleBlockTeleportationParticles` towards + /// `BlockUtil.unpackDifferenceInPosition(from, data, radius)`: the dragon + /// egg's event 2015 packs offsets within (16, 8, 16), a consumable's + /// teleport (2017) within (127, 127, 127). + pub fn block_teleportation( + &mut self, + from: [i32; 3], + data: i32, + radius: [i32; 3], + particle_level: u8, + ) { let to = [ - from[0].wrapping_add(((data >> 16) & 255) - 16), - from[1].wrapping_add(((data >> 8) & 255) - 8), - from[2].wrapping_add((data & 255) - 16), + from[0].wrapping_add(((data >> 16) & 255) - radius[0]), + from[1].wrapping_add(((data >> 8) & 255) - radius[1]), + from[2].wrapping_add((data & 255) - radius[2]), ] .map(f64::from); let from = from.map(f64::from); @@ -3798,7 +3807,7 @@ mod tests { let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new()); engine.seed_randoms(0, 0, 0); // Destination offset (-15, 7, 15); the unused top byte is ignored. - engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, 0); + engine.block_teleportation([4, 12, -5], 0xff01_0f1fu32 as i32, [16, 8, 16], 0); assert_eq!(engine.pending.len(), 128); assert!(engine.pending.iter().all(|p| p.ty == ParticleType::Portal)); let first = &engine.pending[0]; @@ -3818,6 +3827,25 @@ mod tests { assert!(engine.sounds.is_empty()); } + #[test] + fn consume_teleport_unpacks_offsets_within_127() { + let mut engine = ParticleEngine::new(Path::new(""), &HashMap::new()); + engine.seed_randoms(0, 0, 0); + // TeleportRandomlyConsumeEffect: BlockUtil.clampedPackDifferenceInPosition + // of the move (-7, -3, 9) with radii 127, from (4, 12, -5) to (-3, 9, 4). + let data = (-7 + 127) << 16 | (-3 + 127) << 8 | (9 + 127); + engine.block_teleportation([4, 12, -5], data, [127, 127, 127], 0); + assert_eq!(engine.pending.len(), 128); + for p in &engine.pending { + let [x, y, z] = p.position; + assert!((-3.0..5.0).contains(&x), "{x}"); + assert!((8.5..12.5).contains(&y), "{y}"); + assert!((-5.0..5.0).contains(&z), "{z}"); + } + // The same draws as the egg's: only the unpacking differs. + assert_eq!(engine.level_random.state(), 99_413_408_083_437); + } + #[test] fn egg_teleport_options_roll_before_distance_rejection() { for (option, count, state) in [ @@ -3831,7 +3859,7 @@ mod tests { if distant { engine.camera = [1000.0; 3]; } - engine.block_teleportation([4, 12, -5], 0x010f1f, option); + engine.block_teleportation([4, 12, -5], 0x010f1f, [16, 8, 16], option); assert_eq!(engine.pending.len(), if distant { 0 } else { count }); assert_eq!(engine.level_random.state(), state); } diff --git a/crates/horizon-client/src/player_sync.rs b/crates/horizon-client/src/player_sync.rs new file mode 100644 index 000000000..96b09c708 --- /dev/null +++ b/crates/horizon-client/src/player_sync.rs @@ -0,0 +1,86 @@ +//! LocalPlayer.sendPosition and PositionMoveRotation.calculateAbsolute. +use horizon_core::geometry::Vec3; +use horizon_protocol::packets::play::{self, PlayerPosition, Serverbound as S, relative}; + +/// Only movement updates advance this baseline. A teleport acknowledgement is +/// separate and must not suppress the next tick's corrected position or look. +#[derive(Default)] +pub struct PositionSender { + position: [f64; 3], + rotation: (f32, f32), + on_ground: bool, + collision: bool, + reminder: u32, +} + +impl PositionSender { + pub fn update( + &mut self, + position: [f64; 3], + rotation: (f32, f32), + on_ground: bool, + collision: bool, + ) -> Option<S> { + self.reminder += 1; + let d: [f64; 3] = std::array::from_fn(|i| position[i] - self.position[i]); + let moved = + d[0] * d[0] + d[1] * d[1] + d[2] * d[2] > 2.0e-4 * 2.0e-4 || self.reminder >= 20; + let rotated = rotation.0 - self.rotation.0 != 0.0 || rotation.1 - self.rotation.1 != 0.0; + let flags = u8::from(on_ground) | u8::from(collision) << 1; + let [x, y, z] = position; + let (yaw, pitch) = rotation; + let packet = if moved && rotated { + Some(S::MovePlayerPosRot(play::MovePlayerPosRot { + x, + y, + z, + yaw, + pitch, + flags, + })) + } else if moved { + Some(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags })) + } else if rotated { + Some(S::MovePlayerRot(play::MovePlayerRot { yaw, pitch, flags })) + } else if self.on_ground != on_ground || self.collision != collision { + Some(S::MovePlayerStatus(play::MovePlayerStatus { flags })) + } else { + None + }; + if moved { + self.position = position; + self.reminder = 0; + } + if rotated { + self.rotation = rotation; + } + self.on_ground = on_ground; + self.collision = collision; + packet + } +} + +/// Rotate the old velocity before adding the relative delta components. +/// Angles deliberately use Java's double toRadians followed by a float cast. +pub fn teleport_velocity( + mut velocity: Vec3, + old_rotation: (f32, f32), + new_rotation: (f32, f32), + packet: &PlayerPosition, +) -> Vec3 { + if packet.relatives & relative::ROTATE_DELTA != 0 { + let pitch = f64::from(old_rotation.1 - new_rotation.1).to_radians() as f32; + let yaw = f64::from(old_rotation.0 - new_rotation.0).to_radians() as f32; + velocity = velocity.rotate_x(pitch).rotate_y(yaw); + } + let old = [velocity.x, velocity.y, velocity.z]; + let flags = [relative::DELTA_X, relative::DELTA_Y, relative::DELTA_Z]; + let result: [f64; 3] = std::array::from_fn(|i| { + if packet.relatives & flags[i] != 0 { + old[i] + packet.delta[i] + } else { + packet.delta[i] + } + }); + Vec3::new(result[0], result[1], result[2]) +} diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 569e7ef3c..c407a7967 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1321,22 +1321,22 @@ fn cached_region( /// Write `records` into the region files of `folder` in place, as vanilla's /// `RegionFile.write` does: each chunk takes free sectors and the header /// then points to it; the region's other chunks are not touched. `None` -/// clears a chunk. The chunks are compressed before their region is locked -/// for the writes, and each region is flushed to the disk once. +/// clears a chunk. The chunks are encoded and compressed before their region +/// is locked for the writes (`compress_records`), and each region is flushed +/// to the disk once. fn write_region_records( root: &Path, cache: &RegionCache, folder: &str, - records: Vec<((i32, i32), Option<Arc<NamedTag>>)>, + records: &[((i32, i32), &Record)], ) -> Result<()> { let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map_or(0, |d| d.as_secs() as u32); + let compressed = compress_records(records, timestamp); let mut by_region: BTreeMap<(i32, i32), Vec<(ChunkPos, Option<ChunkRecord>)>> = BTreeMap::new(); - for ((x, z), tag) in records { - let record = tag - .map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())) - .transpose()?; + for (&((x, z), _), record) in records.iter().zip(compressed) { + let record = record?; by_region .entry((x >> 5, z >> 5)) .or_default() @@ -1367,6 +1367,57 @@ fn write_region_records( Ok(()) } +/// Fewest chunks each helper of `compress_records` takes: below this a thread +/// costs more to start than it saves. +const CHUNKS_PER_HELPER: usize = 4; +/// Each record encoded and compressed (`None` for a deletion), in the order +/// given. Vanilla's IOWorker does this one chunk after another; here a batch +/// is shared out to scoped threads, which take the next chunk as they finish +/// one. Each chunk's bytes depend only on the chunk, and the writes stay in +/// order, so the files are the same as from one thread. At most half the +/// hardware threads help, leaving the rest to the game and its workers. +fn compress_records( + records: &[((i32, i32), &Record)], + timestamp: u32, +) -> Vec<std::io::Result<Option<ChunkRecord>>> { + let compress = |record: &Record| { + record + .tag() + .map(|tag| ChunkRecord::from_nbt(&tag, Compression::Zlib, timestamp, Limits::default())) + .transpose() + }; + let helpers = std::thread::available_parallelism() + .map_or(1, |n| n.get().div_ceil(2)) + .min(records.len() / CHUNKS_PER_HELPER); + if helpers <= 1 { + return records.iter().map(|(_, r)| compress(r)).collect(); + } + let next = std::sync::atomic::AtomicUsize::new(0); + let mut done: Vec<(usize, std::io::Result<Option<ChunkRecord>>)> = + std::thread::scope(|scope| { + let threads: Vec<_> = (0..helpers) + .map(|_| { + scope.spawn(|| { + let mut out = Vec::new(); + loop { + let i = next.fetch_add(1, Ordering::Relaxed); + let Some((_, record)) = records.get(i) else { + return out; + }; + out.push((i, compress(record))); + } + }) + }) + .collect(); + threads + .into_iter() + .flat_map(|t| t.join().unwrap_or_else(|e| std::panic::resume_unwind(e))) + .collect() + }); + done.sort_unstable_by_key(|(i, _)| *i); + done.into_iter().map(|(_, r)| r).collect() +} + fn region_path(root: &Path, folder: &str, rx: i32, rz: i32) -> PathBuf { root.join(format!("{folder}/r.{rx}.{rz}.mca")) } @@ -1582,12 +1633,12 @@ impl SaveDir { p.get(&(entities, k.0, k.1)).is_none_or(|p| p.0 <= seq) }) }; - let records = batch + let records: Vec<_> = batch .iter() .filter(|(k, _, seq)| newest(k, *seq)) - .map(|(k, r, _)| (*k, r.tag())) + .map(|(k, r, _)| (*k, r)) .collect(); - if let Err(e) = write_region_records(&root, cache, folder, records) { + if let Err(e) = write_region_records(&root, cache, folder, &records) { log::warn!("Horizon: failed to write {folder} files: {e}"); } // Readers find the files (and a fresh region cache) from here on. @@ -2905,6 +2956,43 @@ mod tests { assert_eq!(source.block_entities[0].0, (99, 0, 99)); } + #[test] + fn records_compressed_on_helpers_match_one_thread_in_order() { + use super::{Record, compress_records}; + let records: Vec<((i32, i32), Record)> = (0..53i32) + .map(|i| { + let record = if i % 7 == 3 { + Record::Delete + } else { + let payload: Vec<i64> = (0..i * 97 % 2000).map(|v| i64::from(v * i)).collect(); + Record::Tag(Arc::new(NamedTag { + name: "".into(), + tag: Tag::compound([ + ("xPos", Tag::Int(i)), + ("Data", Tag::LongArray(payload)), + ]), + })) + }; + ((i, -i), record) + }) + .collect(); + let refs: Vec<_> = records.iter().map(|(k, r)| (*k, r)).collect(); + let compressed = compress_records(&refs, 1234); + assert_eq!(compressed.len(), records.len()); + for ((_, record), got) in records.iter().zip(compressed) { + let want = record + .tag() + .map(|t| ChunkRecord::from_nbt(&t, Compression::Zlib, 1234, Limits::default())) + .transpose() + .unwrap(); + let got = got.unwrap(); + assert_eq!( + got.as_ref().map(|r| (&r.compressed, r.timestamp)), + want.as_ref().map(|r| (&r.compressed, r.timestamp)) + ); + } + } + #[test] fn older_worlds_are_upgraded_on_opening() { let dir = std::env::temp_dir().join(format!("horizon-dv-{}", std::process::id())); diff --git a/crates/horizon-client/src/spans.rs b/crates/horizon-client/src/spans.rs index 9fd91b2df..5c37f2bfc 100644 --- a/crates/horizon-client/src/spans.rs +++ b/crates/horizon-client/src/spans.rs @@ -1,11 +1,12 @@ //! Named timings within a frame, for finding what makes a frame slow: //! `HORIZON_SPIKES=MS` prints the spans of every frame whose CPU time -//! exceeds MS milliseconds. Costs one clock read per span when enabled and -//! a relaxed load otherwise. +//! exceeds MS milliseconds, and of every server tick (dedicated or +//! integrated) longer than MS. Costs one clock read per span when enabled +//! and a relaxed load otherwise. use std::{ cell::RefCell, sync::atomic::{AtomicBool, Ordering}, - time::Instant, + time::{Duration, Instant}, }; static ENABLED: AtomicBool = AtomicBool::new(false); @@ -28,6 +29,18 @@ pub fn time<T>(name: &'static str, f: impl FnOnce() -> T) -> T { SPANS.with(|s| s.borrow_mut().push((name, ms))); out } +/// The CPU time this thread has used, where the platform tells it: a tick +/// with more wall time than CPU time waited (for a lock, or for a core on a +/// busy machine). +pub fn thread_cpu() -> Option<Duration> { + #[cfg(unix)] + { + let t = rustix::time::clock_gettime(rustix::time::ClockId::ThreadCPUTime); + Some(Duration::new(t.tv_sec as u64, t.tv_nsec as u32)) + } + #[cfg(not(unix))] + None +} /// The frame's spans, summed by name, slowest first; clears them. pub fn take() -> Vec<(&'static str, f32)> { let spans = SPANS.with(|s| std::mem::take(&mut *s.borrow_mut())); @@ -41,3 +54,29 @@ pub fn take() -> Vec<(&'static str, f32)> { sums.sort_by(|a, b| b.1.total_cmp(&a.1)); sums } + +#[cfg(test)] +mod tests { + /// The thread's CPU clock moves with work done on it, not with time + /// spent asleep. + #[cfg(unix)] + #[test] + fn thread_cpu_counts_work_not_sleep() { + let start = super::thread_cpu().unwrap(); + std::thread::sleep(std::time::Duration::from_millis(50)); + let slept = super::thread_cpu().unwrap() - start; + // Busy until the clock shows 10 ms of work (a loaded machine gives + // the thread less than its wall time). + let mut x = 0u64; + let busy = std::time::Instant::now(); + let worked = loop { + x = std::hint::black_box(x.wrapping_mul(31).wrapping_add(7)); + let worked = super::thread_cpu().unwrap() - start - slept; + if worked.as_millis() >= 10 || busy.elapsed().as_secs() >= 10 { + break worked; + } + }; + assert!(slept.as_millis() < 25, "{slept:?} while asleep"); + assert!(worked.as_millis() >= 10, "{worked:?} while busy"); + } +} diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 6acdcafd2..1a592e21b 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -5,7 +5,7 @@ use crate::fast_hash::{FxHashMap, FxHashSet}; use crate::{ chunk::{Chunk, SECTIONS}, - light::{LightTables, apply_lighting, apply_relighting, light_chunk}, + light::{LightChanges, LightTables, apply_lighting, apply_relighting, light_chunk}, mesher::{MeshTables, Mesher, Region, SectionMesh, borrow}, world::World, }; @@ -335,6 +335,7 @@ impl GenerationScan { } pub struct WorkerContext { pub assets: Arc<crate::assets::Assets>, + pub render: Arc<crate::assets::RenderAssets>, pub tables: Arc<MeshTables>, pub biomes: Arc<crate::biome::Biomes>, pub light: Arc<LightTables>, @@ -424,6 +425,7 @@ impl Streaming { cutout_leaves: settings.cutout_leaves, cull_leaves: settings.cull_leaves, assets: &context.assets, + render: &context.render, tables: &context.tables, biomes: &context.biomes, visibility, @@ -544,7 +546,7 @@ impl Streaming { self.lighting.remove(&(x, z)); self.meshing.retain(|k, _| (k.0, k.2) != (x, z)); self.waiting.retain(|k| (k.0, k.2) != (x, z)); - world.dirty_sections.retain(|k| (k.0, k.2) != (x, z)); + world.dirty_sections.take_column(x, z); world.chunks.remove(&(x, z)) } fn submit(&mut self, priority: i64, job: Job) { @@ -748,12 +750,12 @@ impl Streaming { // only around the light that changed, as vanilla's light // updates dirty only their sections (#270). let first = self.lit.insert((x, z)); - let changed = if first { + let mut changed = LightChanges::default(); + if first { apply_lighting(chunk, sections); - Vec::new() } else { - apply_relighting(chunk, sections) - }; + apply_relighting(chunk, sections, &mut changed); + } chunk.lit = true; if first { for dz in -1..=1 { @@ -809,7 +811,9 @@ impl Streaming { let far: HashSet<(i32, i32)> = far.iter().copied().collect(); self.meshing.retain(|k, _| !far.contains(&(k.0, k.2))); self.waiting.retain(|k| !far.contains(&(k.0, k.2))); - world.dirty_sections.retain(|k| !far.contains(&(k.0, k.2))); + world + .dirty_sections + .retain_columns(|x, z| !far.contains(&(x, z))); } // Drop far proto chunks that are not checked out. let (center, r4) = (self.center, i64::from(self.radius + 4)); @@ -1025,66 +1029,63 @@ impl Streaming { !back }); } - let dirty: Vec<_> = world.dirty_sections.iter().copied().collect(); - let mut columns: FxHashMap<(i32, i32), Option<Box<Region>>> = FxHashMap::default(); - let mut ready_columns: FxHashMap<(i32, i32), bool> = FxHashMap::default(); - for (x, sy, z) in dirty { + // Column by column: the checks below hold for all of a column's + // sections, and columns waiting for light cost one look per frame. + let columns: Vec<_> = world.dirty_sections.columns().collect(); + for ((x, z), sections) in columns { if !world.chunks.contains_key(&(x, z)) { - world.dirty_sections.remove(&(x, sy, z)); + world.dirty_sections.take_column(x, z); continue; } if !self.ranges().in_view(x, z) { - world.dirty_sections.remove(&(x, sy, z)); - self.waiting.insert((x, sy, z)); + world.dirty_sections.take_column(x, z); + for sy in section_indexes(sections) { + self.waiting.insert((x, sy, z)); + } continue; } - // Once per column: the 3x3 check would otherwise repeat for each - // of its sections every frame. A neighbour being lit dirties this - // column again when its light job finishes (new chunks relight - // their eight neighbours), so wait for it rather than mesh once - // per neighbour. Columns still in `dirty_light` here can't be lit - // yet (a neighbour of theirs is missing): waiting for them could - // last until the player comes back. - let (lit, lighting) = (&self.lit, &self.lighting); - let ready = *ready_columns.entry((x, z)).or_insert_with(|| { - (-1..=1).all(|dz| { - (-1..=1).all(|dx| { - let n = (x + dx, z + dz); - lit.contains(&n) && !lighting.contains_key(&n) - }) + // A neighbour being lit dirties this column again when its light + // job finishes (new chunks relight their eight neighbours), so + // wait for it rather than mesh once per neighbour. Columns still + // in `dirty_light` here can't be lit yet (a neighbour of theirs is + // missing): waiting for them could last until the player comes + // back. + let ready = (-1..=1).all(|dz| { + (-1..=1).all(|dx| { + let n = (x + dx, z + dz); + self.lit.contains(&n) && !self.lighting.contains_key(&n) }) }); if !ready { continue; } - let region = columns - .entry((x, z)) - .or_insert_with(|| Self::region(world, x, z)); - let Some(region) = region.clone() else { + let Some(region) = Self::region(world, x, z) else { continue; }; - world.dirty_sections.remove(&(x, sy, z)); - let first = self.meshed.insert((x, z)); - self.sequence += 1; - self.meshing.insert((x, sy, z), self.sequence); - self.submit( - self.distance(x, z) * 4 + if first { 2 } else { 0 }, - Job::Mesh( - x, - sy, - z, - region, - self.sequence, - MeshSettings { - nether: self.nether_shading, - zoom: self.biome_zoom, - blend_radius: self.biome_blend, - smooth_lighting: self.smooth_lighting, - cutout_leaves: self.cutout_leaves, - cull_leaves: self.cull_leaves, - }, - ), - ); + world.dirty_sections.take_column(x, z); + for sy in section_indexes(sections) { + let first = self.meshed.insert((x, z)); + self.sequence += 1; + self.meshing.insert((x, sy, z), self.sequence); + self.submit( + self.distance(x, z) * 4 + if first { 2 } else { 0 }, + Job::Mesh( + x, + sy, + z, + region.clone(), + self.sequence, + MeshSettings { + nether: self.nether_shading, + zoom: self.biome_zoom, + blend_radius: self.biome_blend, + smooth_lighting: self.smooth_lighting, + cutout_leaves: self.cutout_leaves, + cull_leaves: self.cull_leaves, + }, + ), + ); + } } (uploads, removed) } @@ -1125,12 +1126,14 @@ impl Streaming { if positions.is_empty() { return; } - let changed = crate::light::relight( + let mut changed = LightChanges::default(); + crate::light::relight( &mut world.chunks, &self.light_tables, self.sky_light, &positions, false, + &mut changed, ); Self::mark_light_changes(world, &changed); if !self.light_snapshots.is_empty() { @@ -1152,12 +1155,14 @@ impl Streaming { .map(|(_, p)| *p) .collect(); if !positions.is_empty() { - let changed = crate::light::relight( + let mut changed = LightChanges::default(); + crate::light::relight( &mut world.chunks, &self.light_tables, self.sky_light, &positions, true, + &mut changed, ); Self::mark_light_changes(world, &changed); } @@ -1169,31 +1174,15 @@ impl Streaming { } /// Sections whose meshes sample a changed light value (faces and corners /// read light from neighbouring blocks). - fn mark_light_changes(world: &mut World, changed: &[(i32, i32, i32)]) { + fn mark_light_changes(world: &mut World, changed: &LightChanges) { if let Some(log) = &mut world.light_log { - for &(x, y, z) in changed { - *log.entry((x >> 4, z >> 4)).or_default() |= 1 << ((y - crate::chunk::MIN_Y) >> 4); - } - } - let mut last = None; - for &(x, y, z) in changed { - for dz in -1..=1 { - for dy in -1..=1 { - for dx in -1..=1 { - let s = ( - (y + dy - crate::chunk::MIN_Y) >> 4, - (x + dx) >> 4, - (z + dz) >> 4, - ); - if last == Some(s) || !(0..SECTIONS as i32).contains(&s.0) { - continue; - } - last = Some(s); - world.dirty_sections.insert((s.1, s.0, s.2)); - } - } + for (x, sy, z) in changed.sections() { + *log.entry((x, z)).or_default() |= 1 << sy; } } + changed.dirty_sections(|section| { + world.dirty_sections.insert(section); + }); } fn ranges(&self) -> Ranges<'_> { Ranges { @@ -1355,6 +1344,16 @@ impl Drop for Streaming { } } } +/// The section indexes set in a column's bits, lowest first. +fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> { + std::iter::from_fn(move || { + (bits != 0).then(|| { + let sy = bits.trailing_zeros() as i32; + bits &= bits - 1; + sy + }) + }) +} #[cfg(test)] mod tests { use super::*; diff --git a/crates/horizon-client/src/telemetry.rs b/crates/horizon-client/src/telemetry.rs index 9e83655fa..d0140f941 100644 --- a/crates/horizon-client/src/telemetry.rs +++ b/crates/horizon-client/src/telemetry.rs @@ -3,6 +3,7 @@ //! summary, in the outbox. It never sends anything itself: the launcher does, at its next start. //! Without the player's yes for that kind nothing is kept, and crash-reports/ stays local. use std::path::Path; +use std::sync::atomic::{AtomicU32, Ordering}; use std::sync::{Mutex, OnceLock}; use std::time::Instant; @@ -18,6 +19,11 @@ const MIN_SECONDS: f32 = 60.0; const CRASH_DETAILS: [&str; 3] = ["Horizon Version", "Graphics Adapter", "Render Settings"]; static STARTED: OnceLock<Instant> = OnceLock::new(); +/// When the menu bundle became ready, so the time to the title screen measures +/// the menu and not the world bundle loaded behind it. +static UI_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); +static CORE_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); +static REST_READY_MS: AtomicU32 = AtomicU32::new(u32::MAX); /// The GPU's name, driver and backend, once the renderer has its adapter. static GPU: Mutex<Option<(String, String, String)>> = Mutex::new(None); @@ -26,6 +32,34 @@ pub fn mark_start() { STARTED.get_or_init(Instant::now); } +/// The menu bundle is ready: the title backdrop can draw. The first writer wins. +pub fn mark_ui_ready() { + if let Some(started) = STARTED.get() { + let ms = started.elapsed().as_millis() as u32; + let _ = UI_READY_MS.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed); + } +} + +pub fn mark_core_ready() { + mark_ready(&CORE_READY_MS); +} + +pub fn mark_rest_ready() { + mark_ready(&REST_READY_MS); +} + +fn mark_ready(mark: &AtomicU32) { + if let Some(started) = STARTED.get() { + let ms = started.elapsed().as_millis().min(u128::from(u32::MAX - 1)) as u32; + let _ = mark.compare_exchange(u32::MAX, ms, Ordering::Relaxed, Ordering::Relaxed); + } +} + +fn readiness_ms(mark: &AtomicU32) -> Option<u32> { + let ms = mark.load(Ordering::Relaxed); + (ms != u32::MAX).then_some(ms) +} + pub fn set_gpu(name: &str, driver: String, backend: String) { *GPU.lock().unwrap_or_else(|e| e.into_inner()) = Some((name.to_owned(), driver, backend)); } @@ -138,7 +172,12 @@ impl Session { pub fn title_shown(&mut self) { if !self.title_measured { self.title_measured = true; - self.to_title_ms = STARTED.get().map(|s| s.elapsed().as_millis() as u32); + let ui_ms = UI_READY_MS.load(Ordering::Relaxed); + self.to_title_ms = if ui_ms != u32::MAX { + Some(ui_ms) + } else { + STARTED.get().map(|s| s.elapsed().as_millis() as u32) + }; } } @@ -147,6 +186,11 @@ impl Session { self.opening.get_or_insert_with(Instant::now); } + /// An entry queued during startup was cancelled before opening a world. + pub fn cancel_world_opening(&mut self) { + self.opening = None; + } + /// A frame drawn while playing (not in menus or loading). pub fn frame(&mut self, ms: f32) { if let Some(opening) = self.opening.take() @@ -175,6 +219,8 @@ impl Session { peak_ram_mb: peak_ram_mb(), to_title_ms: self.to_title_ms, to_world_ms: self.to_world_ms, + to_core_ms: self.to_title_ms.and_then(|_| readiness_ms(&CORE_READY_MS)), + to_rest_ms: self.to_title_ms.and_then(|_| readiness_ms(&REST_READY_MS)), }) } @@ -377,6 +423,20 @@ mod tests { assert_eq!(pending[0].1.kind(), Kind::Crash); } + #[test] + fn cancelled_startup_entry_does_not_time_menu_browsing() { + let mut session = Session::default(); + session.world_opening(); + assert!(session.opening.is_some()); + session.cancel_world_opening(); + assert!(session.opening.is_none()); + session.frame(16.0); + assert!(session.to_world_ms.is_none()); + session.world_opening(); + session.frame(16.0); + assert!(session.to_world_ms.is_some()); + } + #[test] fn a_session_is_kept_only_with_consent_and_once_long_enough() { let home = home("session"); diff --git a/crates/horizon-client/src/terrain.wgsl b/crates/horizon-client/src/terrain.wgsl index 504d197aa..7d25cef2f 100644 --- a/crates/horizon-client/src/terrain.wgsl +++ b/crates/horizon-client/src/terrain.wgsl @@ -72,11 +72,16 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> { return textureSampleLevel(lightmap, lightmap_sampler, clamp(uv / 256.0 + 0.5 / 16.0, vec2(0.5 / 16.0), vec2(15.5 / 16.0)), 0.0); } +// mesher.rs's TerrainVertex holds the UV in 32768 steps per unit: a power of +// two on an integer below 2^24, so it decodes exactly. +fn terrain_uv(packed: vec2<u32>) -> vec2<f32> { + return vec2<f32>(packed) * (1.0 / 32768.0); +} @vertex fn vs_terrain( - @location(0) position: vec3<f32>, @location(1) uv: vec2<f32>, + @location(0) position: vec3<f32>, @location(1) uv: vec2<u32>, @location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32>, @location(5) origin: vec4<f32>) -> TerrainOut { - return terrain_vertex(position, uv, layer, color, light, origin.xyz); + return terrain_vertex(position, terrain_uv(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: @@ -85,11 +90,11 @@ fn sample_lightmap(sky: f32, block: f32) -> vec4<f32> { @group(1) @binding(1) var<storage, read> slot_origins: array<vec4<f32>>; @vertex fn vs_terrain_flat( @builtin(vertex_index) vertex: u32, - @location(0) position: vec3<f32>, @location(1) uv: vec2<f32>, + @location(0) position: vec3<f32>, @location(1) uv: vec2<u32>, @location(2) layer: u32, @location(3) color: vec4<f32>, @location(4) light: vec2<u32> ) -> TerrainOut { let origin = slot_origins[block_slots[vertex >> 8u]]; - return terrain_vertex(position, uv, layer, color, light, origin.xyz); + return terrain_vertex(position, terrain_uv(uv), layer, color, light, origin.xyz); } fn terrain_vertex(position: vec3<f32>, uv: vec2<f32>, layer: u32, color: vec4<f32>, light: vec2<u32>, origin: vec3<f32>) -> TerrainOut { diff --git a/crates/horizon-client/src/text.rs b/crates/horizon-client/src/text.rs index ea11d4163..3874efd17 100644 --- a/crates/horizon-client/src/text.rs +++ b/crates/horizon-client/src/text.rs @@ -279,6 +279,12 @@ impl Text { self.source = Some(c.into()); self } + /// The same spans, sent to vanilla as `component` (a shape the spans' + /// own JSON would not take, such as a styled root with siblings). + pub fn with_component(mut self, component: Value) -> Self { + self.source = Some(component.into()); + self + } pub fn with_color(self, color: u32) -> Self { self.with_style(&Style::color(color)) } diff --git a/crates/horizon-client/src/tick_chunk_membership.rs b/crates/horizon-client/src/tick_chunk_membership.rs index 42785f289..a7e934443 100644 --- a/crates/horizon-client/src/tick_chunk_membership.rs +++ b/crates/horizon-client/src/tick_chunk_membership.rs @@ -10,6 +10,9 @@ pub struct TickChunkMembership { revision: Option<u64>, added: Vec<Key>, removed: Vec<Key>, + /// Loaded chunks with saved ticks that have not started ticking yet + /// (`LevelChunkTicks.pendingTicks`, unpacked by `startTickingChunk`). + waiting: HashSet<Key>, } impl TickChunkMembership { @@ -20,6 +23,7 @@ impl TickChunkMembership { self.revision = None; self.added.clear(); self.removed.clear(); + self.waiting.clear(); } /// Returns false in O(1) when resident membership is unchanged. On change, @@ -36,6 +40,7 @@ impl TickChunkMembership { true } else { self.removed.push(*key); + self.waiting.remove(key); false } }); @@ -62,6 +67,28 @@ impl TickChunkMembership { pub fn removed(&self) -> &[Key] { &self.removed } + + /// `key` was registered with saved ticks to unpack once it ticks. + pub fn wait(&mut self, key: Key) { + self.waiting.insert(key); + } + + /// The waiting chunks that `ticking` says now tick, no longer waiting. + pub fn start_ticking(&mut self, mut ticking: impl FnMut(Key) -> bool) -> Vec<Key> { + if self.waiting.is_empty() { + return Vec::new(); + } + let started: Vec<Key> = self + .waiting + .iter() + .copied() + .filter(|&k| ticking(k)) + .collect(); + for key in &started { + self.waiting.remove(key); + } + started + } } #[cfg(test)] @@ -124,6 +151,24 @@ mod tests { compare(&mut cache, &mut old, &map); } + #[test] + fn waiting_chunks_start_ticking_once_and_unloaded_ones_stop_waiting() { + let mut map = ChunkMap::default(); + let mut cache = TickChunkMembership::default(); + for key in [(0, 0), (1, 0), (2, 0)] { + map.insert(key, Arc::new(Chunk::empty(key.0, key.1))); + cache.wait(key); + } + cache.synchronize(&map); + assert_eq!(cache.start_ticking(|k| k == (0, 0)), vec![(0, 0)]); + assert!(cache.start_ticking(|k| k == (0, 0)).is_empty()); + map.remove(&(1, 0)); + cache.synchronize(&map); + let mut started = cache.start_ticking(|_| true); + started.sort_unstable(); + assert_eq!(started, vec![(2, 0)]); + } + #[test] fn scheduler_keeps_saved_ticks_on_stable_membership_and_removes_unloaded_chunks() { use horizon_core::{ diff --git a/crates/horizon-client/src/ticket_levels.rs b/crates/horizon-client/src/ticket_levels.rs new file mode 100644 index 000000000..216815de1 --- /dev/null +++ b/crates/horizon-client/src/ticket_levels.rs @@ -0,0 +1,232 @@ +//! Which chunks tick, from the chunk tickets of `DistanceManager`. +//! +//! Every player holds two kinds of ticket: +//! - `PLAYER_LOADING` at level 31 (`ENTITY_TICKING`) on every chunk within +//! the server's view distance (Chebyshev), from `PlayerTicketTracker`; +//! - `PLAYER_SIMULATION` at level `31 - simulationDistance` on its own chunk. +//! +//! A `/forceload`ed chunk holds a `FORCED` ticket at level 31 of both kinds. +//! Levels rise by one per chunk away from a ticket (`ChunkTracker`) and each +//! chunk takes the lowest. The loading level gives the chunk's +//! `FullChunkStatus` (`ChunkLevel.fullStatus`: 31 entity ticking, 32 block +//! ticking, 33 full) and the simulation level gives what +//! `inEntityTickingRange` (31 or less) and `inBlockTickingRange` (32 or less) +//! answer. Vanilla needs both: +//! - entities tick where both levels are entity ticking (`ServerLevel.tick`, +//! and `EntityTickList` holds only the entities of entity-ticking chunks); +//! - random ticks run in the simulation tracker's entity-ticking chunks that +//! have a ticking chunk (`ChunkMap.forEachBlockTickingChunk`); +//! - scheduled ticks, block events and block entities run where both are +//! block ticking (`isPositionTickingWithEntitiesLoaded`, +//! `shouldTickBlocksAt`, `LevelChunk.isTicking`). +//! +//! Whoever the players are (the local player, LAN guests, a dedicated +//! server's players), they count the same. +use crate::fast_hash::FxHashMap; +use std::sync::Arc; + +/// `ChunkLevel`'s levels. +pub const ENTITY_TICKING: u8 = 31; +pub const BLOCK_TICKING: u8 = 32; +/// What a chunk with no ticket near it has (`FULL` and above count as none). +const NONE: (u8, u8) = (BLOCK_TICKING + 1, BLOCK_TICKING + 1); + +/// The tickets of one level: where its players are, its forced chunks, and +/// the server's view and simulation distances. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Sources { + pub players: Vec<(i32, i32)>, + pub forced: Vec<(i32, i32)>, + pub view_distance: i32, + pub simulation_distance: i32, +} + +/// Each chunk's (loading, simulation) level, for the chunks where either is +/// block ticking or lower; `None` ticks everywhere (a game with no server and +/// no player: the headless fixtures). +#[derive(Clone, Default)] +pub struct Levels(Option<Arc<FxHashMap<(i32, i32), (u8, u8)>>>); + +impl Levels { + /// Chunk coordinates. + fn get(&self, x: i32, z: i32) -> Option<(u8, u8)> { + let map = self.0.as_ref()?; + Some(map.get(&(x, z)).copied().unwrap_or(NONE)) + } + /// `DistanceManager.inEntityTickingRange`, in an entity-ticking chunk: + /// where entities tick. + pub fn entity_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= ENTITY_TICKING && s <= ENTITY_TICKING) + } + /// `inBlockTickingRange` in a block-ticking chunk: where scheduled ticks, + /// block events and block entities run. + pub fn block_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= BLOCK_TICKING) + } + /// `inEntityTickingRange` in a block-ticking chunk: where random ticks run. + pub fn random_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z) + .is_none_or(|(l, s)| l <= BLOCK_TICKING && s <= ENTITY_TICKING) + } + /// `ChunkHolder.getFullStatus` is block ticking or more: the chunk's + /// ticking future can complete (its saved ticks unpack then). + pub fn loaded_ticking(&self, x: i32, z: i32) -> bool { + self.get(x, z).is_none_or(|(l, _)| l <= BLOCK_TICKING) + } + /// The same as [`Self::entity_ticking`] at a block position. + pub fn entity_ticking_at(&self, x: i32, z: i32) -> bool { + self.entity_ticking(x >> 4, z >> 4) + } + /// The same as [`Self::block_ticking`] at a block position. + pub fn block_ticking_at(&self, x: i32, z: i32) -> bool { + self.block_ticking(x >> 4, z >> 4) + } +} + +/// The levels, rebuilt only when their sources change (a player crossing +/// into another chunk, a distance or a forced chunk changing). +#[derive(Default)] +pub struct ChunkTickets { + sources: Option<Sources>, + levels: Levels, +} + +impl ChunkTickets { + /// `None`: tick everywhere. + pub fn update(&mut self, mut sources: Option<Sources>) { + if let Some(s) = sources.as_mut() { + s.players.sort_unstable(); + s.players.dedup(); + s.forced.sort_unstable(); + } + if sources == self.sources { + return; + } + self.levels = Levels(sources.as_ref().map(|s| Arc::new(compute(s)))); + self.sources = sources; + } + pub fn levels(&self) -> Levels { + self.levels.clone() + } +} + +fn compute(s: &Sources) -> FxHashMap<(i32, i32), (u8, u8)> { + let view = s.view_distance.clamp(0, 32); + let simulation = s.simulation_distance.clamp(0, 32); + let mut levels: FxHashMap<(i32, i32), (u8, u8)> = FxHashMap::default(); + let mut lower = |key, loading: i32, sim: i32| { + let e = levels.entry(key).or_insert(NONE); + e.0 = e.0.min(loading.min(i32::from(NONE.0)) as u8); + e.1 = e.1.min(sim.min(i32::from(NONE.1)) as u8); + }; + // PLAYER_LOADING within the view distance, PLAYER_SIMULATION at the + // player's chunk (`getPlayerTicketLevel`: never below 0). + let player_sim = (i32::from(ENTITY_TICKING) - simulation).max(0); + let reach = (view + 1).max(i32::from(BLOCK_TICKING) - player_sim); + for &(px, pz) in &s.players { + for dz in -reach..=reach { + for dx in -reach..=reach { + let d = dx.abs().max(dz.abs()); + lower( + (px + dx, pz + dz), + i32::from(ENTITY_TICKING) + (d - view).max(0), + player_sim + d, + ); + } + } + } + for &(fx, fz) in &s.forced { + for dz in -1i32..=1 { + for dx in -1i32..=1 { + let level = i32::from(ENTITY_TICKING) + dx.abs().max(dz.abs()); + lower((fx + dx, fz + dz), level, level); + } + } + } + levels.retain(|_, l| *l != NONE); + levels +} + +#[cfg(test)] +mod tests { + use super::*; + + fn levels(players: &[(i32, i32)], forced: &[(i32, i32)], view: i32, sim: i32) -> Levels { + let mut t = ChunkTickets::default(); + t.update(Some(Sources { + players: players.to_vec(), + forced: forced.to_vec(), + view_distance: view, + simulation_distance: sim, + })); + t.levels() + } + + #[test] + fn simulation_distance_inside_the_view() { + // view 8, simulation 4: entities and random ticks out to 4 chunks, + // scheduled ticks out to 5. + let l = levels(&[(0, 0)], &[], 8, 4); + assert!(l.entity_ticking(4, -4) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(-4, 4) && !l.random_ticking(0, 5)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + assert!(l.loaded_ticking(9, 9) && !l.loaded_ticking(10, 0)); + } + + #[test] + fn view_distance_inside_the_simulation() { + // view 4, simulation 10: what isn't loaded at entity ticking (beyond + // the view distance) runs no entities, and block ticks stop where the + // chunk is only full (beyond the view distance + 1). + let l = levels(&[(0, 0)], &[], 4, 10); + assert!(l.entity_ticking(4, 0) && !l.entity_ticking(5, 0)); + assert!(l.random_ticking(5, 0) && !l.random_ticking(6, 0)); + assert!(l.block_ticking(5, 5) && !l.block_ticking(6, 0)); + } + + #[test] + fn every_player_and_forced_chunk() { + let l = levels(&[(0, 0), (40, 0)], &[(-100, 7)], 4, 4); + assert!(l.entity_ticking(44, 0) && l.entity_ticking(0, -4)); + assert!(!l.entity_ticking(20, 0)); + // A forced chunk entity ticks, its neighbours only block tick. + assert!(l.entity_ticking(-100, 7) && !l.entity_ticking(-101, 7)); + assert!(l.block_ticking(-101, 8) && !l.block_ticking(-102, 7)); + assert!(!l.random_ticking(-101, 7)); + assert!(l.entity_ticking_at(-1600, 112) && !l.block_ticking_at(-1617, 112)); + } + + #[test] + fn no_tickets_tick_nothing_and_no_sources_everything() { + let none = levels(&[], &[], 10, 10); + assert!(!none.block_ticking(0, 0) && !none.entity_ticking(0, 0)); + let everywhere = ChunkTickets::default().levels(); + assert!(everywhere.random_ticking(1000, -1000)); + } + + #[test] + fn rebuilt_only_when_sources_change() { + let mut t = ChunkTickets::default(); + let s = |players: Vec<(i32, i32)>| { + Some(Sources { + players, + forced: Vec::new(), + view_distance: 2, + simulation_distance: 2, + }) + }; + t.update(s(vec![(0, 0), (5, 5)])); + let first = t.levels(); + t.update(s(vec![(5, 5), (0, 0)])); + assert!(Arc::ptr_eq( + first.0.as_ref().unwrap(), + t.levels().0.as_ref().unwrap() + )); + t.update(s(vec![(1, 0), (5, 5)])); + assert!(t.levels().entity_ticking(3, 0) && !first.entity_ticking(3, 0)); + t.update(None); + assert!(t.levels().0.is_none()); + } +} diff --git a/crates/horizon-client/src/world.rs b/crates/horizon-client/src/world.rs index efcbf9591..af7c1671b 100644 --- a/crates/horizon-client/src/world.rs +++ b/crates/horizon-client/src/world.rs @@ -8,6 +8,46 @@ use std::{ sync::Arc, }; +/// Sections (x, section index, z) waiting to be remeshed, kept by column +/// (a bit per section index), so the mesh scheduler looks at each column once +/// rather than at every section of it. +#[derive(Clone, Debug, Default)] +pub struct DirtySections { + columns: crate::fast_hash::FxHashMap<(i32, i32), u32>, +} +const _: () = assert!(SECTIONS <= 32); +impl DirtySections { + pub fn insert(&mut self, (x, sy, z): (i32, i32, i32)) { + debug_assert!((0..SECTIONS as i32).contains(&sy)); + *self.columns.entry((x, z)).or_default() |= 1 << sy; + } + pub fn contains(&self, &(x, sy, z): &(i32, i32, i32)) -> bool { + (0..SECTIONS as i32).contains(&sy) + && self.columns.get(&(x, z)).is_some_and(|m| m & 1 << sy != 0) + } + /// The dirty section indexes of column (x, z), as bits, removed. + pub fn take_column(&mut self, x: i32, z: i32) -> u32 { + self.columns.remove(&(x, z)).unwrap_or(0) + } + /// Keep the columns `keep` accepts. + pub fn retain_columns(&mut self, mut keep: impl FnMut(i32, i32) -> bool) { + self.columns.retain(|&(x, z), _| keep(x, z)); + } + /// The columns holding dirty sections, with their section bits. + pub fn columns(&self) -> impl Iterator<Item = ((i32, i32), u32)> + '_ { + self.columns.iter().map(|(&c, &m)| (c, m)) + } + pub fn clear(&mut self) { + self.columns.clear(); + } + pub fn is_empty(&self) -> bool { + self.columns.is_empty() + } + /// How many sections are dirty. + pub fn len(&self) -> usize { + self.columns.values().map(|m| m.count_ones() as usize).sum() + } +} pub struct World { pub fast_lava: bool, pub chunks: crate::chunk_map::ChunkMap, @@ -16,7 +56,7 @@ pub struct World { pub health_rules: crate::health::HealthRules, pub air: BlockStateId, /// Sections whose geometry changed and need remeshing. - pub dirty_sections: crate::fast_hash::FxHashSet<(i32, i32, i32)>, + pub dirty_sections: DirtySections, /// Chunks whose light must be recomputed. pub dirty_light: crate::fast_hash::FxHashSet<(i32, i32)>, /// Edits on lit chunks (position, old state, new state), relit @@ -143,7 +183,11 @@ impl World { } /// A controlled blockstate scene for the native scene probes: material /// layers, a stepped pyramid and the model gallery. Not generated terrain. - pub fn test_scene(assets: &crate::assets::Assets, radius: i32) -> crate::Result<Self> { + pub fn test_scene( + assets: &crate::assets::Assets, + render: &crate::assets::RenderAssets, + radius: i32, + ) -> crate::Result<Self> { let air = assets .registry .default_state("minecraft:air") @@ -188,7 +232,7 @@ impl World { } } } - for (position, state) in &assets.model_placements { + for (position, state) in &render.model_placements { world.set(position.x, position.y, position.z, *state)?; } world.revision = 0; @@ -243,6 +287,13 @@ impl World { } Ok(()) } + /// `getHeight(Heightmap.Types.WORLD_SURFACE, x, z)`: one above the highest + /// block that isn't `air`, or `MIN_Y` (also where the chunk isn't loaded). + pub fn world_surface(&self, x: i32, z: i32, air: impl Fn(BlockStateId) -> bool) -> i32 { + self.chunks.get(&(x >> 4, z >> 4)).map_or(MIN_Y, |chunk| { + chunk.world_surface(x, z, |v| air(BlockStateId(v))) + }) + } pub fn block(&self, x: i32, y: i32, z: i32) -> BlockStateId { self.chunks .get(&(x >> 4, z >> 4)) diff --git a/crates/horizon-client/tests/generation_saves.rs b/crates/horizon-client/tests/generation_saves.rs index 26da11efe..ce91a1096 100644 --- a/crates/horizon-client/tests/generation_saves.rs +++ b/crates/horizon-client/tests/generation_saves.rs @@ -170,13 +170,15 @@ fn chunks_left_behind_keep_their_decoration() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets, + render: render.clone(), }); let generator = Arc::new(Recorder::default()); let mut session = Session::new(generator.clone(), context.clone()); diff --git a/crates/horizon-client/tests/lan_bot.rs b/crates/horizon-client/tests/lan_bot.rs index 7a8209939..18af20343 100644 --- a/crates/horizon-client/tests/lan_bot.rs +++ b/crates/horizon-client/tests/lan_bot.rs @@ -181,6 +181,8 @@ impl Server { sprinting: false, equipment: Default::default(), health: 20.0, + attributes: Vec::new(), + living_flags: 0, }; let mut ctx = TickCtx { world: &mut self.world, @@ -422,17 +424,40 @@ fn guests_see_each_other_and_the_world_entities() { data: 0, meta: Vec::new(), equipment: Vec::new(), + attributes: Vec::new(), precise: false, }; let first = thread::spawn(move || { let mut bot = connect(port, "Alex", false)?; + bot.c + .reader + .set_read_timeout(Some(Duration::from_millis(200))) + .unwrap(); let mut zombies = 0; let mut players = 0; let mut moves = 0; + let mut at: Option<[f64; 3]> = None; + let mut reminder = Instant::now(); let deadline = Instant::now() + Duration::from_secs(20); while Instant::now() < deadline && !(zombies > 0 && players > 0 && moves > 0) { - match bot.recv_play()? { + // A vanilla client sends its position at least every 20 ticks even + // when standing still (LocalPlayer's positionReminder), and the + // server checks which entities it sees again on each one. + if let Some([x, y, z]) = at + && reminder.elapsed() >= Duration::from_secs(1) + { + bot.send(S::MovePlayerPos(play::MovePlayerPos { x, y, z, flags: 1 })); + reminder = Instant::now(); + } + let Ok((id, payload)) = bot.c.recv() else { + continue; + }; + let Ok(packet) = C::decode(id, &payload) else { + continue; + }; + match packet { C::PlayerPosition(p) => { + at = Some(p.position); bot.send(S::AcceptTeleportation(play::AcceptTeleportation { id: p.teleport, x: p.position[0], diff --git a/crates/horizon-client/tests/streaming_meshes.rs b/crates/horizon-client/tests/streaming_meshes.rs index 6804d197e..3aa30a330 100644 --- a/crates/horizon-client/tests/streaming_meshes.rs +++ b/crates/horizon-client/tests/streaming_meshes.rs @@ -55,13 +55,15 @@ fn columns_loaded_past_the_render_distance_mesh_when_they_come_in_range() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets, + render: render.clone(), }); let mut streaming = Streaming::new(Arc::new(Saved), context, 3); streaming.radius = 4; @@ -135,13 +137,15 @@ fn relit_columns_keep_every_mesh_current() { return; }; let assets = Arc::new(Assets::load(&root).unwrap()); + let render = Arc::new(assets.reload(&root).unwrap()); let facts = BlockFacts::load(&root, assets.registry).unwrap(); let visibility = models::load_visibility(&root, assets.registry).unwrap(); let context = Arc::new(WorkerContext { - tables: Arc::new(MeshTables::new(&assets, &facts, visibility).unwrap()), + tables: Arc::new(MeshTables::new(&assets, &render, &facts, visibility).unwrap()), light: Arc::new(LightTables::load(&root, assets.registry, &facts).unwrap()), biomes: Arc::new(Biomes::load(&root).unwrap()), assets: assets.clone(), + render: render.clone(), }); let state = |name: &str| assets.registry.default_state(name).unwrap().0; let (stone, glowstone, torch) = ( @@ -149,8 +153,9 @@ fn relit_columns_keep_every_mesh_current() { state("minecraft:glowstone"), state("minecraft:torch"), ); - // Columns from a server, one of them never sent: its neighbours stay - // unlit, next to lit columns within the render distance. + // Columns from a server, one of them not sent yet. They keep the light + // the server sent (#824, as vanilla's `enableChunkLight`), so its + // neighbours are lit too. let mut streaming = Streaming::new(Arc::new(Saved), context.clone(), 3); streaming.radius = 4; streaming.remote = true; @@ -176,7 +181,7 @@ fn relit_columns_keep_every_mesh_current() { } }; settle(&mut streaming, &mut world); - assert!(!streaming.is_lit(1, 0) && streaming.is_lit(0, 0)); + assert!(streaming.is_lit(1, 0) && streaming.is_lit(0, 0)); // Open the roof and put torches in the cave on a ring two blocks inside // the unlit (1, 0): its lit neighbours are relit, and their meshes change // only through light (no edit is next to them). @@ -210,6 +215,7 @@ fn relit_columns_keep_every_mesh_current() { cutout_leaves: true, cull_leaves: false, assets: &context.assets, + render: &context.render, tables: &context.tables, biomes: &context.biomes, visibility: context.tables.visibility.clone(), diff --git a/crates/horizon-core/src/biome.rs b/crates/horizon-core/src/biome.rs index 4f8c9ff54..96baeda4b 100644 --- a/crates/horizon-core/src/biome.rs +++ b/crates/horizon-core/src/biome.rs @@ -22,20 +22,86 @@ impl BiomeZoom { } /// Choose the closest of eight jittered quart corners, preserving vanilla's /// corner order, strict tie comparison and signed coordinate wrapping. + /// + /// Each corner re-derives its distance from a fresh six-step mix driven by + /// the quart coordinate. The first two steps depend only on the X and Y + /// offsets, so those shared prefixes are mixed once (two X states, then four + /// XY states) instead of eight times, and the six-step tail is evaluated for + /// all eight corners. Since `next(m, salt + offset) == next(m, salt) + + /// offset`, each coordinate is folded into its step with one addition. pub fn quart_at_block(self, block: BlockPos) -> [i32; 3] { let shifted = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2)); let base = shifted.map(|v| v >> 2); let fractions = shifted.map(|v| f64::from(v & 3) / 4.); + let coordinate = base.map(i64::from); + let seed = self.seed; + const A: i64 = 6364136223846793005; + const B: i64 = 1442695040888963407; + let g = |m: i64| m.wrapping_mul(m.wrapping_mul(A).wrapping_add(B)); + let root = g(seed); + let m0: [i64; 2] = + std::array::from_fn(|x: usize| root.wrapping_add(coordinate[0].wrapping_add(x as i64))); + let m1: [[i64; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + g(m0[x]).wrapping_add(coordinate[1].wrapping_add(y as i64)) + }) + }); + let m2: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m1[x][y]).wrapping_add(coordinate[2].wrapping_add(z as i64)) + }) + }) + }); + let m3: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m2[x][y][z]).wrapping_add(coordinate[0].wrapping_add(x as i64)) + }) + }) + }); + let m4: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m3[x][y][z]).wrapping_add(coordinate[1].wrapping_add(y as i64)) + }) + }) + }); + let m5: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| { + g(m4[x][y][z]).wrapping_add(coordinate[2].wrapping_add(z as i64)) + }) + }) + }); + let m6: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| g(m5[x][y][z]).wrapping_add(seed)) + }) + }); + let m7: [[[i64; 2]; 2]; 2] = std::array::from_fn(|x: usize| { + std::array::from_fn(|y: usize| { + std::array::from_fn(|z: usize| g(m6[x][y][z]).wrapping_add(seed)) + }) + }); let mut selected = base; let mut best = f64::INFINITY; - for corner in 0..8 { - let offsets = [(corner >> 2) & 1, (corner >> 1) & 1, corner & 1]; - let quart = std::array::from_fn(|i| base[i].wrapping_add(offsets[i])); - let delta = std::array::from_fn(|i| fractions[i] - f64::from(offsets[i])); - let distance = fiddled_distance(self.seed, quart, delta); - if best > distance { - best = distance; - selected = quart; + for x in 0..2 { + for y in 0..2 { + for z in 0..2 { + let dx = fractions[0] - x as f64 + fiddle(m5[x][y][z]); + let dy = fractions[1] - y as f64 + fiddle(m6[x][y][z]); + let dz = fractions[2] - z as f64 + fiddle(m7[x][y][z]); + let distance = dz * dz + dy * dy + dx * dx; + if best > distance { + best = distance; + selected = [ + base[0].wrapping_add(x as i32), + base[1].wrapping_add(y as i32), + base[2].wrapping_add(z as i32), + ]; + } + } } } selected @@ -50,25 +116,112 @@ pub fn noise_quart_at_block(block: BlockPos) -> [i32; 3] { pub fn noise_quart_at_position(position: [f64; 3]) -> [i32; 3] { position.map(|v| (v.floor() as i32) >> 2) } -fn next(seed: i64, salt: i64) -> i64 { - seed.wrapping_mul( - seed.wrapping_mul(6364136223846793005) - .wrapping_add(1442695040888963407), - ) - .wrapping_add(salt) -} fn fiddle(seed: i64) -> f64 { (((seed >> 24) & 1023) as f64 / 1024. - 0.5) * 0.9 } -fn fiddled_distance(seed: i64, quart: [i32; 3], delta: [f64; 3]) -> f64 { - let mut mixed = seed; - for coordinate in quart.into_iter().cycle().take(6) { - mixed = next(mixed, i64::from(coordinate)); + +#[cfg(test)] +mod tests { + use super::*; + + /// The straightforward per-corner formulation, kept as the parity oracle + /// for the prefix-shared implementation. + fn reference(seed: i64, block: BlockPos) -> [i32; 3] { + let shifted = [block.x, block.y, block.z].map(|v| v.wrapping_sub(2)); + let base = shifted.map(|v| v >> 2); + let fractions = shifted.map(|v| f64::from(v & 3) / 4.); + let mut selected = base; + let mut best = f64::INFINITY; + for corner in 0..8 { + let offsets = [(corner >> 2) & 1, (corner >> 1) & 1, corner & 1]; + let quart: [i32; 3] = std::array::from_fn(|i| base[i].wrapping_add(offsets[i])); + let delta: [f64; 3] = std::array::from_fn(|i| fractions[i] - f64::from(offsets[i])); + let mut mixed = seed; + for coordinate in quart.into_iter().cycle().take(6) { + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(i64::from(coordinate)); + } + let x = delta[0] + fiddle(mixed); + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(seed); + let y = delta[1] + fiddle(mixed); + mixed = mixed + .wrapping_mul( + mixed + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ) + .wrapping_add(seed); + let z = delta[2] + fiddle(mixed); + let distance = z * z + y * y + x * x; + if best > distance { + best = distance; + selected = quart; + } + } + selected + } + + #[test] + fn quart_at_block_matches_reference() { + let seeds = [ + 0i64, + 1, + -1, + i64::MIN, + i64::MAX, + 0x0123_4567_89ab_cdef, + -0x0123_4567_89ab_cdef, + ]; + let extremes = [ + i32::MIN, + i32::MIN + 1, + -1, + 0, + 1, + 2, + 3, + 4, + -2, + i32::MAX - 1, + i32::MAX, + ]; + for &seed in &seeds { + let zoom = BiomeZoom::new(seed); + for x in -34..34 { + for y in -34..34 { + for z in -34..34 { + let block = BlockPos::new(x, y, z); + assert_eq!( + zoom.quart_at_block(block), + reference(seed, block), + "seed {seed} at {x} {y} {z}" + ); + } + } + } + for &x in &extremes { + for &y in &extremes { + for &z in &extremes { + let block = BlockPos::new(x, y, z); + assert_eq!( + zoom.quart_at_block(block), + reference(seed, block), + "seed {seed} at {x} {y} {z}" + ); + } + } + } + } } - let x = delta[0] + fiddle(mixed); - mixed = next(mixed, seed); - let y = delta[1] + fiddle(mixed); - mixed = next(mixed, seed); - let z = delta[2] + fiddle(mixed); - z * z + y * y + x * x } diff --git a/crates/horizon-core/src/density/mod.rs b/crates/horizon-core/src/density/mod.rs index 6bc84a8d1..f4ee1af49 100644 --- a/crates/horizon-core/src/density/mod.rs +++ b/crates/horizon-core/src/density/mod.rs @@ -103,6 +103,13 @@ impl SamplerContext { self.scratch.push(buffer); result } + /// Start an independent evaluation, retaining only temporary scratch buffers. + /// Cached scalar/volume results and world bindings must not cross chunks or + /// graphs, whose cache IDs can refer to different functions. + pub fn reset(&mut self) { + self.caches = self.caches.as_ref().map(|_| Vec::new()); + self.fields = WorldFields::default(); + } /// Release retained storage between worlds or after unusually large work. pub fn clear_scratch(&mut self) { self.scratch.clear(); diff --git a/crates/horizon-core/src/density/tests.rs b/crates/horizon-core/src/density/tests.rs index 77a643097..9fad8bc4f 100644 --- a/crates/horizon-core/src/density/tests.rs +++ b/crates/horizon-core/src/density/tests.rs @@ -755,3 +755,73 @@ fn spline_lazy_branch_failure_preserves_completed_output_and_returns_scratch() { assert_eq!(context.scratch.len(), 2); assert_eq!(sampler.sample_value(&mut context, [0; 3]), Ok(7.0)); } + +#[test] +fn reset_retains_scratch_but_discards_graph_caches_and_world_bindings() { + let binding = Arc::new(ConstantSampler(17.0)); + let lifetime = Arc::downgrade(&binding); + let mut context = SamplerContext::cached() + .with_world_fields(WorldFields::default().with_field(WorldField::Beardifier, binding)); + let cached = CachingDensitySampler::new( + 0, + Arc::new(ContextBoundSampler::new(WorldField::Beardifier)), + ) + .unwrap(); + let volume = DensityVolume::new([2; 3], [0; 3], [1; 3]).unwrap(); + let mut output = [0.0; 8]; + cached + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [17.0; 8]); + assert_eq!(cached.sample_value(&mut context, [9; 3]), Ok(17.0)); + context + .with_buffer(128, |_, buffer| { + buffer.fill(99.0); + Ok(()) + }) + .unwrap(); + let allocation = context.scratch[0].as_ptr(); + let capacity = context.scratch[0].capacity(); + context.reset(); + assert!(lifetime.upgrade().is_none()); + assert!(context.caches.as_ref().unwrap().is_empty()); + assert_eq!(context.scratch[0].as_ptr(), allocation); + assert_eq!(context.scratch[0].capacity(), capacity); + // Same coordinates and cache ID must resolve the new context's fallback. + assert_eq!(cached.sample_value(&mut context, [9; 3]), Ok(0.0)); + cached + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [0.0; 8]); + // A different graph may reuse IDs without inheriting scalar/volume results. + context.reset(); + let replacement = CachingDensitySampler::new(0, Arc::new(ConstantSampler(3.0))).unwrap(); + assert_eq!(replacement.sample_value(&mut context, [9; 3]), Ok(3.0)); + replacement + .sample_volume(&mut context, &mut output, volume) + .unwrap(); + assert_eq!(output, [3.0; 8]); +} + +#[test] +fn reset_after_sampling_error_drops_blender_and_preserves_uncached_mode() { + let blender = Arc::new(EmptyBlender); + let lifetime = Arc::downgrade(&blender); + let mut context = + SamplerContext::default().with_world_fields(WorldFields::default().with_blender(blender)); + let result: Result<(), SampleError> = context.with_buffer(64, |_, buffer| { + buffer.fill(42.0); + Err(SampleError::RecursiveCache) + }); + assert_eq!(result, Err(SampleError::RecursiveCache)); + let allocation = context.scratch[0].as_ptr(); + context.reset(); + assert!(lifetime.upgrade().is_none()); + assert!(context.caches.is_none()); + context + .with_buffer(32, |_, buffer| { + assert_eq!(buffer.as_ptr(), allocation); + Ok(()) + }) + .unwrap(); +} diff --git a/crates/horizon-core/src/paletted.rs b/crates/horizon-core/src/paletted.rs index 5c0ec374c..3d56bb987 100644 --- a/crates/horizon-core/src/paletted.rs +++ b/crates/horizon-core/src/paletted.rs @@ -151,33 +151,85 @@ fn write(words: &mut [u64], bits: u8, i: usize, value: u32) { let (word, shift) = locate(bits, i); words[word] = (words[word] & !(mask(bits) << shift)) | (u64::from(value) << shift); } +/// Values below this are looked up in a table indexed by value once a +/// palette outgrows the scan: every block state and biome id of 26.3. +const DENSE_VALUES: u32 = 1 << 16; +thread_local! { + /// `palette_ids`' table: 1 + the id of each value seen, 0 for the others. + /// Only the entries of the palette being built are set, and they are + /// cleared again before it returns. + static DENSE_IDS: std::cell::RefCell<Vec<u32>> = const { std::cell::RefCell::new(Vec::new()) }; +} /// The distinct `values` in first-occurrence order and each value's index in -/// them. Up to 16 distinct values a scan finds them faster than hashing. +/// them. A run of one value (most of a section) is matched once, a scan finds +/// up to 16 distinct values faster than any lookup, and past that a table +/// indexed by value finds them without hashing. fn palette_ids(values: &[u32]) -> (Vec<u32>, Vec<u32>) { let mut palette: Vec<u32> = Vec::new(); - let mut small = true; - let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new(); let mut ids = Vec::with_capacity(values.len()); - for &value in values { - let id = if small { - match palette.iter().position(|&v| v == value) { + let mut last: Option<(u32, u32)> = None; + let mut rest = values; + while let Some((&value, tail)) = rest.split_first() { + let id = match last { + Some((v, id)) if v == value => id, + _ if palette.len() > 16 => break, + _ => match palette.iter().position(|&v| v == value) { Some(id) => id as u32, None => { palette.push(value); - if palette.len() > 16 { - small = false; - lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32))); - } palette.len() as u32 - 1 } + }, + }; + last = Some((value, id)); + ids.push(id); + rest = tail; + } + if rest.is_empty() { + return (palette, ids); + } + if palette.iter().chain(rest).all(|&v| v < DENSE_VALUES) { + DENSE_IDS.with(|table| { + let mut table = table.borrow_mut(); + for (id, &v) in palette.iter().enumerate() { + let v = v as usize; + if table.len() <= v { + table.resize(v + 1, 0); + } + table[v] = id as u32 + 1; } - } else { - *lookup.entry(value).or_insert_with(|| { + for &value in rest { + let v = value as usize; + if table.len() <= v { + table.resize(v + 1, 0); + } + let id = match table[v] { + 0 => { + palette.push(value); + table[v] = palette.len() as u32; + palette.len() as u32 - 1 + } + slot => slot - 1, + }; + ids.push(id); + } + for &v in &palette { + table[v as usize] = 0; + } + }); + } else { + let mut lookup: std::collections::HashMap<u32, u32> = palette + .iter() + .enumerate() + .map(|(i, &v)| (v, i as u32)) + .collect(); + for &value in rest { + let id = *lookup.entry(value).or_insert_with(|| { palette.push(value); palette.len() as u32 - 1 - }) - }; - ids.push(id); + }); + ids.push(id); + } } (palette, ids) } @@ -828,4 +880,135 @@ mod tests { ); } } + + /// The pre-optimization `palette_ids` (scan, then a SipHash map), kept to + /// compare against. + fn baseline_palette_ids(values: &[u32]) -> (Vec<u32>, Vec<u32>) { + let mut palette: Vec<u32> = Vec::new(); + let mut small = true; + let mut lookup: std::collections::HashMap<u32, u32> = std::collections::HashMap::new(); + let mut ids = Vec::with_capacity(values.len()); + for &value in values { + let id = if small { + match palette.iter().position(|&v| v == value) { + Some(id) => id as u32, + None => { + palette.push(value); + if palette.len() > 16 { + small = false; + lookup.extend(palette.iter().enumerate().map(|(i, &v)| (v, i as u32))); + } + palette.len() as u32 - 1 + } + } + } else { + *lookup.entry(value).or_insert_with(|| { + palette.push(value); + palette.len() as u32 - 1 + }) + }; + ids.push(id); + } + (palette, ids) + } + /// Sections like the ones saved: stone, ores and caves under dirt, grass + /// and air; a mixed surface (plants, leaves, logs) in short runs; a + /// global palette; ids past the table; and biomes. + fn palette_cases() -> Vec<(&'static str, Vec<u32>)> { + let mut state = 0x9E37_79B9_7F4A_7C15u64; + let mut terrain = Vec::with_capacity(4096); + for i in 0..4096u32 { + let y = i >> 8; + let r = rng(&mut state); + terrain.push(match y { + 0..=8 if r % 40 == 0 => 2000 + (r >> 8) as u32 % 6, + 0..=8 if r % 13 == 0 => 0, + 0..=8 => 1, + 9..=10 => 10, + 11 => 9, + _ => 0, + }); + } + let mut surface = Vec::with_capacity(4096); + while surface.len() < 4096 { + let r = rng(&mut state); + let run = 1 + (r % 8) as usize; + let v = 100 + ((r >> 8) % 24) as u32 * 37; + surface.extend(std::iter::repeat_n(v, run.min(4096 - surface.len()))); + } + let global: Vec<u32> = (0..4096) + .map(|_| (rng(&mut state) % 600) as u32 * 41) + .collect(); + let large: Vec<u32> = (0..4096) + .map(|i| { + if i % 3 == 0 { + 70_000 + (rng(&mut state) % 40) as u32 + } else { + i as u32 % 20 + } + }) + .collect(); + let biomes: Vec<u32> = (0..64).map(|i| [3, 3, 3, 7, 7, 12][i % 6]).collect(); + vec![ + ("terrain", terrain), + ("surface", surface), + ("global", global), + ("large ids", large), + ("biomes", biomes), + ("single", vec![5; 4096]), + ("seventeen", (0..4096).map(|i| (i % 17) as u32).collect()), + ] + } + #[test] + fn palette_ids_match_first_occurrence_order() { + for (name, values) in palette_cases() { + assert_eq!( + palette_ids(&values), + baseline_palette_ids(&values), + "{name}" + ); + // The table is left clean for the next section. + assert_eq!( + palette_ids(&values), + baseline_palette_ids(&values), + "{name} again" + ); + } + DENSE_IDS.with(|t| assert!(t.borrow().iter().all(|&slot| slot == 0))); + } + /// `palette_ids` against the pre-optimization implementation over the + /// cases above. 25 measured rounds alternate order and report the median + /// microseconds per call. + #[test] + #[ignore = "microbenchmark; run with --ignored --nocapture"] + fn benchmark_palette_ids() { + use std::{hint::black_box, time::Instant}; + for (name, values) in palette_cases() { + 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..500 { + if optimized { + black_box(palette_ids(black_box(&values))); + } else { + black_box(baseline_palette_ids(black_box(&values))); + } + } + if round > 0 { + times[usize::from(optimized)] + .push(started.elapsed().as_secs_f64() * 1e6 / 500.0); + } + } + } + for t in &mut times { + t.sort_by(f64::total_cmp); + } + let (base, new) = (times[0][times[0].len() / 2], times[1][times[1].len() / 2]); + println!( + "palette_ids {name}: baseline {base:.2} us, new {new:.2} us, {:.2}x", + base / new + ); + } + } } diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index c73570684..0cf36b88b 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -205,6 +205,29 @@ pub fn upgrade_recipe(recipe: &mut Value) -> bool { true } +/// Block and item ids vanilla renamed after 1.21.1, as its datafixers +/// rename them in worlds (DataVersion 4541: the chain became the iron chain +/// when copper chains came in). A data file naming the old id fails to load +/// in 26.3: a recipe, a loot entry, a processor's block match. +const RENAMED_IDS: [(&str, &str); 1] = [("minecraft:chain", "minecraft:iron_chain")]; + +/// Every string of a data file that is a renamed id ([`RENAMED_IDS`]) set to +/// the new one, in place; whether any was. +pub fn renamed_ids(v: &mut Value) -> bool { + match v { + Value::String(s) => match RENAMED_IDS.iter().find(|(old, _)| s == old) { + Some((_, new)) => { + *s = (*new).to_owned(); + true + } + None => false, + }, + Value::Array(a) => a.iter_mut().fold(false, |c, x| renamed_ids(x) | c), + Value::Object(o) => o.values_mut().fold(false, |c, x| renamed_ids(x) | c), + _ => false, + } +} + /// A 1.21.1 loot table in 26.3's shape, in place: `conditions` lists become /// one `condition` (`all_of` for several), `functions` become `modifier`, /// and conditions and functions name their kind in `type`. A tool match on @@ -320,7 +343,15 @@ fn unreadable(name: &str, bytes: &mut Vec<u8>) -> Option<String> { } let value: Value = match serde_json::from_slice(bytes) { Ok(v) => v, - Err(e) => return Some(format!("does not parse as JSON: {e}")), + // Minecraft reads data files with Gson's lenient reader, which skips + // comments: YUNG's pools have them. The carry is plain JSON. + Err(e) => match serde_json::from_slice::<Value>(&without_comments(bytes)) { + Ok(v) => { + *bytes = serde_json::to_vec_pretty(&v).expect("a parsed value serializes"); + v + } + Err(_) => return Some(format!("does not parse as JSON: {e}")), + }, }; let shared_tag = name.starts_with("data/minecraft/tags/") || name.starts_with("data/c/tags/"); if shared_tag && value.get("replace").and_then(Value::as_bool) == Some(true) { @@ -329,15 +360,65 @@ fn unreadable(name: &str, bytes: &mut Vec<u8>) -> Option<String> { None } +/// JSON text without the comments Gson's lenient reader skips: `//` and +/// `#` to the end of the line, and `/* ... */`, outside strings. +fn without_comments(bytes: &[u8]) -> Vec<u8> { + let mut out = Vec::with_capacity(bytes.len()); + let mut i = 0; + let mut string = false; + while i < bytes.len() { + let b = bytes[i]; + if string { + out.push(b); + if b == b'\\' { + out.extend(bytes.get(i + 1)); + i += 1; + } else if b == b'"' { + string = false; + } + i += 1; + continue; + } + match (b, bytes.get(i + 1)) { + (b'"', _) => { + string = true; + out.push(b); + i += 1; + } + (b'/', Some(b'/')) | (b'#', _) => { + while i < bytes.len() && bytes[i] != b'\n' { + i += 1; + } + } + (b'/', Some(b'*')) => { + i += 2; + while i < bytes.len() && !bytes[i..].starts_with(b"*/") { + i += 1; + } + i += 2; + out.push(b' '); + } + _ => { + out.push(b); + i += 1; + } + } + } + out +} + /// Carries `jar` over into `out/carry/`. With the oracle's `facts`, blocks /// and items are the ones the mod registers, with the templates and numbers -/// the facts give; `allowed` says which vanilla blocks the game has. +/// the facts give; `allowed` says which vanilla blocks the game has; +/// `loaded` which mods are ported along, for the conditions of the mod's +/// worldgen modifiers. pub fn carry( jar: &Path, info: &JarInfo, out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, + loaded: &dyn Fn(&str) -> bool, conventions: &BTreeMap<String, Value>, ) -> Result<Report, String> { let id = &info.mod_id; @@ -363,6 +444,8 @@ pub fn carry( let mut block_loot = BTreeSet::new(); let mut biome_conventions = BTreeSet::new(); let set_tags = crate::worldgen::structure_set_tags(&mut zip); + let piece_counts = crate::worldgen::piece_counts(&mut zip); + let processor_data = crate::processors::ProcessorData::read(&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(); @@ -405,12 +488,16 @@ pub fn carry( { if let Ok(mut recipe) = serde_json::from_slice::<Value>(&bytes) { tags_used(&recipe, &mut convention); - if upgrade_recipe(&mut recipe) { + let renamed = renamed_ids(&mut recipe); + let upgraded = upgrade_recipe(&mut recipe); + if upgraded { report.recipes_upgraded += 1; - bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); } else { report.recipes_kept.push(file.to_owned()); } + if upgraded || renamed { + bytes = serde_json::to_vec_pretty(&recipe).unwrap_or(bytes); + } } } else if let Some(kind) = rel .strip_prefix("worldgen/") @@ -422,11 +509,67 @@ pub fn carry( 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) - { + let types = &mut report.worldgen_types; + let carried = crate::processors::carry( + kind, + &mut v, + &processor_data, + &mut types.processors_carried, + ) | crate::processors::rule_tests( + kind, + &mut v, + &mut types.rule_tests_carried, + ); + let mut changed = + crate::worldgen::upgrade(kind, &mut v, types, &set_tags) || carried; + if kind == "structure" { + let path = rel.trim_start_matches("worldgen/structure/"); + let structure = format!("{id}:{}", path.trim_end_matches(".json")); + changed |= crate::worldgen::disables(&structure, &mut v); + changed |= + crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); + } + if changed { bytes = serde_json::to_vec_pretty(&v).unwrap_or(bytes); } } + } else if let Some(path) = rel + .strip_prefix("lithostitched/worldgen_modifier/") + .filter(|_| name.starts_with("data/") && name.ends_with(".json")) + { + // Additions to other sets and pools, as files the game merges. + let modifier = serde_json::from_slice::<Value>(&bytes).ok(); + let types = &mut report.worldgen_types; + if let Some((kind, mut added)) = + modifier.and_then(|v| crate::worldgen::modifier(&v, loaded, types)) + { + crate::processors::carry( + kind, + &mut added, + &processor_data, + &mut types.processors_carried, + ); + crate::processors::rule_tests(kind, &mut added, &mut types.rule_tests_carried); + crate::worldgen::upgrade(kind, &mut added, types, &set_tags); + let to = format!( + "data/{id}/worldgen/{kind}/{}/{path}", + crate::worldgen::ADDED + ); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&added).unwrap_or_default(), + )?; + } + } else if rel.starts_with("trial_spawner/") + && name.starts_with("data/") + && name.ends_with(".json") + { + // Trial spawner configs (Moog's arenas): their mobs' NBT. + if let Ok(mut config) = serde_json::from_slice::<Value>(&bytes) + && crate::processors::upgrade_trial_spawner(&mut config) + { + bytes = serde_json::to_vec_pretty(&config).unwrap_or(bytes); + } } else if rel.starts_with("tags/worldgen/biome/") && name.starts_with("data/") { if let Ok(v) = serde_json::from_slice::<Value>(&bytes) { crate::worldgen::convention_tags(&v, &mut biome_conventions); @@ -441,6 +584,7 @@ pub fn carry( if let Ok(mut table) = serde_json::from_slice::<Value>(&bytes) { let before = table.clone(); upgrade_loot(&mut table); + renamed_ids(&mut table); if table != before { report.loot_tables_upgraded += 1; bytes = serde_json::to_vec_pretty(&table).unwrap_or(bytes); @@ -462,6 +606,35 @@ pub fn carry( } write(&dest, &bytes)?; } + // Entries the mod adds to other structure sets in Java code, for the + // structures it has. + for (file, set, entries) in crate::worldgen::code_set_entries(id) { + let entries: Vec<Value> = entries + .into_iter() + .filter(|(s, _)| { + s.split_once(':').is_some_and(|(ns, path)| { + inside + .join(format!("data/{ns}/worldgen/structure/{path}.json")) + .exists() + }) + }) + .map(|(structure, weight)| json!({"structure": structure, "weight": weight})) + .collect(); + if entries.is_empty() { + continue; + } + let added = &mut report.worldgen_types.added_to; + *added.entry(set.to_owned()).or_default() += entries.len(); + let to = format!( + "data/{id}/worldgen/structure_set/{}/{file}.json", + crate::worldgen::ADDED + ); + let v = json!({"horizon:add_to": set, "structures": entries}); + write( + &inside.join(to), + &serde_json::to_vec_pretty(&v).unwrap_or_default(), + )?; + } // 1.21.4 moved item models behind `items/<name>.json` definitions. for m in &item_models { let def = inside.join(format!("assets/{id}/items/{m}.json")); @@ -682,6 +855,36 @@ mod tests { use super::*; use std::io::Write; + /// YUNG's pools carry comments, which Minecraft's lenient reader skips; + /// the carry holds them as plain JSON. A comment marker inside a string + /// stays, and text that is not JSON without its comments is refused. + #[test] + fn reads_json_with_comments_as_minecraft_does() { + let name = "data/m/worldgen/template_pool/bridge.json"; + let mut bytes = br#"{ + // Pillar w/ chance of unlit beacon + "elements": [ /* one */ {"weight": 20, "location": "m:a//b#c"} ], # done + "fallback": "minecraft:empty" +}"# + .to_vec(); + assert_eq!(unreadable(name, &mut bytes), None); + let v: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!( + v, + json!({"elements": [{"weight": 20, "location": "m:a//b#c"}], + "fallback": "minecraft:empty"}) + ); + let mut plain = br#"{"a": "b\"//"}"#.to_vec(); + assert_eq!(unreadable(name, &mut plain), None); + assert_eq!(plain, br#"{"a": "b\"//"}"#.to_vec()); + let mut broken = b"{\"a\": 1} trailing".to_vec(); + assert!( + unreadable(name, &mut broken) + .unwrap() + .starts_with("does not parse") + ); + } + #[test] fn upgrades_ingredients() { let mut r = json!({"type": "minecraft:crafting_shaped", "pattern": ["##"], @@ -734,6 +937,27 @@ mod tests { assert_eq!(new, glass); } + #[test] + fn renames_ids_vanilla_renamed() { + let mut recipe = json!({"type": "minecraft:crafting_shaped", "pattern": ["c"], + "key": {"c": {"item": "minecraft:chain"}}, "result": {"id": "m:sign", "count": 1}}); + assert!(renamed_ids(&mut recipe)); + assert_eq!(recipe["key"]["c"]["item"], "minecraft:iron_chain"); + let mut rule = json!({"input_predicate": {"predicate_type": "minecraft:block_match", + "block": "minecraft:chain"}, "output_state": {"id": "minecraft:chain", + "properties": {"axis": "y"}}}); + assert!(renamed_ids(&mut rule)); + assert_eq!(rule["input_predicate"]["block"], "minecraft:iron_chain"); + assert_eq!(rule["output_state"]["id"], "minecraft:iron_chain"); + // Only whole ids: other blocks and mods' own chains stay. + let mut other = json!([ + "minecraft:chain_command_block", + "m:chain", + "minecraft:iron_chain" + ]); + assert!(!renamed_ids(&mut other)); + } + #[test] fn templates_from_blockstate_properties() { let door = @@ -832,6 +1056,14 @@ mod tests { r#"{"values": ["gem:gem_block"]}"#, ), ("data/c/tags/item/gems.json", r#"{"values": ["gem:gem"]}"#), + ( + "data/gem/lithostitched/worldgen_modifier/houses.json", + r#"{"type": "lithostitched:add_template_pool_elements", + "template_pools": "minecraft:village/plains/houses", + "elements": [{"weight": 2, "element": {"element_type": "minecraft:single_pool_element", + "location": "gem:hut", "projection": "rigid", + "processors": {"processors": [{"processor_type": "lithostitched:block_swap"}]}}}]}"#, + ), // What the game would refuse: vanilla skips these files alone. ("assets/gem/lang/ry_UA.json", r#"{"item.gem.gem": "Gem"}"#), ("data/gem/tags/item/empty.json", ""), @@ -858,8 +1090,17 @@ mod tests { ); assert_eq!(info.census.classes, 1); let out = dir.join("work/mods/gem"); - let report = carry(&jar, &info, &out, None, &|_| true, &BTreeMap::new()).unwrap(); - assert_eq!(report.copied, 13); + let report = carry( + &jar, + &info, + &out, + None, + &|_| true, + &|_| true, + &BTreeMap::new(), + ) + .unwrap(); + assert_eq!(report.copied, 14); let unreadable: Vec<&str> = report.unreadable.keys().map(String::as_str).collect(); assert_eq!( unreadable, @@ -892,6 +1133,25 @@ mod tests { ) .unwrap(); assert_eq!(recipe["key"]["#"], "gem:gem"); + // A lithostitched pool addition, as a file the game merges, upgraded + // as the mod's own pools are. + let added: Value = serde_json::from_slice( + &fs::read(carried.join("data/gem/worldgen/template_pool/horizon_added/houses.json")) + .unwrap(), + ) + .unwrap(); + assert_eq!( + added["horizon:add_to"], + json!(["minecraft:village/plains/houses"]) + ); + assert_eq!( + added["elements"][0]["element"]["processors"], + json!({"processors": []}) + ); + assert_eq!( + report.worldgen_types.added_to["minecraft:village/plains/houses"], + 1 + ); // Horizon's own reader accepts it: blocks and items declared, files fenced. let package = horizon_mods::Package::read(&carried).unwrap(); diff --git a/crates/horizon-port-pack/src/lib.rs b/crates/horizon-port-pack/src/lib.rs index 0e678fb9a..08f9b273f 100644 --- a/crates/horizon-port-pack/src/lib.rs +++ b/crates/horizon-port-pack/src/lib.rs @@ -14,5 +14,6 @@ pub mod jar; pub mod modrinth; pub mod oracle; pub mod pipeline; +pub mod processors; pub mod report; pub mod worldgen; diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 3afe5b3a3..7152dc921 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -120,13 +120,27 @@ pub fn carry( }); 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() { + let chosen = |r: &inventory::Record| { + if only.is_empty() { r.class == "content" } else { only.contains(&r.key) - }; + } + }; + // The mods ported along (carried now or before), for the conditions of + // the mods' worldgen modifiers. + let ported: BTreeSet<&str> = records + .iter() + .filter(|r| { + r.jar.is_some() && (chosen(r) || work.join("mods").join(&r.key).join("carry").is_dir()) + }) + .filter_map(|r| Some(r.info.as_ref()?.mod_id.as_str())) + .chain(["minecraft"]) + .collect(); + let loaded = |m: &str| ported.contains(m); + let mut done = 0; + for r in &records { + let chosen = chosen(r); let (Some(jar), Some(info)) = (&r.jar, &r.info) else { if chosen && !only.is_empty() { log(format!( @@ -155,6 +169,7 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, + &loaded, &conventions, ) { Ok(report) => { diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs new file mode 100644 index 000000000..5dd9c9730 --- /dev/null +++ b/crates/horizon-port-pack/src/processors.rs @@ -0,0 +1,1309 @@ +//! Structure processors the structure libraries write in Java, carried over +//! as data the game runs: the ones that give spawners their mob. +//! +//! - Moog's Structure Lib's and Repurposed Structures' spawner randomizing +//! processors pick a mob from a weighted list for each spawner. They become +//! `horizon:spawner_mobs` (`horizon_world::worldgen::structure::processor`), +//! with Repurposed's `rs_spawners` list written in. +//! - YUNG's Better Dungeons and Better Desert Temples turn a spawner or a +//! placeholder block into a spawner of a fixed mob. That is vanilla's `rule` +//! processor with an `append_static` block entity. +//! - Moog's vanilla loot swap only acts when its mod's "replace vanilla" +//! preset is on; one that ships off is a no-op and is taken out. +//! - Lithostitched's `reference` runs other processor lists in turn: their +//! processors are written in its place (Choice Theorem's Overhauled +//! Villages builds most of its lists so). Its `apply_random` and +//! `condition` become the game's `horizon:apply_random` and +//! `horizon:condition`, with the lists inside them carried the same way, +//! and its `set_block` (simple or weighted states) `horizon:set_block`. +//! +//! What is not here is taken out of its list later and counted +//! (`worldgen::upgrade`). The entity NBT is written in 26.3's shape (an +//! `equipment` map, not 1.21.1's `HandItems` and `ArmorItems`). +use serde_json::{Value, json}; +use std::{ + collections::{BTreeMap, BTreeSet}, + io::{Read, Seek}, +}; + +/// What the processors read from the mod's own data files. +#[derive(Debug, Default)] +pub struct ProcessorData { + /// Repurposed Structures' `rs_spawners/<path>.json` by id: each mob and + /// its weight, without the weight-0 entries its loader removes. + pub spawners: BTreeMap<String, Vec<(String, f64)>>, + /// Moog's "replace vanilla" presets that are on by default: + /// `(mod id, vanilla_key)`. + pub replace_vanilla: BTreeSet<(String, String)>, + /// The mod's processor lists by id, for Lithostitched's references. + pub lists: BTreeMap<String, Value>, +} + +impl ProcessorData { + pub fn read<R: Read + Seek>(zip: &mut zip::ZipArchive<R>) -> Self { + let mut out = Self::default(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let name = entry.name().to_owned(); + let Some((ns, rest)) = name + .strip_prefix("data/") + .and_then(|r| r.strip_suffix(".json")) + .and_then(|r| r.split_once('/')) + else { + continue; + }; + let spawners = rest.strip_prefix("rs_spawners/"); + let list = rest.strip_prefix("worldgen/processor_list/"); + if spawners.is_none() && list.is_none() && rest != "moogs_structures/replace_vanilla" { + continue; + } + let mut text = String::new(); + let Ok(v) = entry + .read_to_string(&mut text) + .map_err(|_| ()) + .and_then(|_| serde_json::from_str::<Value>(&text).map_err(|_| ())) + else { + continue; + }; + if let Some(path) = list { + out.lists.insert(format!("{ns}:{path}"), v); + continue; + } + if let Some(path) = spawners { + let mobs = v["mobs"] + .as_array() + .into_iter() + .flatten() + .filter_map(|m| Some((m["name"].as_str()?.to_owned(), m["weight"].as_f64()?))) + .filter(|(_, w)| *w != 0.) + .collect(); + out.spawners.insert(format!("{ns}:{path}"), mobs); + continue; + } + for preset in v["presets"].as_array().into_iter().flatten() { + if preset["default_enabled"].as_bool() != Some(true) { + continue; + } + for r in preset["replacements"].as_array().into_iter().flatten() { + if let Some(key) = r["vanilla_key"].as_str() { + out.replace_vanilla.insert((ns.to_owned(), key.to_owned())); + } + } + } + } + out + } +} + +/// Calls `f` on each processor list in a worldgen file: a `processor_list` +/// file, and the inline lists of a template pool's elements (list elements +/// included). Whether any call changed something. +pub fn each_list(kind: &str, v: &mut Value, f: &mut dyn FnMut(&mut Value) -> bool) -> bool { + match kind { + "processor_list" => f(v), + "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 |= f(p); + } + } + } else if let Some(p) = element.get_mut("processors") { + changed |= f(p); + } + } + changed + } + _ => false, + } +} + +/// The processors of a list: `{"processors": [...]}` or a bare list (an id +/// names another file and is left alone). +pub fn processors(list: &mut Value) -> Option<&mut Vec<Value>> { + match list { + Value::Array(a) => Some(a), + Value::Object(o) => o.get_mut("processors").and_then(Value::as_array_mut), + _ => None, + } +} + +/// Rewrites the processors of a worldgen file that have a data form; each is +/// counted by type in `carried`. Whether anything changed. +pub fn carry( + kind: &str, + v: &mut Value, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, +) -> bool { + each_list(kind, v, &mut |list| { + let Some(list) = processors(list) else { + return false; + }; + let (out, changed) = carry_all(std::mem::take(list), data, carried); + *list = out; + changed + }) +} + +/// The processors of one list carried: references written in, then each +/// one with a data form replaced by it. Whether anything changed. +fn carry_all( + list: Vec<Value>, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, +) -> (Vec<Value>, bool) { + let (expanded, mut changed) = references(list, data, carried, 0); + let mut out = Vec::with_capacity(expanded.len()); + for p in expanded { + let kind = p["processor_type"].as_str().unwrap_or_default().to_owned(); + let replacement = match kind.as_str() { + "lithostitched:apply_random" => apply_random(&p, data, carried).map(|p| vec![p]), + "lithostitched:condition" => condition(&p, data, carried).map(|p| vec![p]), + _ => as_data(&kind, &p, data), + }; + match replacement { + Some(replacement) => { + *carried.entry(kind).or_default() += 1; + out.extend(replacement); + changed = true; + } + None => out.push(p), + } + } + (out, changed) +} + +/// A processor list inside a carried processor: an id stays (the game reads +/// that file, carried on its own); an inline one is carried here. +fn nested(list: &Value, data: &ProcessorData, carried: &mut BTreeMap<String, usize>) -> Value { + let mut list = list.clone(); + if let Some(ps) = processors(&mut list) { + *ps = carry_all(std::mem::take(ps), data, carried).0; + } + list +} + +/// Lithostitched's `apply_random` as `horizon:apply_random`: its weighted +/// lists, or its set of lists at weight 1. A tag is not carried. +fn apply_random( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, +) -> Option<Value> { + let lists = &p["processor_lists"]; + let weighted = lists.as_array().is_some_and(|a| { + a.iter() + .all(|e| e.get("weight").is_some() && e.get("data").is_some()) + }); + let entries: Vec<(Value, Value)> = if weighted { + lists + .as_array()? + .iter() + .map(|e| (e["weight"].clone(), e["data"].clone())) + .collect() + } else { + match lists { + Value::String(id) if !id.starts_with('#') => vec![(1.into(), lists.clone())], + Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => { + vec![(1.into(), lists.clone())] + } + Value::Array(a) + if a.iter() + .all(|x| x.as_str().is_some_and(|s| !s.starts_with('#')) || x.is_object()) => + { + a.iter().map(|x| (1.into(), x.clone())).collect() + } + Value::Object(_) => vec![(1.into(), lists.clone())], + _ => return None, + } + }; + let lists: Vec<Value> = entries + .into_iter() + .map(|(weight, list)| json!({"weight": weight, "data": nested(&list, data, carried)})) + .collect(); + let mut out = json!({"processor_type": "horizon:apply_random", "processor_lists": lists}); + if let Some(mode) = p.get("mode") { + out["mode"] = mode.clone(); + } + Some(out) +} + +/// Lithostitched's `condition` as `horizon:condition`, when the game runs +/// every condition in it (true, all_of, any_of, not, random_chance, +/// matching_blocks with plain property values); else it stays Java. +fn condition( + p: &Value, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, +) -> Option<Value> { + fn runs(c: &Value) -> bool { + if let Some(all) = c.as_array() { + return all.iter().all(runs); + } + let kind = c["type"].as_str().unwrap_or_default(); + match kind.strip_prefix("lithostitched:").unwrap_or(kind) { + "true" | "random_chance" => true, + "all_of" | "any_of" => c["conditions"] + .as_array() + .is_some_and(|a| a.iter().all(runs)), + "not" => runs(&c["condition"]), + "matching_blocks" => c.get("properties").is_none_or(|p| { + p.as_object() + .is_some_and(|o| o.values().all(Value::is_string)) + }), + _ => false, + } + } + if !runs(&p["if_true"]) { + return None; + } + // One processor or a list of them. + let mut branch = |key: &str| -> Value { + let list = match p.get(key) { + None => Vec::new(), + Some(Value::Array(a)) => a.clone(), + Some(one) => vec![one.clone()], + }; + carry_all(list, data, carried).0.into() + }; + let (then, otherwise) = (branch("then"), branch("else")); + let mut out = json!({"processor_type": "horizon:condition", "if_true": p["if_true"], + "then": then, "else": otherwise}); + if let Some(mode) = p.get("random_mode") { + out["random_mode"] = mode.clone(); + } + Some(out) +} + +/// Repurposed Structures' rule tests and the game's types that run them +/// (`horizon_world::worldgen`'s `rule_test` and `structure::processor`). +const RULE_TESTS: [(&str, &str); 3] = [ + ( + "repurposed_structures:matter_phase_rule_test", + "horizon:matter_phase", + ), + ( + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "horizon:piece_origin_axis_aligned_linear_pos", + ), + ( + "repurposed_structures:y_value_pos_rule_test", + "horizon:y_value", + ), +]; + +/// Renames the rule tests written in Java that the game runs under its own +/// type ([`RULE_TESTS`]) in a worldgen file's processor lists; each is +/// counted by type in `carried`. Their fields are the mod's. Whether +/// anything changed. Without this the game, like vanilla, refuses the list +/// and every pool naming it: Repurposed's mineshafts and Nether monument. +pub fn rule_tests(kind: &str, v: &mut Value, carried: &mut BTreeMap<String, usize>) -> bool { + fn rename(v: &mut Value, carried: &mut BTreeMap<String, usize>) -> bool { + match v { + Value::Object(o) => { + let mut changed = false; + if let Some(Value::String(t)) = o.get_mut("predicate_type") + && let Some((old, new)) = RULE_TESTS.iter().find(|(old, _)| t == old) + { + *carried.entry((*old).to_owned()).or_default() += 1; + *t = (*new).to_owned(); + changed = true; + } + o.values_mut().fold(changed, |c, x| rename(x, carried) | c) + } + Value::Array(a) => a.iter_mut().fold(false, |c, x| rename(x, carried) | c), + _ => false, + } + } + each_list(kind, v, &mut |list| rename(list, carried)) +} + +/// Lithostitched's references in a list, each replaced by the processors of +/// the lists it names, in order (references in them too, to a depth of 8). +/// One naming a tag or a list the mod does not have stays, to be dropped. +/// Whether any was replaced. +fn references( + list: Vec<Value>, + data: &ProcessorData, + carried: &mut BTreeMap<String, usize>, + depth: usize, +) -> (Vec<Value>, bool) { + let mut out = Vec::with_capacity(list.len()); + let mut changed = false; + for p in list { + let named = (p["processor_type"] == "lithostitched:reference" && depth < 8) + .then(|| referenced(&p["processor_lists"], data)) + .flatten(); + match named { + Some(inner) => { + *carried.entry("lithostitched:reference".into()).or_default() += 1; + out.extend(references(inner, data, carried, depth + 1).0); + changed = true; + } + None => out.push(p), + } + } + (out, changed) +} + +/// The processors of the lists a reference names: an id, an inline list, or +/// a list of either. +fn referenced(lists: &Value, data: &ProcessorData) -> Option<Vec<Value>> { + let one = |l: &Value| -> Option<Vec<Value>> { + let mut list = match l { + Value::String(id) if !id.starts_with('#') => { + let id = if id.contains(':') { + id.clone() + } else { + format!("minecraft:{id}") + }; + data.lists.get(&id)?.clone() + } + Value::Object(_) | Value::Array(_) => l.clone(), + _ => return None, + }; + processors(&mut list).map(std::mem::take) + }; + match lists { + // A bare list of processors is one inline list; else a list of lists. + Value::Array(a) if a.iter().any(|x| x.get("processor_type").is_some()) => Some(a.clone()), + Value::Array(a) => Some(a.iter().map(one).collect::<Option<Vec<_>>>()?.concat()), + other => one(other), + } +} + +/// The data form of a Java processor: the processors to put in its place +/// (none for a no-op), or `None` when it has none. +fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option<Vec<Value>> { + let (ns, _) = kind.split_once(':')?; + Some(match kind { + "moogs_structures:spawner_randomizing_processor" => { + let mobs = p["weighted_entities"] + .as_array()? + .iter() + .map(|e| { + // The entry's NBT, then its id over it. + let mut entity = match &e["nbt"] { + Value::Object(o) => o.clone(), + _ => serde_json::Map::new(), + }; + entity.insert("id".into(), e["entity"].as_str()?.into()); + Some(json!({"entity": entity, "weight": e["weight"].as_f64()?})) + }) + .collect::<Option<Vec<_>>>()?; + vec![spawner_mobs(p, mobs, None)] + } + "repurposed_structures:spawner_randomizing_processor" => { + // A list the mod does not ship falls back to a vanilla dungeon + // mob in the mod; left out here. + let list = data + .spawners + .get(p["rs_spawner_resourcelocation"].as_str()?)?; + let mobs = list + .iter() + .map(|(id, weight)| json!({"entity": {"id": id}, "weight": weight})) + .collect(); + vec![spawner_mobs(p, mobs, repurposed_light(p)?)] + } + "moogs_structures:vanilla_loot_swap_processor" => { + let key = ( + p["modid"].as_str()?.to_owned(), + p["vanilla_key"].as_str()?.to_owned(), + ); + if data.replace_vanilla.contains(&key) { + return None; + } + Vec::new() + } + "moogs_structures:trial_spawner_randomizing_processor" => { + // The configs by id: 26.3 reads them from `trial_spawner/`, the + // folder Moog's loads them from. + let mut nbt = json!({"normal_config": p["normal_config"].as_str()?}); + if let Some(ominous) = p["ominous_config"].as_str() { + nbt["ominous_config"] = ominous.into(); + } + // The state the template was saved with goes. + let saved = [ + "server_data", + "shared_data", + "spawn_data", + "cooldown_end_at_tick", + "next_mob_spawns_at", + ]; + vec![same_state_rule(&TRIAL_SPAWNER_STATES, &saved, |_| { + nbt.clone() + })] + } + "moogs_structures:vault_randomizing_processor" => { + let normal = p["loot_table"].as_str()?; + let config = |ominous: bool| { + let (table, key) = match ominous { + true => ( + p["ominous_loot_table"].as_str().unwrap_or(normal), + p["ominous_key_item"] + .as_str() + .unwrap_or("minecraft:ominous_trial_key"), + ), + false => ( + normal, + p["key_item"].as_str().unwrap_or("minecraft:trial_key"), + ), + }; + // Merged into the vault's config, as the mod puts both in. + json!({"config": {"loot_table": table, "key_item": {"id": key, "count": 1}}}) + }; + vec![same_state_rule( + &VAULT_STATES, + &["server_data", "shared_data"], + |s| config(s.get("ominous") == Some(&"true")), + )] + } + _ if ns == "betterdeserttemples" + && let Some(processor) = desert_temple(kind) => + { + vec![processor] + } + "lithostitched:block_swap" => { + // The same map; the game's swap keeps the properties both have. + p["blocks"].as_object()?; + vec![json!({"processor_type": "horizon:block_swap", "blocks": p["blocks"]})] + } + "lithostitched:set_block" => { + // A simple or weighted state provider, the block entity left as + // it is. + let provider = p["state_provider"]["type"].as_str()?; + let modifier = p["block_entity_modifier"]["type"].as_str(); + let plain = + modifier.is_none_or(|m| m.trim_start_matches("minecraft:") == "passthrough"); + if !plain + || !matches!( + provider, + "minecraft:simple_state_provider" | "minecraft:weighted_state_provider" + ) + { + return None; + } + let mut out = p.clone(); + out["processor_type"] = "horizon:set_block".into(); + if let Some(o) = out.as_object_mut() { + o.remove("block_entity_modifier"); + } + vec![out] + } + "betterdungeons:small_dungeon_chest_processor" => { + // Its config's defaults: one chest at least, two at most, a + // fifth of the others kept until then; ChestBlock covers both. + vec![json!({"processor_type": "horizon:count_cap", + "blocks": ["minecraft:chest", "minecraft:trapped_chest"], + "min": 1, "max": 2, "chance": 0.2f32 as f64, + "replacement": block("minecraft:cave_air")})] + } + _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], + _ => return None, + }) +} + +/// A block's states, as (block, [(property, values)]). +type States = ( + &'static str, + &'static [(&'static str, &'static [&'static str])], +); +const TRIAL_SPAWNER_STATES: States = ( + "minecraft:trial_spawner", + &[ + ( + "trial_spawner_state", + &[ + "inactive", + "waiting_for_players", + "active", + "waiting_for_reward_ejection", + "ejecting_reward", + "cooldown", + ], + ), + ("ominous", &["false", "true"]), + ], +); +const VAULT_STATES: States = ( + "minecraft:vault", + &[ + ("facing", &["north", "south", "west", "east"]), + ( + "vault_state", + &["inactive", "active", "unlocking", "ejecting"], + ), + ("ominous", &["false", "true"]), + ], +); + +/// Moog's trial spawner and vault processors keep the block, take keys out +/// of its block entity and set others. As vanilla's `rule`: one rule per +/// state of the block, matching it and writing it back, with the game's +/// `horizon:edit` modifier taking out `remove` and merging `nbt(state)` in. +fn same_state_rule( + states: &States, + remove: &[&str], + nbt: impl Fn(&BTreeMap<&str, &str>) -> Value, +) -> Value { + let (block, properties) = states; + let mut all = vec![BTreeMap::new()]; + for (key, values) in properties.iter() { + all = all + .into_iter() + .flat_map(|s| { + values.iter().map(move |v| { + let mut s = s.clone(); + s.insert(*key, *v); + s + }) + }) + .collect(); + } + let rules: Vec<Value> = all + .iter() + .map(|s| { + let state = json!({"id": block, "properties": s}); + json!({ + "input_predicate": {"predicate_type": "minecraft:blockstate_match", "block_state": state}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": state, + "block_entity_modifier": {"type": "horizon:edit", "remove": remove, "data": nbt(s)}, + }) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) +} + +/// An entity's NBT in 26.3's shape, in place: 1.21.1's `ArmorItems` (feet +/// to head), `HandItems` (main hand, off hand) and their drop chances become +/// `equipment` and `drop_chances` by slot; empty items and the default drop +/// chance (0.085) are left out, as 26.3 saves them. Whether it changed. +pub fn upgrade_entity(entity: &mut Value) -> bool { + let Some(o) = entity.as_object_mut() else { + return false; + }; + const ARMOR: [&str; 4] = ["feet", "legs", "chest", "head"]; + const HANDS: [&str; 2] = ["mainhand", "offhand"]; + let mut changed = false; + for (items, chances, slots) in [ + ("ArmorItems", "ArmorDropChances", &ARMOR[..]), + ("HandItems", "HandDropChances", &HANDS[..]), + ] { + if let Some(Value::Array(list)) = o.remove(items) { + changed = true; + for (slot, item) in slots.iter().zip(list) { + if item.get("id").is_some() { + let equipment = o.entry("equipment").or_insert_with(|| json!({})); + equipment[*slot] = item; + } + } + } + if let Some(Value::Array(list)) = o.remove(chances) { + changed = true; + for (slot, chance) in slots.iter().zip(list) { + if chance.as_f64().is_some_and(|c| (c - 0.085).abs() > 1e-6) { + let drop = o.entry("drop_chances").or_insert_with(|| json!({})); + drop[*slot] = chance; + } + } + } + } + changed +} + +/// A 1.21.1 trial spawner config (`trial_spawner/`) in 26.3's shape, in +/// place: its mobs' NBT ([`upgrade_entity`]). Whether it changed. +pub fn upgrade_trial_spawner(config: &mut Value) -> bool { + let mut changed = false; + for p in config["spawn_potentials"] + .as_array_mut() + .into_iter() + .flatten() + { + changed |= upgrade_entity(&mut p["data"]["entity"]); + } + changed +} + +/// A block state as 26.3 writes it. +fn block(id: &str) -> Value { + json!({"id": id}) +} + +/// Better Desert Temples' placeholder blocks (glass, concrete and wool in +/// the templates) as the mod's processors turn them: the fixed ones as +/// vanilla's `rule`, the random ones as the game's `horizon:pick`, with the +/// mod's bounds on one `nextFloat` (YUNG's BlockStateRandomizer adds its +/// chances up in floats). The ones that read or change the world around +/// (pillars, Diorite's waterlogging) stay dropped. +fn desert_temple(kind: &str) -> Option<Value> { + let swap = |from: &str, to: &str| { + json!({"processor_type": "minecraft:rule", "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": block(to)}]}) + }; + let pick = |from: &str, picks: Vec<Value>, default: Value| json!({"processor_type": "horizon:pick", "block": from, "picks": picks, "default": default}); + // YUNG's BlockStateRandomizer: an entry wins below the sum of the + // chances so far, summed as floats. + let randomizer = |entries: &[(f32, &str)]| { + let mut bottom = 0f32; + entries + .iter() + .map(|(chance, id)| { + bottom += chance; + json!({"below": bottom as f64, "state": block(id)}) + }) + .collect::<Vec<_>>() + }; + let at = |below: f32, id: &str| json!({"below": below as f64, "state": block(id)}); + // Sandstone stairs, upside down, facing Plane.HORIZONTAL.getRandomDirection. + let stairs = || { + let states: Vec<Value> = ["north", "east", "south", "west"] + .iter() + .map(|facing| { + json!({"id": "minecraft:sandstone_stairs", "properties": { + "facing": facing, "half": "top", "shape": "straight", "waterlogged": "false"}}) + }) + .collect(); + json!({"states": states}) + }; + Some(match kind.strip_prefix("betterdeserttemples:")? { + "blue_concrete_processor" => swap("minecraft:blue_concrete", "minecraft:blue_terracotta"), + "yellow_concrete_processor" => { + swap("minecraft:yellow_concrete", "minecraft:yellow_terracotta") + } + "red_wool_processor" => swap("minecraft:red_wool", "minecraft:tnt"), + "white_stained_glass_processor" => pick( + "minecraft:white_stained_glass", + randomizer(&[(0.4, "minecraft:cobweb")]), + json!({"state": block("minecraft:air")}), + ), + "polished_diorite_processor" => pick( + "minecraft:polished_diorite", + randomizer(&[(0.6, "minecraft:cut_sandstone")]), + json!({"state": block("minecraft:sandstone")}), + ), + "orange_stained_glass_processor" => { + let mut sus = at(0.01, "minecraft:suspicious_sand"); + sus["nbt"] = json!({"LootTable": "minecraft:archaeology/desert_pyramid"}); + let mut stairs = stairs(); + stairs["below"] = (0.45f32 as f64).into(); + pick( + "minecraft:orange_stained_glass", + vec![ + sus, + at(0.1, "minecraft:sand"), + at(0.2, "minecraft:sandstone"), + stairs, + ], + json!({"state": block("minecraft:cut_sandstone")}), + ) + } + "red_stained_glass_processor" => pick( + "minecraft:red_stained_glass", + vec![at(0.3, "minecraft:sand"), at(0.75, "minecraft:sandstone")], + stairs(), + ), + "pot_processor" => { + // Four sherds, one float each; the pot back to its default state. + let values: Vec<Value> = [ + (0.05f32, "archer"), + (0.1, "miner"), + (0.15, "prize"), + (0.2, "skull"), + ] + .iter() + .map(|(below, sherd)| { + json!({"below": *below as f64, "value": format!("minecraft:{sherd}_pottery_sherd")}) + }) + .collect(); + pick( + "minecraft:decorated_pot", + Vec::new(), + json!({"state": block("minecraft:decorated_pot"), "lists": [{ + "key": "sherds", "count": 4, "values": values, "default": "minecraft:brick"}]}), + ) + } + _ => return None, + }) +} + +/// [`as_data`]'s `horizon:spawner_mobs` for the mods' spawner randomizing +/// processors, whose fields have the same names and defaults. +fn spawner_mobs(p: &Value, mobs: Vec<Value>, rules: Option<Value>) -> Value { + let mut out = json!({"processor_type": "horizon:spawner_mobs", "mobs": mobs}); + for key in [ + "delay", + "min_spawn_delay", + "max_spawn_delay", + "spawn_count", + "max_nearby_entities", + "required_player_range", + "spawn_range", + ] { + if let Some(n) = p.get(key).filter(|n| n.is_i64()) { + out[key] = n.clone(); + } + } + if let Some(r) = rules { + out["custom_spawn_rules"] = r; + } + if let Some(b) = p.get("spawner_replacement_block") { + out["replacement"] = b.clone(); + } + out +} + +/// Repurposed Structures' `custom_spawn_rules` from its light level ranges: +/// `Some(None)` without either, `None` when one does not read. The sky +/// light's upper bound is written as `max_exclusive`, as the mod does. +fn repurposed_light(p: &Value) -> Option<Option<Value>> { + let range = |key: &str| -> Option<Option<(i64, i64)>> { + match p.get(key) { + None => Some(None), + Some(Value::Number(n)) => n.as_i64().map(|n| Some((n, n))), + Some(v) => Some(Some(( + v["min_inclusive"].as_i64()?, + v["max_inclusive"].as_i64()?, + ))), + } + }; + let (block, sky) = ( + range("valid_block_light_level")?, + range("valid_sky_light_level")?, + ); + if block.is_none() && sky.is_none() { + return Some(None); + } + let mut rules = json!({}); + if let Some((min, max)) = block { + rules["block_light_limit"] = json!({"min_inclusive": min, "max_inclusive": max}); + } + if let Some((min, max)) = sky { + rules["sky_light_limit"] = json!({"min_inclusive": min, "max_exclusive": max}); + } + Some(Some(rules)) +} + +/// An item as 26.3 saves it. +fn item(id: &str) -> Value { + json!({"id": format!("minecraft:{id}"), "count": 1}) +} + +/// YUNG's processors that make a spawner of a fixed mob (YUNG's API's +/// `MobSpawnerData`), as vanilla's `rule`: every `input` block becomes a +/// spawner with that NBT. +fn yung_spawner(kind: &str, p: &Value) -> Option<Value> { + const SPAWNER: &str = "minecraft:spawner"; + // (input block, mob, fields other than the defaults, whether the mob is + // also the only potential, its equipment) + let (input, mob, fields, potential, equipment): (_, _, &[(&str, i64)], _, _) = match kind { + "betterdungeons:mob_spawner_processor" => { + (SPAWNER, p["spawner_mob"].as_str()?, &[], true, None) + } + "betterdungeons:zombie_mob_spawner_processor" => ( + SPAWNER, + "minecraft:zombie", + &[("MaxNearbyEntities", 8)], + true, + None, + ), + "betterdungeons:skeleton_mob_spawner_processor" => ( + SPAWNER, + "minecraft:skeleton", + &[ + ("RequiredPlayerRange", 18), + ("MaxNearbyEntities", 8), + ("MaxSpawnDelay", 650), + ], + true, + None, + ), + "betterdungeons:small_nether_dungeon_mob_spawner_processor" => { + let mob = p["spawner_mob"].as_str()?; + // Wither skeletons get netherite armor that never drops and a + // stone sword (with the mod's default config, they and blazes + // keep their loot). + let armor = (mob == "minecraft:wither_skeleton").then(|| { + json!({ + "equipment": { + "feet": item("netherite_boots"), + "legs": item("netherite_leggings"), + "chest": item("netherite_chestplate"), + "head": item("netherite_helmet"), + "mainhand": item("stone_sword"), + }, + "drop_chances": {"feet": 0.0, "legs": 0.0, "chest": 0.0, "head": 0.0}, + }) + }); + (SPAWNER, mob, &[], true, armor) + } + "betterdungeons:zombie_tombstone_spawner_processor" => ( + "minecraft:black_stained_glass", + "minecraft:skeleton", + &[], + false, + Some(json!({"equipment": {"mainhand": item("iron_sword")}})), + ), + "betterdeserttemples:gravel_processor" => ( + "minecraft:gravel", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + None, + ), + // An empty hand list in 1.21.1: the skeletons spawn without a bow, + // since a spawn entry with more than its id is not finalized. + "betterdeserttemples:bone_block_processor" => ( + "minecraft:bone_block", + "minecraft:skeleton", + &[("RequiredPlayerRange", 32)], + false, + Some(json!({"equipment": {}})), + ), + "betterdeserttemples:infested_cracked_stone_bricks_processor" => ( + "minecraft:infested_cracked_stone_bricks", + "minecraft:silverfish", + &[("RequiredPlayerRange", 24)], + false, + None, + ), + // 1.21.1 ignores the items' old `Count` and `tag` (the shield's + // pattern, the boots' dye): plain items. + "betterdeserttemples:yellow_wool_processor" => ( + "minecraft:yellow_wool", + "minecraft:husk", + &[("MaxNearbyEntities", 8), ("RequiredPlayerRange", 24)], + false, + Some(json!({"equipment": { + "mainhand": item("golden_sword"), + "offhand": item("shield"), + "feet": item("leather_boots"), + "legs": item("leather_leggings"), + "chest": item("golden_chestplate"), + "head": item("chainmail_helmet"), + }})), + ), + _ => return None, + }; + let mut entity = json!({"id": mob}); + if let Some(Value::Object(extra)) = equipment { + entity.as_object_mut()?.extend(extra); + } + let potentials = match potential { + true => json!([{"data": {"entity": entity.clone()}, "weight": 1}]), + false => json!([]), + }; + let mut nbt = json!({ + "Delay": 20, "MinSpawnDelay": 200, "MaxSpawnDelay": 800, "SpawnCount": 4, + "MaxNearbyEntities": 6, "RequiredPlayerRange": 16, "SpawnRange": 4, + "SpawnData": {"entity": entity}, + "SpawnPotentials": potentials, + }); + for (key, value) in fields { + nbt[*key] = (*value).into(); + } + Some(json!({ + "processor_type": "minecraft:rule", + "rules": [{ + "input_predicate": {"predicate_type": "minecraft:block_match", "block": input}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": {"Name": SPAWNER}, + "block_entity_modifier": {"type": "minecraft:append_static", "data": nbt}, + }], + })) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn data() -> ProcessorData { + let mut d = ProcessorData::default(); + d.spawners.insert( + "repurposed_structures:dungeons/badlands".into(), + vec![ + ("minecraft:husk".into(), 10.), + ("minecraft:cave_spider".into(), 3.), + ], + ); + d.replace_vanilla.insert(("mvs".into(), "village".into())); + d + } + + #[test] + fn spawner_processors_become_data() { + let mut list = json!({"processors": [ + {"processor_type": "moogs_structures:spawner_randomizing_processor", + "weighted_entities": [{"entity": "minecraft:blaze", "weight": 2, "nbt": {"Health": 5}}], + "spawn_count": 2, "spawner_replacement_block": {"Name": "minecraft:stone"}}, + {"processor_type": "repurposed_structures:spawner_randomizing_processor", + "rs_spawner_resourcelocation": "repurposed_structures:dungeons/badlands", + "valid_block_light_level": {"min_inclusive": 0, "max_inclusive": 7}}, + {"processor_type": "repurposed_structures:spawner_randomizing_processor", + "rs_spawner_resourcelocation": "repurposed_structures:missing"}, + {"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}, + {"processor_type": "moogs_structures:vanilla_loot_swap_processor", + "modid": "mns", "vanilla_key": "fortress", "loot_table_mapping": {}}, + {"processor_type": "moogs_structures:vanilla_loot_swap_processor", + "modid": "mvs", "vanilla_key": "village", "loot_table_mapping": {}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!(p.len(), 5, "{p:#?}"); + assert_eq!( + p[0], + json!({"processor_type": "horizon:spawner_mobs", + "mobs": [{"entity": {"Health": 5, "id": "minecraft:blaze"}, "weight": 2.0}], + "spawn_count": 2, "replacement": {"Name": "minecraft:stone"}}) + ); + assert_eq!( + p[1], + json!({"processor_type": "horizon:spawner_mobs", + "mobs": [{"entity": {"id": "minecraft:husk"}, "weight": 10.0}, + {"entity": {"id": "minecraft:cave_spider"}, "weight": 3.0}], + "custom_spawn_rules": {"block_light_limit": {"min_inclusive": 0, "max_inclusive": 7}}}) + ); + // Unknown list, vanilla processor, and a swap whose preset is on: kept + // (the Java ones are dropped later); the swap that is off is gone. + assert_eq!( + p[2]["rs_spawner_resourcelocation"], + "repurposed_structures:missing" + ); + assert_eq!(p[3]["processor_type"], "minecraft:gravity"); + assert_eq!(p[4]["modid"], "mvs"); + assert_eq!( + carried, + BTreeMap::from([ + ("moogs_structures:spawner_randomizing_processor".into(), 1), + ("moogs_structures:vanilla_loot_swap_processor".into(), 1), + ( + "repurposed_structures:spawner_randomizing_processor".into(), + 1 + ), + ]) + ); + } + + #[test] + fn yungs_spawners_become_rules() { + let mut pool = json!({"elements": [{"element": {"processors": {"processors": [ + {"processor_type": "betterdungeons:skeleton_mob_spawner_processor"}, + {"processor_type": "betterdeserttemples:bone_block_processor"}, + {"processor_type": "betterdungeons:small_nether_dungeon_mob_spawner_processor", + "spawner_mob": "minecraft:wither_skeleton"}, + {"processor_type": "betterdungeons:candle_processor"}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(carry("template_pool", &mut pool, &data(), &mut carried)); + let p = &pool["elements"][0]["element"]["processors"]["processors"]; + let rule = |i: usize| &p[i]["rules"][0]; + assert_eq!(rule(0)["input_predicate"]["block"], "minecraft:spawner"); + assert_eq!( + rule(0)["output_state"], + json!({"Name": "minecraft:spawner"}) + ); + let nbt = &rule(0)["block_entity_modifier"]["data"]; + assert_eq!( + ( + nbt["RequiredPlayerRange"].clone(), + nbt["MaxNearbyEntities"].clone() + ), + (json!(18), json!(8)) + ); + assert_eq!(nbt["MaxSpawnDelay"], 650); + assert_eq!( + nbt["SpawnPotentials"], + json!([{"data": {"entity": {"id": "minecraft:skeleton"}}, "weight": 1}]) + ); + // Bone blocks become bowless skeleton spawners with no potentials. + let bone = &rule(1)["block_entity_modifier"]["data"]; + assert_eq!(rule(1)["input_predicate"]["block"], "minecraft:bone_block"); + assert_eq!( + bone["SpawnData"], + json!({"entity": {"id": "minecraft:skeleton", "equipment": {}}}) + ); + assert_eq!(bone["SpawnPotentials"], json!([])); + let wither = &rule(2)["block_entity_modifier"]["data"]["SpawnData"]["entity"]; + assert_eq!( + wither["equipment"]["head"]["id"], + "minecraft:netherite_helmet" + ); + assert_eq!(wither["drop_chances"]["feet"], 0.0); + assert_eq!(p[3]["processor_type"], "betterdungeons:candle_processor"); + assert_eq!(carried.values().sum::<usize>(), 3); + } + + #[test] + fn trial_spawners_and_vaults_drop_their_saved_state() { + let mut list = json!({"processors": [ + {"processor_type": "moogs_structures:trial_spawner_randomizing_processor", + "normal_config": "mns:arena/normal", "ominous_config": "mns:arena/ominous"}, + {"processor_type": "moogs_structures:vault_randomizing_processor", + "loot_table": "mns:vaults/main", "ominous_loot_table": "mns:vaults/ominous"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + let rules = |i: usize| p[i]["rules"].as_array().unwrap().clone(); + // Every state of the block: 6 x 2 trial spawners, 4 x 4 x 2 vaults. + assert_eq!((rules(0).len(), rules(1).len()), (12, 32)); + let spawner = &rules(0)[0]; + assert_eq!( + spawner["input_predicate"]["block_state"], + spawner["output_state"] + ); + assert_eq!( + spawner["block_entity_modifier"], + json!({"type": "horizon:edit", + "remove": ["server_data", "shared_data", "spawn_data", + "cooldown_end_at_tick", "next_mob_spawns_at"], + "data": {"normal_config": "mns:arena/normal", + "ominous_config": "mns:arena/ominous"}}) + ); + for rule in rules(1) { + let ominous = rule["output_state"]["properties"]["ominous"] == "true"; + let (table, key) = match ominous { + true => ("mns:vaults/ominous", "minecraft:ominous_trial_key"), + false => ("mns:vaults/main", "minecraft:trial_key"), + }; + assert_eq!( + rule["block_entity_modifier"], + json!({"type": "horizon:edit", "remove": ["server_data", "shared_data"], + "data": {"config": {"loot_table": table, + "key_item": {"id": key, "count": 1}}}}) + ); + } + assert_eq!(carried.len(), 2); + } + + #[test] + fn trial_spawner_mobs_take_26_3s_equipment() { + let mut config = json!({"spawn_potentials": [{"weight": 1, "data": {"entity": { + "id": "minecraft:skeleton", + "ArmorItems": [{}, {}, {}, {"id": "minecraft:iron_helmet", "count": 1}], + "ArmorDropChances": [0.085, 0.085, 0.085, 0.0], + "HandItems": [{"id": "minecraft:bow", "count": 1}, {}], + "HandDropChances": [0.085, 0.085]}}}]}); + assert!(upgrade_trial_spawner(&mut config)); + assert_eq!( + config["spawn_potentials"][0]["data"]["entity"], + json!({"id": "minecraft:skeleton", + "equipment": {"head": {"id": "minecraft:iron_helmet", "count": 1}, + "mainhand": {"id": "minecraft:bow", "count": 1}}, + "drop_chances": {"head": 0.0}}) + ); + assert!(!upgrade_trial_spawner(&mut config)); + } + + #[test] + fn desert_temple_placeholders_become_rules_and_picks() { + let mut list = json!({"processors": [ + {"processor_type": "betterdeserttemples:red_wool_processor"}, + {"processor_type": "betterdeserttemples:white_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:orange_stained_glass_processor"}, + {"processor_type": "betterdeserttemples:pot_processor"}, + {"processor_type": "betterdeserttemples:quartz_pillar_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0]["rules"][0]["output_state"], + json!({"id": "minecraft:tnt"}) + ); + assert_eq!(p[1]["processor_type"], "horizon:pick"); + assert_eq!(p[1]["picks"][0]["below"], 0.4f32 as f64); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:air"); + let glass = &p[2]["picks"]; + assert_eq!(glass[0]["state"]["id"], "minecraft:suspicious_sand"); + assert_eq!( + glass[0]["nbt"]["LootTable"], + "minecraft:archaeology/desert_pyramid" + ); + assert_eq!(glass[3]["states"].as_array().unwrap().len(), 4); + assert_eq!(glass[3]["below"], 0.45f32 as f64); + assert_eq!(p[3]["default"]["lists"][0]["count"], 4); + // The pillar reads the world below: still Java, still dropped later. + assert_eq!( + p[4]["processor_type"], + "betterdeserttemples:quartz_pillar_processor" + ); + assert_eq!(carried.values().sum::<usize>(), 4); + } + + #[test] + fn small_dungeon_chests_are_capped() { + let mut list = json!({"processors": [ + {"processor_type": "betterdungeons:small_dungeon_chest_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let cap = &list["processors"][0]; + assert_eq!(cap["processor_type"], "horizon:count_cap"); + assert_eq!( + (cap["min"].as_u64(), cap["max"].as_u64()), + (Some(1), Some(2)) + ); + assert_eq!(cap["replacement"], json!({"id": "minecraft:cave_air"})); + } + + #[test] + fn lithostitched_block_swaps_become_the_games() { + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}, + {"processor_type": "lithostitched:block_swap", "blocks": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data(), &mut carried)); + let p = list["processors"].as_array().unwrap(); + assert_eq!( + p[0], + json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:cobblestone": "minecraft:mossy_cobblestone"}}) + ); + // A map that is not one stays Java (dropped later). + assert_eq!(p[1]["processor_type"], "lithostitched:block_swap"); + } + + #[test] + fn lithostitched_references_are_written_in() { + let mut data = data(); + let gravity = json!({"processor_type": "minecraft:gravity", "heightmap": "WORLD_SURFACE_WG", "offset": 0}); + data.lists + .insert("v:road".into(), json!({"processors": [gravity.clone()]})); + data.lists.insert( + "v:house".into(), + json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:road"}, + {"processor_type": "lithostitched:block_swap", "blocks": {"minecraft:dirt": "minecraft:grass_block"}}]}), + ); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": ["v:house", "v:road"]}, + {"processor_type": "lithostitched:reference", "processor_lists": "#v:roads"}, + {"processor_type": "lithostitched:reference", "processor_lists": ["v:nowhere"]}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + // House (its own reference to road first, then its swap), then road; + // the swap inside is carried too. + assert_eq!(p[0], gravity); + assert_eq!(p[1]["processor_type"], "horizon:block_swap"); + assert_eq!(p[2], gravity); + // A tag or a list the mod lacks stays, to be dropped. + assert_eq!(p[3]["processor_lists"], "#v:roads"); + assert_eq!(p[4]["processor_lists"], json!(["v:nowhere"])); + assert_eq!(carried["lithostitched:reference"], 2); + } + + #[test] + fn lithostitched_random_and_condition_become_the_games() { + let mut data = data(); + let swap = json!({"processor_type": "lithostitched:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + data.lists + .insert("v:green".into(), json!({"processors": [swap.clone()]})); + let mut list = json!({"processors": [ + {"processor_type": "lithostitched:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [ + {"processor_type": "lithostitched:reference", "processor_lists": "v:green"}, + {"processor_type": "v:java"}]}}]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": ["v:green", "v:red"]}, + {"processor_type": "lithostitched:apply_random", "mode": "per_block", + "processor_lists": "#v:colours"}, + {"processor_type": "lithostitched:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": swap, "else": {"processor_type": "lithostitched:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}}, + {"processor_type": "lithostitched:condition", + "if_true": {"type": "lithostitched:matching_biomes", "biomes": "#c:is_cold"}, + "then": []}]}); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &data, &mut carried)); + let p = list["processors"].as_array().unwrap(); + let green = json!({"processor_type": "horizon:block_swap", + "blocks": {"minecraft:dirt": "minecraft:grass_block"}}); + // Inline lists are carried; Java left in them is dropped later. + assert_eq!( + p[0], + json!({"processor_type": "horizon:apply_random", "mode": "per_piece", "processor_lists": [ + {"weight": 3, "data": "minecraft:empty"}, + {"weight": 1, "data": {"processors": [green.clone(), {"processor_type": "v:java"}]}}]}) + ); + assert_eq!( + p[1]["processor_lists"], + json!([{"weight": 1, "data": "v:green"}, {"weight": 1, "data": "v:red"}]) + ); + assert_eq!(p[2]["processor_type"], "lithostitched:apply_random"); + assert_eq!( + p[3], + json!({"processor_type": "horizon:condition", + "if_true": [{"type": "lithostitched:matching_blocks", "blocks": "minecraft:cobblestone"}], + "then": [green], "else": [{"processor_type": "horizon:set_block", "state_provider": + {"type": "minecraft:simple_state_provider", "state": {"Name": "minecraft:stone"}}}]}) + ); + assert_eq!(p[4]["processor_type"], "lithostitched:condition"); + assert_eq!(carried["lithostitched:apply_random"], 2); + assert_eq!(carried["lithostitched:condition"], 1); + } + + #[test] + fn repurposed_rule_tests_become_the_games() { + let rule = |input: Value, position: Value| { + json!({"input_predicate": input, "location_predicate": {"predicate_type": + "repurposed_structures:matter_phase_rule_test", "phase_to_test_for": "AIR"}, + "position_predicate": position, "output_state": {"id": "minecraft:lava"}}) + }; + let mut pool = json!({"elements": [{"weight": 1, "element": { + "element_type": "minecraft:single_pool_element", "processors": {"processors": [ + {"processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:always_true"}), + json!({"predicate_type": "repurposed_structures:y_value_pos_rule_test", + "min_y_value": 0, "max_y_value": 31}))]}, + {"processor_type": "minecraft:capped", "limit": 2, "delegate": { + "processor_type": "minecraft:rule", "rules": [rule( + json!({"predicate_type": "minecraft:block_match", "block": "minecraft:rail"}), + json!({"predicate_type": + "repurposed_structures:piece_origin_axis_aligned_linear_pos_rule_test", + "axis": "y", "min_dist": 0, "max_dist": 1}))]}}]}}}]}); + let mut carried = BTreeMap::new(); + assert!(rule_tests("template_pool", &mut pool, &mut carried)); + let list = &pool["elements"][0]["element"]["processors"]["processors"]; + let first = &list[0]["rules"][0]; + assert_eq!( + first["location_predicate"]["predicate_type"], + "horizon:matter_phase" + ); + assert_eq!(first["location_predicate"]["phase_to_test_for"], "AIR"); + assert_eq!( + first["position_predicate"]["predicate_type"], + "horizon:y_value" + ); + assert_eq!(first["position_predicate"]["max_y_value"], 31); + let delegated = &list[1]["delegate"]["rules"][0]; + assert_eq!( + delegated["position_predicate"]["predicate_type"], + "horizon:piece_origin_axis_aligned_linear_pos" + ); + assert_eq!( + delegated["input_predicate"]["predicate_type"], + "minecraft:block_match" + ); + assert_eq!(carried.values().sum::<usize>(), 4); + assert_eq!(carried["repurposed_structures:matter_phase_rule_test"], 2); + // A file holding none is left as it is. + assert!(!rule_tests("template_pool", &mut pool, &mut carried)); + assert!(!rule_tests( + "structure", + &mut json!({"predicate_type": + "repurposed_structures:y_value_pos_rule_test"}), + &mut carried + )); + } +} diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 25e0dbbea..4449e9f5b 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -26,11 +26,66 @@ const JIGSAWS: [&str; 3] = [ "moogs_structures:moogs_structures_generic_jigsaw_structure", "repurposed_structures:generic_jigsaw_structure", ]; +/// The Nether variants of the piece-limited jigsaws: laid out the same, +/// then moved onto land. +const NETHER_JIGSAWS: [&str; 2] = [ + "moogs_structures:moogs_structures_generic_nether_jigsaw_structure", + "repurposed_structures:generic_nether_jigsaw_structure", +]; +/// Repurposed Structures' generic jigsaws with a start check of their own: the +/// `repurposed` key of `horizon:start_checks` names it. +const REPURPOSED_CHECKED: [(&str, &str); 3] = [ + ("repurposed_structures:city_nether_structure", "city_nether"), + ( + "repurposed_structures:shipwreck_nether_structure", + "shipwreck_nether", + ), + ("repurposed_structures:stronghold_end", "stronghold_end"), +]; +/// Repurposed Structures' mineshaft: its generic jigsaw laid out under the +/// terrain (`"layout": "mineshaft"` in `horizon:piece_limited`). +const REPURPOSED_MINESHAFT: &str = "repurposed_structures:generic_mineshaft"; +/// Layout rules the piece-limited assembler keeps (`horizon:piece_limited`). +const PIECE_LIMITED_RULES: [&str; 4] = [ + "y_allowance", + "burying_type", + "use_bounding_box_hack", + "pools_that_ignore_boundaries", +]; /// Placements that are vanilla's random spread with extra rules. const SPREADS: [&str; 2] = [ "moogs_structures:advanced_random_spread", "repurposed_structures:advanced_random_spread", ]; +/// YUNG's placements: vanilla's random spread with an enhanced exclusion +/// zone (several sets), plus, for the temples, no start near an ocean or a +/// river, and for strongholds, starts only in odd rings around the origin. +const YUNG_SPREADS: [&str; 4] = [ + "yungsapi:enhanced_random_spread", + "betterdeserttemples:desert_temple", + "betterjungletemples:jungle_temple", + "betterstrongholds:stronghold", +]; +/// YUNG's structures and the vanilla structure type each one's mod turns +/// off (its DisableVanilla*Mixin, on by default in each mod's config). +const YUNG_REPLACES: [(&str, &str); 7] = [ + ( + "betterdeserttemples:desert_temple", + "minecraft:desert_pyramid", + ), + ( + "betterjungletemples:jungle_temple", + "minecraft:jungle_temple", + ), + ("betterwitchhuts:witch_hut", "minecraft:swamp_hut"), + ( + "betteroceanmonuments:ocean_monument", + "minecraft:ocean_monument", + ), + ("betterstrongholds:stronghold", "minecraft:stronghold"), + ("betterfortresses:fortress", "minecraft:fortress"), + ("bettermineshafts:mineshaft_", "minecraft:mineshaft"), +]; /// 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; @@ -42,14 +97,17 @@ const START_RULES: [(&str, &str); 3] = [ ]; /// The jigsaws' rules on laying out pieces, which vanilla's jigsaw has no /// place for. -const LAYOUT_RULES: [&str; 6] = [ +const LAYOUT_RULES: [&str; 5] = [ "y_allowance", "burying_type", "use_bounding_box_hack", "pools_that_ignore_boundaries", "enhanced_terrain_adaptation", - "vertical_distance_from_start_piece", ]; +/// Fields of older versions the mods' codecs no longer read: their own +/// structures ignore them, and so does carry. Repurposed's jungle fortress +/// and End stronghold still write `vertical_distance_from_start_piece`. +const DEAD_FIELDS: [&str; 1] = ["vertical_distance_from_start_piece"]; /// Pool elements that are vanilla's with extra fields: (mod type, vanilla type). const ELEMENTS: [(&str, &str); 3] = [ ( @@ -76,6 +134,212 @@ pub struct Upgrade { pub rules_lost: BTreeMap<String, usize>, /// Processors written in Java, taken out of their lists, by type. pub processors_dropped: BTreeMap<String, usize>, + /// Processors written in Java carried as data the game runs + /// ([`crate::processors`]), by type. + pub processors_carried: BTreeMap<String, usize>, + /// Rule tests written in Java carried as the game's own + /// ([`crate::processors::rule_tests`]), by type. + pub rule_tests_carried: BTreeMap<String, usize>, + /// Entries added to other structure sets and template pools + /// (`horizon:add_to`), by the set or pool they join. + pub added_to: BTreeMap<String, usize>, + /// Lithostitched worldgen modifiers not carried: by type, `conditions` + /// when they need a mod that is not ported along, `target` when they + /// name their sets or pools by a tag. + pub modifiers_left: BTreeMap<String, usize>, +} + +/// Where a mod's additions to other sets and pools go in its carry: +/// `data/<id>/worldgen/<kind>/horizon_added/<name>.json`. +pub const ADDED: &str = "horizon_added"; + +/// A lithostitched worldgen modifier +/// (`data/<ns>/lithostitched/worldgen_modifier/`) that adds to structure +/// sets or template pools, as a file the game merges into them (the key +/// `horizon:add_to`, `horizon_client::mod_content`): (kind, file). The +/// modifier's conditions are checked against `loaded`, the mods ported +/// along: a compat addition for a mod that is not would place that mod's +/// blocks, which the game does not have. Other modifier types are left out. +/// Both are counted in `report`. +pub fn modifier( + v: &Value, + loaded: &dyn Fn(&str) -> bool, + report: &mut Upgrade, +) -> Option<(&'static str, Value)> { + let t = v["type"].as_str().unwrap_or_default(); + let mut left = |why: &str| *report.modifiers_left.entry(why.to_owned()).or_default() += 1; + let (kind, targets, from, to) = match t { + "lithostitched:add_structure_set_entries" => { + ("structure_set", "structure_sets", "entries", "structures") + } + "lithostitched:add_template_pool_elements" => { + ("template_pool", "template_pools", "elements", "elements") + } + _ => { + left(t); + return None; + } + }; + if !conditions_hold(v, loaded) { + left("conditions"); + return None; + } + let targets: Option<Vec<&str>> = match &v[targets] { + Value::String(s) => Some(vec![s.as_str()]), + Value::Array(a) => a.iter().map(Value::as_str).collect(), + _ => None, + }; + let Some(targets) = targets.filter(|t| !t.is_empty() && t.iter().all(|t| !t.starts_with('#'))) + else { + left("target"); + return None; + }; + let entries = v[from].as_array().cloned().unwrap_or_default(); + for target in &targets { + *report.added_to.entry((*target).to_owned()).or_default() += entries.len(); + } + Some(( + kind, + serde_json::json!({"horizon:add_to": targets, to: entries}), + )) +} + +/// Whether a modifier's load conditions hold: lithostitched's `predicate`, +/// and the loader's conditions (NeoForge's, else Fabric's). A condition +/// type not known here does not hold. +fn conditions_hold(v: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let all = |list: &Value, test: &dyn Fn(&Value) -> bool| { + list.as_array().is_some_and(|a| a.iter().all(test)) + }; + fn predicate(p: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| predicate(q, loaded); + let list = &p["predicates"]; + match p["type"] + .as_str() + .map(|t| t.trim_start_matches("lithostitched:")) + { + Some("true") => true, + Some("mod_loaded") => p["mod_id"].as_str().is_some_and(loaded), + Some("not") => !predicate(&p["predicate"], loaded), + Some("all_of") => list.as_array().is_some_and(|a| a.iter().all(test)), + Some("any_of") => list.as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn neoforge(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| neoforge(q, loaded); + match c["type"].as_str() { + Some("neoforge:true") => true, + Some("neoforge:mod_loaded") => c["modid"].as_str().is_some_and(loaded), + Some("neoforge:not") => !neoforge(&c["value"], loaded), + Some("neoforge:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("neoforge:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + fn fabric(c: &Value, loaded: &dyn Fn(&str) -> bool) -> bool { + let test = |q: &Value| fabric(q, loaded); + let mods = || { + c["values"] + .as_array() + .into_iter() + .flatten() + .map(Value::as_str) + }; + match c["condition"].as_str() { + Some("fabric:true") => true, + Some("fabric:all_mods_loaded") => mods().all(|m| m.is_some_and(loaded)), + Some("fabric:any_mods_loaded") => mods().any(|m| m.is_some_and(loaded)), + Some("fabric:not") => !fabric(&c["value"], loaded), + Some("fabric:and") => c["values"].as_array().is_some_and(|a| a.iter().all(test)), + Some("fabric:or") => c["values"].as_array().is_some_and(|a| a.iter().any(test)), + _ => false, + } + } + let litho = v.get("predicate").is_none_or(|p| predicate(p, loaded)); + let loader = match ( + v.get("neoforge:conditions"), + v.get("fabric:load_conditions"), + ) { + (Some(c), _) => all(c, &|c| neoforge(c, loaded)), + // One condition or a list of them. + (None, Some(c)) if c.is_array() => all(c, &|c| fabric(c, loaded)), + (None, Some(c)) => fabric(c, loaded), + (None, None) => true, + }; + litho && loader +} + +/// ChoiceTheorem's Overhauled Village's villages and outposts, which it adds +/// to vanilla's `villages` and `pillager_outposts` sets in Java code +/// (`CTOV.registerstructure`, through lithostitched), with its default +/// config: every village type in three sizes, weighted 10, 4 and 1, and +/// every outpost weighted 1. Vanilla's own entries stay (weight 1 each). +const CTOV_VILLAGES: [&str; 21] = [ + "beach", + "christmas", + "desert", + "desert_oasis", + "dark_forest", + "jungle", + "jungle_tree", + "mesa", + "mesa_fortified", + "mountain", + "mountain_alpine", + "mushroom", + "plains", + "plains_fortified", + "savanna", + "savanna_na", + "snowy_igloo", + "swamp", + "swamp_fortified", + "taiga", + "taiga_fortified", +]; +const CTOV_OUTPOSTS: [&str; 11] = [ + "beach", + "dark_forest", + "desert", + "jungle", + "badlands", + "mountain", + "plains", + "savanna", + "snowy", + "swamp", + "taiga", +]; + +/// The entries a mod adds to other structure sets in Java code, as its +/// default config has them: (file name, set, `[(structure, weight)]`). +/// Lithostitched appends them in the order of a hash map of every modifier +/// in the pack, which carry cannot know; they are written in the order the +/// mod registers them. Each set picks by weight, so how often each starts +/// is the same. +pub fn code_set_entries(mod_id: &str) -> Vec<(&'static str, &'static str, Vec<(String, u32)>)> { + match mod_id { + "ctov" => { + let outposts = CTOV_OUTPOSTS + .iter() + .map(|v| (format!("ctov:pillager_outpost_{v}"), 1)) + .collect(); + let villages = [("small", 10), ("medium", 4), ("large", 1)] + .into_iter() + .flat_map(|(size, weight)| { + CTOV_VILLAGES + .iter() + .map(move |v| (format!("ctov:{size}/village_{v}"), weight)) + }) + .collect(); + vec![ + ("pillager_outposts", "minecraft:pillager_outposts", outposts), + ("villages", "minecraft:villages", villages), + ] + } + _ => Vec::new(), + } } /// Rewrites one `data/<ns>/worldgen/<kind>/...` file in place; whether it @@ -90,55 +354,57 @@ pub fn upgrade( ) -> 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 + let renamed = crate::carry::renamed_ids(v); + let dropped = crate::processors::each_list(kind, v, &mut |list| { + drop_java_processors(list, &mut report.processors_dropped) + }); + upgrade_types(kind, v, report, set_tags) || states || dropped || renamed } -/// 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 +/// Takes the processors written in Java (any type outside `minecraft:` and +/// the game's own `horizon:`) out of a processor list: `{"processors": +/// [...]}`, a bare list, or an id (left as it is). The ones with a data form +/// were rewritten before ([`crate::processors::carry`]). 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<String, usize>) -> 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 Some(processors) = crate::processors::processors(list) else { + 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:"); + let java = !t.starts_with("minecraft:") && !t.starts_with("horizon:"); if java { *dropped.entry(t.to_owned()).or_default() += 1; } !java }); - processors.len() != before + let mut changed = processors.len() != before; + // The inline lists inside the game's apply_random and condition. + for p in processors.iter_mut() { + let inner: Vec<&mut Value> = match p["processor_type"].as_str() { + Some("horizon:apply_random") => p["processor_lists"] + .as_array_mut() + .into_iter() + .flatten() + .map(|e| &mut e["data"]) + .collect(), + Some("horizon:condition") => { + let o = p.as_object_mut().into_iter().flat_map(|o| o.iter_mut()); + o.filter(|(k, _)| *k == "then" || *k == "else") + .map(|(_, v)| v) + .collect() + } + _ => Vec::new(), + }; + for list in inner { + changed |= drop_java_processors(list, dropped); + } + } + changed } /// 1.21.1 writes a block or fluid state as `{"Name": ..., "Properties": @@ -180,12 +446,45 @@ fn upgrade_types( 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", + // Better Dungeons' small Nether dungeon is YUNG's jigsaw behind a + // config switch that ships on. + Some("yungsapi:yung_jigsaw" | "betterdungeons:small_nether_dungeon") => { + yung_structure(v, lost); + true + } + Some(t) + if JIGSAWS.contains(&t) + || NETHER_JIGSAWS.contains(&t) + || t == REPURPOSED_MINESHAFT + || REPURPOSED_CHECKED.iter().any(|(r, _)| *r == t) => + { + let mineshaft = t == REPURPOSED_MINESHAFT; + let check = REPURPOSED_CHECKED.iter().find(|(r, _)| *r == t); + let check = check.map(|(_, c)| *c); + let library = match t.split_once(':').map(|(ns, _)| ns) { + Some("moogs_structures") => Some("moogs"), + Some("repurposed_structures") => Some("repurposed"), + _ => None, }; - start_checks(v, liquid, lost); + let liquid = if library == Some("moogs") { + "top" + } else { + "lowest" + }; + let mut limited = library.map(|l| piece_limited(v, l)); + if let Some(limited) = limited.as_mut().filter(|_| mineshaft) { + limited["layout"] = "mineshaft".into(); + } + start_checks(v, liquid, lost, limited.is_some()); + if let Some(check) = check { + if !v["horizon:start_checks"].is_object() { + v["horizon:start_checks"] = Value::Object(Default::default()); + } + v["horizon:start_checks"]["repurposed"] = check.into(); + } + if let Some(limited) = limited { + v["horizon:piece_limited"] = limited; + } v["type"] = "minecraft:jigsaw".into(); true } @@ -206,6 +505,11 @@ fn upgrade_types( p["type"] = "minecraft:random_spread".into(); true } + Some(t) if YUNG_SPREADS.contains(&t) => { + let t = t.to_owned(); + yung_placement(&t, &mut v["placement"], set_tags, lost); + true + } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -231,6 +535,9 @@ fn upgrade_types( if let Some((_, to)) = ELEMENTS.iter().find(|(from, _)| *from == t) { element["element_type"] = (*to).into(); changed = true; + } else if t == "yungsapi:yung_single_element" { + yung_element(element, lost); + changed = true; } else if !t.starts_with("minecraft:") { unsupported(t); } @@ -243,10 +550,122 @@ fn upgrade_types( changed } +/// YUNG's API's jigsaw as vanilla's, laid out by its own assembler in the +/// game (`horizon:yungsapi`, `horizon_world::worldgen::structure::yung`): +/// the heights pieces stay within move under the key. Its terrain +/// adaptation and a start offset in the chunk are lost. +fn yung_structure(v: &mut Value, lost: &mut BTreeMap<String, usize>) { + let Some(o) = v.as_object_mut() else { + return; + }; + o.insert("type".into(), "minecraft:jigsaw".into()); + let mut rules = serde_json::Map::new(); + for key in ["min_y", "max_y"] { + if let Some(y) = o.remove(key) { + rules.insert(key.into(), y); + } + } + let none = |a: &Value| a["type"] == "yungsapi:none"; + if o.remove("enhanced_terrain_adaptation") + .is_some_and(|a| !none(&a)) + { + *lost + .entry("enhanced_terrain_adaptation".into()) + .or_default() += 1; + } + for key in ["x_offset_in_chunk", "z_offset_in_chunk"] { + if o.remove(key).is_some_and(|n| n != 0) { + *lost.entry(key.into()).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// YUNG's single pool element as vanilla's, its rules under +/// `horizon:yungsapi`: name and `max_count`, depth range, priority, +/// `ignore_bounds` and its condition. Its terrain adaptation, dead-end pool +/// and modifiers are lost. +fn yung_element(element: &mut Value, lost: &mut BTreeMap<String, usize>) { + let Some(o) = element.as_object_mut() else { + return; + }; + o.insert( + "element_type".into(), + "minecraft:single_pool_element".into(), + ); + let mut rules = serde_json::Map::new(); + for (from, to) in [ + ("name", "name"), + ("max_count", "max_count"), + ("min_required_depth", "min_depth"), + ("max_possible_depth", "max_depth"), + ("is_priority", "priority"), + ("ignore_bounds", "ignore_bounds"), + ] { + if let Some(x) = o.remove(from) { + rules.insert(to.into(), x); + } + } + if let Some(c) = o.remove("condition") { + rules.insert("condition".into(), yung_condition(&c, lost)); + } + for key in ["enhanced_terrain_adaptation", "deadend_pool", "modifiers"] { + let empty = + |x: &Value| x.as_array().is_some_and(Vec::is_empty) || x["type"] == "yungsapi:none"; + if o.remove(key).is_some_and(|x| !empty(&x)) { + *lost.entry(format!("yungsapi {key}")).or_default() += 1; + } + } + o.insert("horizon:yungsapi".into(), rules.into()); +} + +/// One of YUNG's structure conditions in the game's terms. `mod_loaded` +/// holds for Minecraft alone: a mod that needs code is not ported, and the +/// pieces it guards would place its blocks. A condition the game does not +/// have does not hold, and is counted. +fn yung_condition(c: &Value, lost: &mut BTreeMap<String, usize>) -> Value { + let t = c["type"].as_str().unwrap_or_default(); + let list = |lost: &mut BTreeMap<String, usize>| -> Value { + let all = c["conditions"].as_array().into_iter().flatten(); + all.map(|x| yung_condition(x, lost)) + .collect::<Vec<_>>() + .into() + }; + let opt = |k: &str| c.get(k).cloned().unwrap_or(Value::Null); + match t.trim_start_matches("yungsapi:") { + "always_true" => serde_json::json!({"type": "true"}), + "not" => { + serde_json::json!({"type": "not", "condition": yung_condition(&c["condition"], lost)}) + } + "all_of" => serde_json::json!({"type": "all_of", "conditions": list(lost)}), + "any_of" => serde_json::json!({"type": "any_of", "conditions": list(lost)}), + "depth" => serde_json::json!({"type": "depth", + "min_depth": opt("min_required_depth"), "max_depth": opt("max_possible_depth")}), + "altitude" => serde_json::json!({"type": "altitude", + "bottom": opt("bottom_cutoff_y"), "top": opt("top_cutoff_y")}), + "random_chance" => serde_json::json!({"type": "random_chance", "chance": opt("chance")}), + "rotation" => serde_json::json!({"type": "rotation", "rotations": opt("rotations")}), + "piece_in_horizontal_direction" => { + // "yungsapi:all" (or no list) matches any piece. + let pieces: Vec<Value> = c["pieces"].as_array().cloned().unwrap_or_default(); + let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); + serde_json::json!({"type": "piece_in_horizontal_direction", + "pieces": if any { Vec::new() } else { pieces }, + "range": opt("range"), "rotation": opt("rotation")}) + } + "mod_loaded" if c["modid"] == "minecraft" => serde_json::json!({"type": "true"}), + "mod_loaded" => serde_json::json!({"type": "false"}), + _ => { + *lost.entry(format!("yungsapi condition {t}")).or_default() += 1; + serde_json::json!({"type": "false"}) + } + } +} + /// 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<String, usize>) { +fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap<String, usize>, limited: bool) { let Some(o) = v.as_object_mut() else { return; }; @@ -266,8 +685,12 @@ fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap<String, usize>) checks.insert(to.into(), n.clone()); } } + for field in DEAD_FIELDS { + o.remove(field); + } for rule in LAYOUT_RULES { - if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) { + let kept = limited && PIECE_LIMITED_RULES.contains(&rule); + if o.remove(rule).is_some_and(|r| r != Value::Bool(false)) && !kept { *lost.entry(rule.into()).or_default() += 1; } } @@ -276,6 +699,121 @@ fn start_checks(v: &mut Value, liquid: &str, lost: &mut BTreeMap<String, usize>) } } +/// A Repurposed Structures or Moog's jigsaw's layout rules for the game's +/// piece-limited assembler: y_allowance, burying, the pools whose fallbacks +/// ignore the bounds, liquid, and the Nether variants' land search. The +/// bounding box hack is vanilla's expansion hack. The pieces' counts are +/// added from the mod's count files ([`piece_counts`]). +fn piece_limited(v: &mut Value, library: &str) -> Value { + let mut out = serde_json::Map::new(); + out.insert("library".into(), library.into()); + let lower = |x: &Value| x.as_str().map(str::to_ascii_lowercase); + for (from, to) in [("min_y_allowed", "min_y"), ("max_y_allowed", "max_y")] { + if let Some(n) = v.get("y_allowance").and_then(|y| y.get(from)) { + out.insert(to.into(), n.clone()); + } + } + if let Some(b) = v.get("burying_type").and_then(lower) { + out.insert("burying".into(), b.into()); + } + if v["cannot_spawn_in_liquid"].as_bool() == Some(true) { + out.insert("no_liquid".into(), true.into()); + } + if let Some(pools) = v + .get("pools_that_ignore_boundaries") + .filter(|p| p.is_array()) + { + out.insert("ignore_bounds_pools".into(), pools.clone()); + } + if v["use_bounding_box_hack"].as_bool() == Some(true) { + v["use_expansion_hack"] = true.into(); + } + if let Some(o) = v.as_object_mut() { + if let Some(search) = o.remove("land_search_direction") { + out.insert("land_search".into(), lower(&search).into()); + } + if let Some(ledge) = o.remove("ledge_offset_y") { + out.insert("ledge_offset_y".into(), ledge); + } + } + out.into() +} + +/// The pieces' spawn counts of the structures a mod ships, by structure id: +/// Repurposed Structures' `rs_pieces_spawn_counts` (each file names its +/// `target_structure`) and Moog's `msl_pieces_spawn_counts` (the file's id), +/// in the game's `horizon:piece_limited` shape. +pub fn piece_counts<R: Read + std::io::Seek>( + zip: &mut zip::ZipArchive<R>, +) -> BTreeMap<String, Value> { + let mut out = BTreeMap::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let name = entry.name().to_owned(); + let Some((ns, rest)) = name + .strip_prefix("data/") + .and_then(|r| r.strip_suffix(".json")) + .and_then(|r| r.split_once('/')) + else { + continue; + }; + let (rs, path) = if let Some(p) = rest.strip_prefix("rs_pieces_spawn_counts/") { + (true, p) + } else if let Some(p) = rest.strip_prefix("msl_pieces_spawn_counts/") { + (false, p) + } else { + continue; + }; + let mut text = String::new(); + let Ok(v) = entry + .read_to_string(&mut text) + .map_err(|_| ()) + .and_then(|_| serde_json::from_str::<Value>(&text).map_err(|_| ())) + else { + continue; + }; + let id = match v["target_structure"].as_str() { + Some(target) if rs => target.to_owned(), + _ if rs => continue, + _ => format!("{ns}:{path}"), + }; + let pieces: Vec<Value> = v["pieces_spawn_counts"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| { + let mut e = serde_json::Map::new(); + e.insert("name".into(), p["nbt_piece_name"].as_str()?.into()); + for (from, to) in [ + ("always_spawn_this_many", "required"), + ("never_spawn_more_than_this_many", "max"), + ("minimum_distance_from_center_piece", "min_depth"), + ] { + if let Some(n) = p.get(from).filter(|n| n.is_number()) { + e.insert(to.into(), n.clone()); + } + } + Some(Value::Object(e)) + }) + .collect(); + out.insert(id, pieces.into()); + } + out +} + +/// Adds a structure's piece counts to its `horizon:piece_limited` key. +pub fn add_piece_counts(id: &str, v: &mut Value, counts: &BTreeMap<String, Value>) -> bool { + match (counts.get(id), v.get_mut("horizon:piece_limited")) { + (Some(pieces), Some(limited)) => { + limited["pieces"] = pieces.clone(); + true + } + _ => false, + } +} + /// 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 @@ -306,7 +844,10 @@ fn placement_rules( 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 zone = ["super_exclusion_zone", "enhanced_exclusion_zone"] + .into_iter() + .find_map(|k| Some((k, o.remove(k)?))); + if let Some((key, zone)) = zone { let sets: Vec<String> = match &zone["other_set"] { Value::String(s) => match s.strip_prefix('#') { Some(tag) => set_tags.get(tag).cloned().unwrap_or_default(), @@ -319,7 +860,7 @@ fn placement_rules( _ => Vec::new(), }; if sets.is_empty() { - *lost.entry("super_exclusion_zone".into()).or_default() += 1; + *lost.entry(key.into()).or_default() += 1; } else { o.insert( "horizon:exclusion_zone".into(), @@ -329,6 +870,65 @@ fn placement_rules( } } +/// One of YUNG's placements as vanilla's random spread with `horizon:` keys: +/// the enhanced exclusion zone as `horizon:exclusion_zone`; the temples' +/// ocean and river search (findBiomeHorizontal around the chunk's middle +/// block at y 120, 48 blocks, every 2 quarts) as `horizon:avoid_biomes`; the +/// strongholds' rings as `horizon:ring_sections`. +fn yung_placement( + t: &str, + p: &mut Value, + set_tags: &BTreeMap<String, Vec<String>>, + lost: &mut BTreeMap<String, usize>, +) { + placement_rules(p, set_tags, lost); + p["type"] = "minecraft:random_spread".into(); + let Some(o) = p.as_object_mut() else { + return; + }; + match t { + "betterdeserttemples:desert_temple" | "betterjungletemples:jungle_temple" => { + o.insert( + "horizon:avoid_biomes".into(), + serde_json::json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}), + ); + } + "betterstrongholds:stronghold" => { + let mut rings = serde_json::Map::new(); + for (from, to) in [ + ("chunk_distance_to_first_ring", "distance_to_first_ring"), + ("ring_chunk_thickness", "thickness"), + ("max_ring_section", "max_section"), + ] { + if let Some(n) = o.remove(from) { + rings.insert(to.into(), n); + } + } + o.insert("horizon:ring_sections".into(), rings.into()); + } + _ => {} + } +} + +/// Marks a YUNG's structure that the game can start (its type is vanilla's +/// after the upgrade) with the vanilla type its mod turns off, under +/// `horizon:disables`. One the game cannot start leaves the vanilla +/// structure in place, so the world keeps one of the two. +pub fn disables(id: &str, v: &mut Value) -> bool { + let Some((_, vanilla)) = YUNG_REPLACES.iter().find(|(s, _)| id.starts_with(s)) else { + return false; + }; + if !v["type"] + .as_str() + .is_some_and(|t| t.starts_with("minecraft:")) + { + return false; + } + v["horizon:disables"] = serde_json::json!([vanilla]); + true +} + /// The mod's structure set tags (`data/<ns>/tags/worldgen/structure_set/`), /// by tag id, with the tags they include expanded. Optional entries /// (`{"id": ..., "required": false}`) count as their id. @@ -476,9 +1076,8 @@ mod tests { 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 formation = json!({"type": "formations:simple"}); + assert!(!upgrade("structure", &mut formation, &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)); @@ -499,7 +1098,7 @@ mod tests { {"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"}} + {"weight": 1, "element": {"element_type": "somelib:element"}} ]}); assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); assert_eq!( @@ -515,11 +1114,8 @@ mod tests { assert_eq!( report.unsupported, BTreeMap::from([ - ( - "moogs_structures:moogs_structures_generic_nether_jigsaw_structure".into(), - 1 - ), - ("yungsapi:yung_single_element".into(), 1), + ("formations:simple".into(), 1), + ("somelib:element".into(), 1), ]) ); } @@ -547,18 +1143,37 @@ mod tests { assert!(moogs.get(gone).is_none(), "{gone}"); } assert_eq!(moogs["size"], 7); - // Repurposed Structures reads the block above the bottom. + // Repurposed Structures reads the block above the bottom. Its jungle + // fortress's vertical distance is a field its code no longer reads. let mut rs = json!({"type": "repurposed_structures:generic_jigsaw_structure", - "cannot_spawn_in_liquid": true}); + "cannot_spawn_in_liquid": true, "vertical_distance_from_start_piece": 35}); assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); assert_eq!(rs["horizon:start_checks"], json!({"liquid": "lowest"})); + assert!(rs.get("vertical_distance_from_start_piece").is_none()); + // Repurposed's own checks: the Nether city, Nether shipwrecks, the End stronghold. + for (t, check) in [ + ("city_nether_structure", "city_nether"), + ("shipwreck_nether_structure", "shipwreck_nether"), + ("stronghold_end", "stronghold_end"), + ] { + let mut rs = json!({"type": format!("repurposed_structures:{t}"), + "cannot_spawn_in_liquid": false, "size": 7}); + assert!(upgrade("structure", &mut rs, &mut report, &NO_TAGS)); + assert_eq!(rs["type"], "minecraft:jigsaw"); + assert_eq!(rs["horizon:start_checks"], json!({"repurposed": check})); + assert_eq!(rs["horizon:piece_limited"]["library"], "repurposed"); + } + assert!(report.unsupported.is_empty()); // 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()); + // The layout rules go to the piece-limited assembler. + assert!(report.rules_lost.is_empty()); assert_eq!( - report.rules_lost, - BTreeMap::from([("burying_type".into(), 1), ("y_allowance".into(), 1)]) + moogs["horizon:piece_limited"], + json!({"library": "moogs", "min_y": 60, "burying": "lowest_corner", + "no_liquid": true}) ); } @@ -599,6 +1214,65 @@ mod tests { assert_eq!(report.rules_lost["super_exclusion_zone"], 1); } + #[test] + fn yungs_jigsaws_keep_their_rules() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "yungsapi:yung_jigsaw", "start_pool": "y:start", "size": 20, + "max_y": 60, "x_offset_in_chunk": 0, "max_distance_from_center": 80, + "enhanced_terrain_adaptation": {"type": "yungsapi:custom", "kernel_size": 24}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "minecraft:jigsaw"); + assert_eq!(s["horizon:yungsapi"], json!({"max_y": 60})); + for gone in ["max_y", "x_offset_in_chunk", "enhanced_terrain_adaptation"] { + assert!(s.get(gone).is_none(), "{gone}"); + } + // Better Dungeons' small Nether dungeon is the same jigsaw. + let mut nether = json!({"type": "betterdungeons:small_nether_dungeon", + "start_pool": "betterdungeons:small_nether_dungeon", "size": 10, + "start_jigsaw_name": "betterdungeons:small_nether_dungeon_anchor", + "max_distance_from_center": 80, "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!(nether["horizon:yungsapi"], json!({})); + assert_eq!( + nether["start_jigsaw_name"], + "betterdungeons:small_nether_dungeon_anchor" + ); + assert!(report.unsupported.is_empty()); + let mut pool = json!({"elements": [{"weight": 3, "element": { + "element_type": "yungsapi:yung_single_element", "location": "y:room", + "processors": "minecraft:empty", "projection": "rigid", + "name": "room", "max_count": 2, "min_required_depth": 1, "is_priority": true, + "ignore_bounds": false, "deadend_pool": "y:end", + "condition": {"type": "yungsapi:all_of", "conditions": [ + {"type": "yungsapi:piece_in_horizontal_direction", "pieces": ["yungsapi:all"], + "range": 5, "rotation": "none"}, + {"type": "yungsapi:not", "condition": {"type": "yungsapi:mod_loaded", "modid": "create"}}, + {"type": "yungsapi:biome", "biomes": []}]}}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + let e = &pool["elements"][0]["element"]; + assert_eq!(e["element_type"], "minecraft:single_pool_element"); + assert_eq!(e["location"], "y:room"); + assert_eq!( + e["horizon:yungsapi"], + json!({"name": "room", "max_count": 2, "min_depth": 1, "priority": true, + "ignore_bounds": false, "condition": {"type": "all_of", "conditions": [ + {"type": "piece_in_horizontal_direction", "pieces": [], "range": 5, "rotation": "none"}, + {"type": "not", "condition": {"type": "false"}}, + {"type": "false"}]}}) + ); + assert!(e.get("deadend_pool").is_none()); + assert_eq!( + report.rules_lost, + BTreeMap::from([ + ("enhanced_terrain_adaptation".into(), 1), + ("yungsapi condition yungsapi:biome".into(), 1), + ("yungsapi deadend_pool".into(), 1), + ]) + ); + assert!(report.unsupported.is_empty()); + } + #[test] fn drops_processors_written_in_java() { let mut report = Upgrade::default(); @@ -643,6 +1317,138 @@ mod tests { ); } + #[test] + fn yungs_placements_keep_their_rules() { + let tags = BTreeMap::from([( + "bf:avoid".to_owned(), + vec!["minecraft:nether_complexes".to_owned()], + )]); + let mut report = Upgrade::default(); + let mut fortress = json!({"placement": {"type": "yungsapi:enhanced_random_spread", + "salt": 1, "spacing": 30, "separation": 20, + "enhanced_exclusion_zone": {"other_set": "#bf:avoid", "chunk_count": 10}}}); + assert!(upgrade("structure_set", &mut fortress, &mut report, &tags)); + assert_eq!( + fortress["placement"], + json!({"type": "minecraft:random_spread", "salt": 1, "spacing": 30, "separation": 20, + "horizon:exclusion_zone": {"other_sets": ["minecraft:nether_complexes"], "chunk_count": 10}}) + ); + let mut temple = json!({"placement": {"type": "betterdeserttemples:desert_temple", + "salt": 2, "spacing": 30, "separation": 20, + "exclusion_zone": {"other_set": "minecraft:villages", "chunk_count": 6}}}); + assert!(upgrade("structure_set", &mut temple, &mut report, &tags)); + assert_eq!(temple["placement"]["type"], "minecraft:random_spread"); + assert_eq!(temple["placement"]["exclusion_zone"]["chunk_count"], 6); + assert_eq!( + temple["placement"]["horizon:avoid_biomes"], + json!({"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], + "radius": 48, "step": 2, "y": 120}) + ); + let mut stronghold = json!({"placement": {"type": "betterstrongholds:stronghold", + "salt": 3, "spacing": 85, "separation": 50, + "chunk_distance_to_first_ring": 80, "ring_chunk_thickness": 96}}); + assert!(upgrade( + "structure_set", + &mut stronghold, + &mut report, + &tags + )); + assert_eq!( + stronghold["placement"], + json!({"type": "minecraft:random_spread", "salt": 3, "spacing": 85, "separation": 50, + "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96}}) + ); + assert_eq!(report.mapped, 3); + assert!(report.unsupported.is_empty()); + // The vanilla counterpart is turned off only for a structure the game starts. + let mut ported = json!({"type": "minecraft:jigsaw"}); + assert!(disables("betterstrongholds:stronghold", &mut ported)); + assert_eq!(ported["horizon:disables"], json!(["minecraft:stronghold"])); + let mut java = json!({"type": "bettermineshafts:mineshaft"}); + assert!(!disables("bettermineshafts:mineshaft_oak", &mut java)); + let mut circle = json!({"type": "minecraft:jigsaw"}); + assert!(!disables("betterwitchhuts:witch_circle", &mut circle)); + } + + #[test] + fn piece_limited_jigsaws_keep_their_layout() { + let mut report = Upgrade::default(); + let mut nether = json!({"type": "repurposed_structures:generic_nether_jigsaw_structure", + "start_pool": "rs:x", "size": 8, "y_allowance": {"min_y_allowed": 40, "max_y_allowed": 90}, + "cannot_spawn_in_liquid": true, "pools_that_ignore_boundaries": ["rs:roof"], + "use_bounding_box_hack": true, "land_search_direction": "HIGHEST_LAND", + "ledge_offset_y": 2}); + assert!(upgrade("structure", &mut nether, &mut report, &NO_TAGS)); + assert_eq!(nether["type"], "minecraft:jigsaw"); + assert_eq!( + nether["horizon:piece_limited"], + json!({"library": "repurposed", "min_y": 40, "max_y": 90, "no_liquid": true, + "ignore_bounds_pools": ["rs:roof"], "land_search": "highest_land", + "ledge_offset_y": 2}) + ); + assert_eq!(nether["use_expansion_hack"], true); + for gone in [ + "y_allowance", + "use_bounding_box_hack", + "land_search_direction", + "ledge_offset_y", + ] { + assert!(nether.get(gone).is_none(), "{gone}"); + } + let mut moogs = json!({"type": "moogs_structures:moogs_structures_generic_jigsaw_structure", + "burying_type": "AVERAGE_LAND"}); + assert!(upgrade("structure", &mut moogs, &mut report, &NO_TAGS)); + assert_eq!( + moogs["horizon:piece_limited"], + json!({"library": "moogs", "burying": "average_land"}) + ); + // Repurposed's mineshaft is laid out under the terrain. + let mut mineshaft = json!({"type": "repurposed_structures:generic_mineshaft", + "start_pool": "rs:mineshafts/birch/start_pool", "size": 9, + "liquid_settings": "ignore_waterlogging"}); + assert!(upgrade("structure", &mut mineshaft, &mut report, &NO_TAGS)); + assert_eq!(mineshaft["type"], "minecraft:jigsaw"); + assert_eq!( + mineshaft["horizon:piece_limited"], + json!({"library": "repurposed", "layout": "mineshaft"}) + ); + assert_eq!(mineshaft["liquid_settings"], "ignore_waterlogging"); + // Lithostitched's jigsaw is vanilla's: no key. + let mut litho = json!({"type": "lithostitched:jigsaw"}); + assert!(upgrade("structure", &mut litho, &mut report, &NO_TAGS)); + assert!(litho.get("horizon:piece_limited").is_none()); + assert!(report.rules_lost.is_empty(), "{:?}", report.rules_lost); + assert!(report.unsupported.is_empty()); + + let mut zip = zip::ZipWriter::new(std::io::Cursor::new(Vec::new())); + let opts = zip::write::SimpleFileOptions::default(); + for (name, text) in [ + ( + "data/rs/rs_pieces_spawn_counts/city.json", + r#"{"target_structure": "rs:city_nether", "pieces_spawn_counts": [ + {"nbt_piece_name": "rs:city/center", "always_spawn_this_many": 1, + "never_spawn_more_than_this_many": 1, "minimum_distance_from_center_piece": 3}]}"#, + ), + ( + "data/mvs/msl_pieces_spawn_counts/tower.json", + r#"{"pieces_spawn_counts": [{"nbt_piece_name": "mvs:top", "never_spawn_more_than_this_many": 2}]}"#, + ), + ] { + 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 counts = piece_counts(&mut zip); + assert_eq!( + counts["rs:city_nether"], + json!([{"name": "rs:city/center", "required": 1, "max": 1, "min_depth": 3}]) + ); + assert_eq!(counts["mvs:tower"], json!([{"name": "mvs:top", "max": 2}])); + assert!(add_piece_counts("rs:city_nether", &mut nether, &counts)); + assert_eq!(nether["horizon:piece_limited"]["pieces"][0]["required"], 1); + assert!(!add_piece_counts("rs:other", &mut nether, &counts)); + } + #[test] fn writes_block_states_in_26_3_shape() { let mut report = Upgrade::default(); @@ -675,6 +1481,88 @@ mod tests { assert_eq!(report.mapped, 0); } + #[test] + fn modifiers_add_to_sets_and_pools() { + let mut report = Upgrade::default(); + let only_fd = |m: &str| m == "farmersdelight"; + let set = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "minecraft:villages", + "entries": [{"structure": "x:village", "weight": 4}]}); + let (kind, added) = modifier(&set, &only_fd, &mut report).unwrap(); + assert_eq!(kind, "structure_set"); + assert_eq!( + added, + json!({"horizon:add_to": ["minecraft:villages"], + "structures": [{"structure": "x:village", "weight": 4}]}) + ); + // A compat addition holds only when its mod is ported along. + let pool = |modid: &str| { + json!({"type": "lithostitched:add_template_pool_elements", + "neoforge:conditions": [{"type": "neoforge:mod_loaded", "modid": modid}], + "fabric:load_conditions": {"condition": "fabric:all_mods_loaded", "values": ["other"]}, + "template_pools": ["x:houses", "y:houses"], + "elements": [{"weight": 5, "element": {"element_type": "minecraft:single_pool_element", + "location": "x:fd_farm", "projection": "rigid", "processors": "minecraft:empty"}}]}) + }; + let (kind, added) = modifier(&pool("farmersdelight"), &only_fd, &mut report).unwrap(); + assert_eq!(kind, "template_pool"); + assert_eq!(added["horizon:add_to"], json!(["x:houses", "y:houses"])); + assert_eq!(added["elements"][0]["weight"], 5); + assert!(modifier(&pool("create"), &only_fd, &mut report).is_none()); + // Fabric's conditions when there are no NeoForge ones; lithostitched's own. + let fabric = json!({"type": "lithostitched:add_structure_set_entries", + "fabric:load_conditions": [{"condition": "fabric:not", + "value": {"condition": "fabric:any_mods_loaded", "values": ["create"]}}], + "predicate": {"type": "lithostitched:all_of", "predicates": [ + {"type": "lithostitched:mod_loaded", "mod_id": "farmersdelight"}, + {"type": "lithostitched:true"}]}, + "structure_sets": "minecraft:villages", "entries": []}); + assert!(modifier(&fabric, &only_fd, &mut report).is_some()); + let tagged = json!({"type": "lithostitched:add_structure_set_entries", + "structure_sets": "#x:sets", "entries": []}); + assert!(modifier(&tagged, &only_fd, &mut report).is_none()); + let features = json!({"type": "lithostitched:add_features"}); + assert!(modifier(&features, &only_fd, &mut report).is_none()); + assert_eq!( + report.added_to, + BTreeMap::from([ + ("minecraft:villages".into(), 1), + ("x:houses".into(), 1), + ("y:houses".into(), 1), + ]) + ); + assert_eq!( + report.modifiers_left, + BTreeMap::from([ + ("conditions".into(), 1), + ("lithostitched:add_features".into(), 1), + ("target".into(), 1), + ]) + ); + } + + #[test] + fn ctov_joins_vanillas_villages_and_outposts() { + let sets = code_set_entries("ctov"); + let (file, set, outposts) = &sets[0]; + assert_eq!( + (*file, *set), + ("pillager_outposts", "minecraft:pillager_outposts") + ); + assert_eq!(outposts.len(), 11); + assert!(outposts.iter().all(|(_, w)| *w == 1)); + let (_, set, villages) = &sets[1]; + assert_eq!(*set, "minecraft:villages"); + assert_eq!(villages.len(), 63); + assert_eq!(villages[0], ("ctov:small/village_beach".into(), 10)); + assert_eq!(villages[21], ("ctov:medium/village_beach".into(), 4)); + assert_eq!( + villages[62], + ("ctov:large/village_taiga_fortified".into(), 1) + ); + assert!(code_set_entries("mvs").is_empty()); + } + #[test] fn convention_tags_include_theirs() { let conventions = BTreeMap::from([ diff --git a/crates/horizon-prepare/src/artifacts.rs b/crates/horizon-prepare/src/artifacts.rs index c9b1947ed..80b3bcf05 100644 --- a/crates/horizon-prepare/src/artifacts.rs +++ b/crates/horizon-prepare/src/artifacts.rs @@ -11,9 +11,10 @@ use std::fs; use std::path::{Component, Path, PathBuf}; const LAUNCHER_HINT: &str = - "Horizon does not download the game: install Minecraft Java Edition with the official \ -launcher, play {version} once, then rerun. If the launcher uses another game directory, \ -pass --minecraft-dir or set HORIZON_MINECRAFT_DIR."; + "Horizon does not download the game: play {version} once in the launcher you play \ +Minecraft Java Edition with (the official launcher, Prism Launcher, MultiMC...) so it downloads \ +the game's files, then rerun. If that launcher keeps them in another folder, pass \ +--minecraft-dir or set HORIZON_MINECRAFT_DIR."; const SERVER_HINT: &str = "Horizon does not download the game: download the {version} server jar yourself (minecraft.net/download/server \ while {version} is the current release, otherwise the downloads.server.url in your launcher's \ versions/{version}/{version}.json), then pass --server-jar PATH or set HORIZON_SERVER_JAR."; @@ -337,8 +338,9 @@ fn native_library_matches(library: &Value, names: &[&str]) -> bool { true } -/// The client libraries the official launcher installs on this OS and architecture. -fn client_library_artifacts(manifest: &Value) -> Result<Vec<&Value>, String> { +/// The client libraries the official launcher installs on this OS and architecture: each +/// library's Maven name and its download. +fn client_library_artifacts(manifest: &Value) -> Result<Vec<(&str, &Value)>, String> { let libraries = manifest .get("libraries") .and_then(Value::as_array) @@ -353,7 +355,8 @@ fn client_library_artifacts(manifest: &Value) -> Result<Vec<&Value>, String> { continue; }; if library_allowed(library)? && native_library_matches(library, &names) { - artifacts.push(artifact); + let name = library.get("name").and_then(Value::as_str).unwrap_or(""); + artifacts.push((name, artifact)); } } Ok(artifacts) @@ -374,6 +377,35 @@ pub(crate) fn safe_relative(path: &str) -> Option<PathBuf> { Some(parts.iter().collect()) } +/// A launcher's copy of the library `name`, whose path in the version JSON is `relative`, under +/// its game folder `minecraft`: at that path, else where Prism Launcher keeps it (#849). Prism's +/// metadata moves a native jar's classifier into its artifact name +/// (`com.mojang:jtracy:1.14.38:natives-windows` is its `com.mojang:jtracy-natives-windows:1.14.38`) +/// and Prism keeps libraries at their name's path, so the same jar, with the same sha1, is in +/// `com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar`. The path the +/// version JSON gives is returned when neither exists, for the error to name. +pub fn launcher_library(minecraft: &Path, name: &str, relative: &Path) -> PathBuf { + let libraries = minecraft.join("libraries"); + let official = libraries.join(relative); + if official.is_file() { + return official; + } + if let [group, artifact, version, classifier] = name.split(':').collect::<Vec<_>>()[..] { + let artifact = format!("{artifact}-{classifier}"); + let path = format!( + "{}/{artifact}/{version}/{artifact}-{version}.jar", + group.replace('.', "/") + ); + if let Some(prism) = safe_relative(&path) + .map(|p| libraries.join(p)) + .filter(|p| p.is_file()) + { + return prism; + } + } + official +} + fn artifact_fields(artifact: &Value) -> Result<(&str, &str), String> { let path = artifact.get("path").and_then(Value::as_str); let sha1 = artifact.get("sha1").and_then(Value::as_str); @@ -502,11 +534,11 @@ pub fn import( let server = import_server(lock, server_jar)?; let (server, server_libraries) = unpack_server(server, &lock.directory, id)?; let mut client_libraries = Vec::new(); - for artifact in client_library_artifacts(&manifest)? { + for (name, artifact) in client_library_artifacts(&manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe library path")?; client_libraries.push(import_copy( - &minecraft.join("libraries").join(&relative), + &launcher_library(&minecraft, name, &relative), &lock.directory.join("libraries/client").join(&relative), sha1, "sha1", @@ -744,7 +776,7 @@ pub fn verify(lock: &Lock) -> Result<Artifacts, String> { /// `client_libraries`); the client-side exporters compile against them. pub fn client_libraries(lock: &Lock, manifest: &Value) -> Result<Vec<PathBuf>, String> { let mut libraries = Vec::new(); - for artifact in client_library_artifacts(manifest)? { + for (_, artifact) in client_library_artifacts(manifest)? { let (path, sha1) = artifact_fields(artifact)?; let relative = safe_relative(path).ok_or("Unsafe client library path")?; let library = lock.directory.join("libraries/client").join(&relative); @@ -992,6 +1024,43 @@ mod tests { ); } + /// A native jar is found where the official launcher keeps it, else under the name Prism + /// Launcher's metadata gives it (#849); a plain library only at the version JSON's path. + #[test] + fn libraries_are_found_where_prism_launcher_keeps_them() { + let fixture = Imports::new(); + let minecraft = &fixture.directory; + let official = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38-natives-windows.jar"); + let name = "com.mojang:jtracy:1.14.38:natives-windows"; + let prism = minecraft.join( + "libraries/com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar", + ); + assert_eq!( + launcher_library(minecraft, name, official), + minecraft.join("libraries").join(official) + ); + fs::create_dir_all(prism.parent().unwrap()).unwrap(); + fs::write(&prism, b"natives").unwrap(); + assert_eq!(launcher_library(minecraft, name, official), prism); + let mojang = minecraft.join("libraries").join(official); + fs::create_dir_all(mojang.parent().unwrap()).unwrap(); + fs::write(&mojang, b"natives").unwrap(); + assert_eq!(launcher_library(minecraft, name, official), mojang); + let plain = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38.jar"); + assert_eq!( + launcher_library(minecraft, "com.mojang:jtracy:1.14.38", plain), + minecraft.join("libraries").join(plain) + ); + for unsafe_name in ["a:..:1:x", "a:b\\c:1:x"] { + let path = launcher_library(minecraft, unsafe_name, plain); + assert_eq!( + path, + minecraft.join("libraries").join(plain), + "{unsafe_name}" + ); + } + } + #[test] fn natives_follow_the_architecture() { let names = ["a:b:1:natives-macos", "a:b:1:natives-macos-arm64"]; diff --git a/crates/horizon-prepare/src/sounds.rs b/crates/horizon-prepare/src/sounds.rs index b18ed3426..f6ff0b714 100644 --- a/crates/horizon-prepare/src/sounds.rs +++ b/crates/horizon-prepare/src/sounds.rs @@ -53,7 +53,7 @@ fn launcher_object(assets: &Path, checksum: &str) -> Result<PathBuf, String> { let path = object_path(assets, checksum)?; if !path.is_file() { return Err(format!( - "Missing asset object {}. Play the pinned version once in the official launcher.", + "Missing asset object {}. Play the pinned version once in your launcher.", path.display() )); } diff --git a/crates/horizon-protocol/src/chunk.rs b/crates/horizon-protocol/src/chunk.rs index 32d7f98b6..165627d90 100644 --- a/crates/horizon-protocol/src/chunk.rs +++ b/crates/horizon-protocol/src/chunk.rs @@ -57,6 +57,19 @@ pub fn storage_len(bits: u8, entries: usize) -> usize { } } +/// SimpleBitStorage's longs for `values` at `bits` each, a long at a time. +fn pack<T>(values: &[T], bits: u8, id: impl Fn(&T) -> u64) -> Vec<i64> { + let per = 64 / bits as usize; + values + .chunks(per) + .map(|word| { + word.iter() + .enumerate() + .fold(0u64, |w, (k, v)| w | id(v) << (k * bits as usize)) as i64 + }) + .collect() +} + /// One PalettedContainer as sent. #[derive(Clone, Debug, PartialEq)] pub struct Paletted { @@ -160,12 +173,11 @@ impl Paletted { data: Vec::new(), }; } - let mut data = vec![0i64; storage_len(bits, values.len())]; - let per = 64 / bits as usize; - for (i, (&v, &id)) in values.iter().zip(&ids).enumerate() { - let id = if has_palette { u64::from(id) } else { v as u64 }; - data[i / per] |= (id << ((i % per) * bits as usize)) as i64; - } + let data = if has_palette { + pack(&ids, bits, |&id| u64::from(id)) + } else { + pack(values, bits, |&v| v as u64) + }; Self { bits, palette: if has_palette { palette } else { Vec::new() }, diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 895db9755..95a68d1ef 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -244,6 +244,18 @@ packet!(EntityPositionSync { id: i32 => VarInt, path: PositionPath => PositionPa packet!(ForgetLevelChunk { pos: [i32; 2] => ChunkPos }); packet!(GameEvent { event: u8 => UByte, param: f32 => Float }); packet!(HurtAnimation { id: i32 => VarInt, yaw: f32 => Float }); +packet!( + /// ClientboundDamageEventPacket: the hurt entity, the damage type's + /// registry id, the causing and the direct entity (none: -1 on the wire's + /// id + 1) and the source's position. + DamageEvent { + id: i32 => VarInt, + source_type: i32 => VarInt, + cause: Option<i32> => OptVarInt, + direct: Option<i32> => OptVarInt, + position: Option<[f64; 3]> => Opt<Vec3d>, + } +); packet!(LevelChunkWithLight { x: i32 => Int, z: i32 => Int, chunk: ChunkData => ChunkData, light: LightData => LightData }); packet!(LevelEvent { kind: i32 => Int, pos: [i32; 3] => Pos, data: i32 => Int, global: bool => Bool }); packet!(LightUpdate { x: i32 => VarInt, z: i32 => VarInt, light: LightData => LightData }); @@ -881,6 +893,24 @@ packet!( UpdateMobEffect { id: i32 => VarInt, effect: i32 => VarInt, amplifier: i32 => VarInt, duration: i32 => VarInt, flags: i8 => Byte } ); packet!(RemoveMobEffect { id: i32 => VarInt, effect: i32 => VarInt }); +packet!( + /// AttributeModifier.STREAM_CODEC: id, amount and operation (0 add_value, + /// 1 add_multiplied_base, 2 add_multiplied_total). + AttributeModifier { id: String => Ident, amount: f64 => Double, operation: i32 => VarInt } +); +packet!( + /// ClientboundUpdateAttributesPacket.AttributeSnapshot: the attribute's + /// registry id, its base value and every modifier. + AttributeSnapshot { + attribute: i32 => VarInt, + base: f64 => Double, + modifiers: Vec<AttributeModifier> => List<AttributeModifier>, + } +); +packet!( + /// ClientboundUpdateAttributesPacket: an entity's synced attribute instances. + UpdateAttributes { id: i32 => VarInt, values: Vec<AttributeSnapshot> => List<AttributeSnapshot> } +); packet!( /// ClientboundSwingAnimationPacket: hand (0 main, 1 off) and the swing /// type (0 none, 1 whack, 2 stab) with its duration in ticks. @@ -1388,6 +1418,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { GameEvent(GameEvent) = GAME_EVENT, GameRuleValues(GameRuleValues) = GAME_RULE_VALUES, HurtAnimation(HurtAnimation) = HURT_ANIMATION, + DamageEvent(DamageEvent) = DAMAGE_EVENT, KeepAlive(KeepAlive) = KEEP_ALIVE, InitializeBorder(InitializeBorder) = INITIALIZE_BORDER, LevelChunkWithLight(LevelChunkWithLight) = LEVEL_CHUNK_WITH_LIGHT, @@ -1455,6 +1486,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { TickingState(TickingState) = TICKING_STATE, TickingStep(TickingStep) = TICKING_STEP, UpdateAdvancements(UpdateAdvancements) = UPDATE_ADVANCEMENTS, + UpdateAttributes(UpdateAttributes) = UPDATE_ATTRIBUTES, UpdateMobEffect(UpdateMobEffect) = UPDATE_MOB_EFFECT, UpdateTags(UpdateTags) = UPDATE_TAGS, TrackedWaypoint(TrackedWaypoint) = WAYPOINT, @@ -2110,6 +2142,25 @@ mod tests { id: 2, slots: vec![(0, None), (5, Some(Stack::new(1, 1)))], }), + Clientbound::UpdateAttributes(UpdateAttributes { + id: 2, + values: vec![AttributeSnapshot { + attribute: 26, + base: 0.23, + modifiers: vec![AttributeModifier { + id: "minecraft:baby".into(), + amount: 0.5, + operation: 1, + }], + }], + }), + Clientbound::DamageEvent(DamageEvent { + id: 7, + source_type: 31, + cause: Some(0), + direct: None, + position: Some([1.5, -2.0, 3.25]), + }), Clientbound::SetHealth(SetHealth { health: 17.5, food: 18, @@ -2347,4 +2398,31 @@ mod tests { ); assert_eq!(p.encode()[1..], [1, 2, 3]); } + + #[test] + fn update_attributes_encode_like_vanilla() { + let p = Clientbound::UpdateAttributes(UpdateAttributes { + id: 5, + values: vec![AttributeSnapshot { + attribute: 1, + base: 0.0, + modifiers: vec![AttributeModifier { + id: "minecraft:armor.helmet".into(), + amount: 3.0, + operation: 0, + }], + }], + }); + let body = p.encode(); + // The packet id (134) is a two-byte VarInt. + let mut expected = vec![134, 1, 5, 1, 1]; + expected.extend(0.0f64.to_be_bytes()); + expected.extend([1, 22]); + expected.extend(b"minecraft:armor.helmet"); + expected.extend(3.0f64.to_be_bytes()); + expected.push(0); + assert_eq!(body, expected); + assert_eq!(crate::ids::play::clientbound::UPDATE_ATTRIBUTES, 134); + assert_eq!(Clientbound::decode(134, &body[2..]).unwrap(), p); + } } diff --git a/crates/horizon-server/Cargo.toml b/crates/horizon-server/Cargo.toml index c3800b80c..2432cd481 100644 --- a/crates/horizon-server/Cargo.toml +++ b/crates/horizon-server/Cargo.toml @@ -10,6 +10,8 @@ description = "Host a Horizon server: server.toml, the CLI and the supervisor th horizon-server-files = { path = "../horizon-server-files" } # The game process's RAM and CPU (the same probes the benchmark reports use). horizon-bench = { path = "../horizon-bench" } +# The log's local times, as the game prints them. +chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.1" diff --git a/crates/horizon-server/src/engine.rs b/crates/horizon-server/src/engine.rs index c0043e1d3..aa83693cb 100644 --- a/crates/horizon-server/src/engine.rs +++ b/crates/horizon-server/src/engine.rs @@ -11,7 +11,9 @@ use std::{ time::Duration, }; -/// The game's program names, most specific first: a headless engine once there is one, else the game. +/// The game's program names, most specific first: the server build (the game without sound or +/// controllers, so it needs neither ALSA nor udev on Linux; `horizon-server-linux-x86_64.tar.gz` holds it), +/// else the full game. const PROGRAMS: [&str; 2] = ["horizon-engine", "horizon-client"]; fn exe(name: &str) -> String { @@ -49,6 +51,55 @@ pub fn program(config: &Config, dir: &Path) -> Result<PathBuf, String> { }) } +/// Checks that the game program starts at all: `--help` loads no game files, so it fails only when the +/// system can't load the program, as on a Linux without the ALSA and udev libraries the full game links +/// (the server build doesn't). The reason, with what to install. +pub fn check_starts(program: &Path) -> Result<(), String> { + let output = Command::new(program) + .arg("--help") + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .output() + .map_err(|e| format!("the game ({}) can't start: {e}", program.display()))?; + if output.status.success() { + return Ok(()); + } + let stderr = String::from_utf8_lossy(&output.stderr); + Err(start_failure(program, output.status.code(), &stderr)) +} + +/// What to tell the owner when the game program exits at once. +fn start_failure(program: &Path, code: Option<i32>, stderr: &str) -> String { + let reason = stderr + .lines() + .find(|l| !l.trim().is_empty()) + .unwrap_or("") + .trim(); + let mut text = format!( + "the game ({}) can't start{}{}", + program.display(), + code.map_or(String::new(), |c| format!(" (exit status {c})")), + if reason.is_empty() { + String::new() + } else { + format!(": {reason}") + } + ); + if reason.contains("error while loading shared libraries") + && (reason.contains("libasound") || reason.contains("libudev")) + { + text.push_str( + "\nThe full game needs ALSA's and udev's libraries (libasound.so.2, libudev.so.1). Install the \ + server build, which needs neither (packaging/server/install.sh picks it on Linux), or the \ + libraries:\n Debian, Ubuntu: sudo apt install libasound2 libudev1 (Ubuntu 24.04 and later: \ + libasound2t64)\n Fedora, RHEL: sudo dnf install alsa-lib systemd-libs\n Arch: sudo pacman -S \ + alsa-lib systemd-libs\n NixOS: enable programs.nix-ld with alsa-lib and udev in its libraries", + ); + } + text +} + /// Where the prepared game files may be, in the order they are tried. pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) -> Vec<PathBuf> { if !config.engine.resources.is_empty() { @@ -65,12 +116,13 @@ pub fn resource_candidates(config: &Config, dir: &Path, program: Option<&Path>) out } -/// The prepared game files: a folder holding the asset index `horizon-prepare` writes. +/// The prepared game files: a folder holding the manifest every `horizon-prepare` run writes +/// (`asset-index.json` comes only with the optional sounds, which a server doesn't need). pub fn resources(config: &Config, dir: &Path, program: Option<&Path>) -> Result<PathBuf, String> { let candidates = resource_candidates(config, dir, program); candidates .iter() - .find(|d| d.join("asset-index.json").is_file()) + .find(|d| d.join("horizon-resources.json").is_file()) .cloned() .ok_or_else(|| { let tried: Vec<String> = candidates @@ -179,4 +231,73 @@ mod tests { [PathBuf::from("/data/res")] ); } + + #[test] + fn resources_prepared_without_sounds_are_found() { + let root = std::env::temp_dir().join(format!("horizon-server-res-{}", std::process::id())); + let prepared = root.join(".local/horizon-client/26.3"); + std::fs::create_dir_all(&prepared).unwrap(); + let program = root.join("horizon-client"); + let config = Config::default(); + let server = root.join("server"); + assert!(resources(&config, &server, Some(&program)).is_err()); + // What `horizon-prepare` writes on every run; no asset index without `horizon-prepare sounds`. + std::fs::write(prepared.join("horizon-resources.json"), "{}").unwrap(); + assert_eq!(resources(&config, &server, Some(&program)), Ok(prepared)); + std::fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn a_missing_library_says_what_to_install() { + let program = Path::new("/opt/horizon/horizon-client"); + let text = start_failure( + program, + Some(127), + "/opt/horizon/horizon-client: error while loading shared libraries: libasound.so.2: cannot open \ + shared object file: No such file or directory\n", + ); + assert!(text.starts_with( + "the game (/opt/horizon/horizon-client) can't start (exit status 127): /opt/horizon/horizon-client: \ + error while loading shared libraries: libasound.so.2" + )); + assert!(text.contains("sudo apt install libasound2 libudev1")); + // Another library: no ALSA advice (the server build, horizon-engine, links neither). + let engine = start_failure( + Path::new("/opt/horizon/horizon-engine"), + Some(127), + "/opt/horizon/horizon-engine: error while loading shared libraries: libgcc_s.so.1: cannot open \ + shared object file: No such file or directory\n", + ); + assert!(!engine.contains("libasound"), "{engine}"); + let other = start_failure(program, Some(1), "something else\n"); + assert_eq!( + other, + "the game (/opt/horizon/horizon-client) can't start (exit status 1): something else" + ); + } + + #[cfg(unix)] + #[test] + fn the_check_runs_the_program() { + use std::os::unix::fs::PermissionsExt; + let root = + std::env::temp_dir().join(format!("horizon-server-check-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + let script = |name: &str, body: &str| { + let path = root.join(name); + std::fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path + }; + assert_eq!(check_starts(&script("starts", "exit 0")), Ok(())); + let fails = script("fails", "echo 'no luck' >&2; exit 3"); + assert_eq!( + check_starts(&fails), + Err(format!( + "the game ({}) can't start (exit status 3): no luck", + fails.display() + )) + ); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/horizon-server/src/init.rs b/crates/horizon-server/src/init.rs index 757b6def8..bd595cddb 100644 --- a/crates/horizon-server/src/init.rs +++ b/crates/horizon-server/src/init.rs @@ -205,6 +205,9 @@ pub fn run(dir: &Path, answers: Answers) -> Result<(), String> { match engine::program(&cfg, dir) { Ok(program) => { println!("Game: {}", program.display()); + if let Err(e) = engine::check_starts(&program) { + println!("Warning: {e}"); + } match engine::resources(&cfg, dir, Some(&program)) { Ok(resources) => println!("Game files: {}", resources.display()), Err(e) => println!("{e}"), diff --git a/crates/horizon-server/src/service.rs b/crates/horizon-server/src/service.rs index 2cafa0e3d..6e6d59f23 100644 --- a/crates/horizon-server/src/service.rs +++ b/crates/horizon-server/src/service.rs @@ -32,7 +32,8 @@ pub fn name(dir: &Path) -> String { } /// The program the service runs: the `horizon-server` on the PATH (the installer's launcher, which keeps -/// running the current version after an update), else this program. +/// running the current version after an update), else this program, through the installer's `current` +/// link when it runs from an installed release. fn program() -> Result<PathBuf, String> { let on_path = std::env::var_os("PATH") .map(|p| std::env::split_paths(&p).collect::<Vec<_>>()) @@ -42,10 +43,30 @@ fn program() -> Result<PathBuf, String> { .find(|p| p.is_file()); match on_path { Some(path) => Ok(path), - None => std::env::current_exe().map_err(|e| e.to_string()), + None => std::env::current_exe() + .map(|exe| through_current(&exe)) + .map_err(|e| e.to_string()), } } +/// `<dir>/releases/<tag>/horizon-server` as `<dir>/current/horizon-server` while `current` points at that +/// release (install.sh and install.ps1's layout), so an update applies at the next restart. Linux reports +/// the running program with links resolved, so the release's own path is what this program sees there. +fn through_current(exe: &Path) -> PathBuf { + let current = (|| { + let release = exe.parent()?; + let releases = release.parent()?; + if releases.file_name()? != "releases" { + return None; + } + let current = releases.parent()?.join("current"); + let name = exe.file_name()?; + let same = std::fs::canonicalize(¤t).ok()? == std::fs::canonicalize(release).ok()?; + same.then(|| current.join(name)) + })(); + current.unwrap_or_else(|| exe.to_path_buf()) +} + /// A systemd unit: a user unit, or with `user` a system unit running as that user. pub fn systemd_unit(program: &Path, dir: &Path, user: Option<&str>) -> String { let (run_as, wanted_by) = match user { @@ -374,4 +395,22 @@ mod tests { assert!(plist.contains("<string>/srv/R&D</string>")); assert!(plist.contains("<string>/srv/R&D/logs/supervisor.log</string>")); } + + #[cfg(unix)] + #[test] + fn an_installed_release_runs_through_current() { + let root = + std::env::temp_dir().join(format!("horizon-service-current-{}", std::process::id())); + let release = root.join("releases/v1"); + std::fs::create_dir_all(&release).unwrap(); + let exe = release.join("horizon-server"); + std::fs::write(&exe, "").unwrap(); + // Not the release in use (or no installer layout): this program as it is. + assert_eq!(through_current(&exe), exe); + std::os::unix::fs::symlink(&release, root.join("current")).unwrap(); + assert_eq!(through_current(&exe), root.join("current/horizon-server")); + let other = root.join("bin/horizon-server"); + assert_eq!(through_current(&other), other); + std::fs::remove_dir_all(&root).unwrap(); + } } diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs index ad056a77c..b26ac67cb 100644 --- a/crates/horizon-server/src/supervisor.rs +++ b/crates/horizon-server/src/supervisor.rs @@ -8,7 +8,6 @@ use crate::{ config::Config, engine, signals, }; -use horizon_server_files::java_properties::now_millis; use serde_json::json; use std::{ fs::File, @@ -29,15 +28,12 @@ const MAX_BACKOFF: Duration = Duration::from_secs(300); /// How long `stop` may take before the game is killed. const STOP_TIMEOUT: Duration = Duration::from_secs(120); -/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, UTC), on -/// stdout and in the log the API serves. +/// A line from the supervisor, in the game's log format (`[HH:mm:ss] [thread/LEVEL]: message`, local time +/// as the game's own lines), on stdout and in the log the API serves. fn note(shared: &Shared, level: &str, message: &str) { - let secs = now_millis().div_euclid(1000).rem_euclid(86_400); let line = format!( - "[{:02}:{:02}:{:02}] [Supervisor/{level}]: {message}", - secs / 3600, - secs / 60 % 60, - secs % 60 + "[{}] [Supervisor/{level}]: {message}", + chrono::Local::now().format("%H:%M:%S") ); println!("{line}"); shared.log.lock().unwrap().push(line); @@ -76,6 +72,8 @@ pub fn run(dir: &Path) -> Result<(), String> { let config = Config::load(dir)?; let program = engine::program(&config, dir)?; let resources = engine::resources(&config, dir, Some(&program))?; + // A game the system can't load would only crash again at every restart: say why at once. + engine::check_starts(&program)?; let _lock = lock(dir)?; let shared = Shared::new(dir); let _endpoint = api::start(shared.clone())?; diff --git a/crates/horizon-telemetry/src/payload.rs b/crates/horizon-telemetry/src/payload.rs index 1429a7116..2ed0ba88d 100644 --- a/crates/horizon-telemetry/src/payload.rs +++ b/crates/horizon-telemetry/src/payload.rs @@ -179,6 +179,10 @@ pub struct Perf { /// From start to the title screen. #[serde(skip_serializing_if = "Option::is_none")] pub to_title_ms: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub to_core_ms: Option<u32>, + #[serde(skip_serializing_if = "Option::is_none")] + pub to_rest_ms: Option<u32>, /// From choosing a world to playing in it, the first time this session. #[serde(skip_serializing_if = "Option::is_none")] pub to_world_ms: Option<u32>, diff --git a/crates/horizon-world/src/attributes/entity.rs b/crates/horizon-world/src/attributes/entity.rs index 1bdf94aaf..b7ffd3925 100644 --- a/crates/horizon-world/src/attributes/entity.rs +++ b/crates/horizon-world/src/attributes/entity.rs @@ -11,6 +11,11 @@ impl AttributeId { pub(super) fn index(self) -> usize { self.0 } + /// The attribute's id in the `minecraft:attribute` registry: the catalog + /// export lists `BuiltInRegistries.ATTRIBUTE` in order. + pub fn registry_id(self) -> i32 { + self.0 as i32 + } } #[derive(Debug)] pub struct RegisteredAttribute { @@ -100,6 +105,10 @@ impl Catalog { defaults, }) } + /// The entity type's supplier base of an attribute, if the type has it. + pub fn default_base(&self, entity: &str, id: AttributeId) -> Option<f64> { + self.defaults.get(entity).and_then(|b| b[id.0]) + } pub fn id(&self, name: &str) -> Option<AttributeId> { self.ids.get(name).copied() } diff --git a/crates/horizon-world/src/block_properties.rs b/crates/horizon-world/src/block_properties.rs index 7c0e17f61..98e06f7cb 100644 --- a/crates/horizon-world/src/block_properties.rs +++ b/crates/horizon-world/src/block_properties.rs @@ -79,15 +79,18 @@ impl BlockProperty { #[derive(Clone, Debug)] pub struct BoundBlockProperty { states: Arc<[u8]>, - property: BlockProperty, + mask: u8, } impl BoundBlockProperty { pub fn contains(&self, id: BlockStateId) -> bool { self.states .get(id.0 as usize) - .is_some_and(|flags| flags & self.property.mask() != 0) + .is_some_and(|flags| flags & self.mask != 0) } } +/// The per-state flag of the block definition's `canOcclude`, past the +/// [`BlockProperty`] bits. +const CAN_OCCLUDE: u8 = 16; /// Immutable FULL face-occlusion results, independent of support/collision. #[derive(Clone, Debug)] @@ -195,7 +198,12 @@ impl<'r> BlockPropertiesRegistry<'r> { .ok_or_else(|| invalid("missing block occlusion shape"))?, ) .map_err(|error| invalid(error.to_string()))?, - ) << 3), + ) << 3) + | if properties.can_occlude { + CAN_OCCLUDE + } else { + 0 + }, ); } Ok(Self { @@ -225,7 +233,14 @@ impl<'r> BlockPropertiesRegistry<'r> { pub fn bind(&self, property: BlockProperty) -> BoundBlockProperty { BoundBlockProperty { states: Arc::clone(&self.states), - property, + mask: property.mask(), + } + } + /// The states whose block definition can occlude (BlockState.canOcclude). + pub fn bind_can_occlude(&self) -> BoundBlockProperty { + BoundBlockProperty { + states: Arc::clone(&self.states), + mask: CAN_OCCLUDE, } } } diff --git a/crates/horizon-world/src/level/mod.rs b/crates/horizon-world/src/level/mod.rs index f1f0b21ac..c706ca280 100644 --- a/crates/horizon-world/src/level/mod.rs +++ b/crates/horizon-world/src/level/mod.rs @@ -301,6 +301,12 @@ pub trait LevelAccess { fn max_y(&self) -> i32 { 320 } + /// `getHeight(WORLD_SURFACE, x, z)`: one above the column's highest + /// block that isn't air. Only air lies above it, so scans for the other + /// heightmaps start there. The default, `max_y`, scans the whole column. + fn world_surface(&self, _x: i32, _z: i32) -> i32 { + self.max_y() + } /// Vanilla `level.random` (a `LegacyRandomSource`). fn random(&mut self) -> &mut LegacyRandom; fn game_time(&self) -> i64; diff --git a/crates/horizon-world/src/level/weather.rs b/crates/horizon-world/src/level/weather.rs index c43d96b15..93027d889 100644 --- a/crates/horizon-world/src/level/weather.rs +++ b/crates/horizon-world/src/level/weather.rs @@ -40,14 +40,16 @@ impl Behaviours { BiomePrecipitation::Rain } } - /// `getHeightmapPos(MOTION_BLOCKING, pos)`. + /// `getHeightmapPos(MOTION_BLOCKING, pos)`, scanning down from the + /// world surface (air neither blocks motion nor holds a fluid). pub fn motion_blocking_top<L: LevelAccess + ?Sized>( &self, level: &L, pos: BlockPos, ) -> BlockPos { let blocks = self.tag("minecraft:blocks_motion_in_heightmap"); - for y in (level.min_y()..level.max_y()).rev() { + let top = level.world_surface(pos.x, pos.z).min(level.max_y()); + for y in (level.min_y()..top).rev() { let state = level.block_state(BlockPos::new(pos.x, y, pos.z)); let fluid = self.fluid(state).kind() != FluidKind::Empty; if fluid || blocks.is_some_and(|t| t.contains(self.block(state))) { diff --git a/crates/horizon-world/src/nbt.rs b/crates/horizon-world/src/nbt.rs index 2a8b11591..a8bed543a 100644 --- a/crates/horizon-world/src/nbt.rs +++ b/crates/horizon-world/src/nbt.rs @@ -110,6 +110,19 @@ impl Limits { max_depth: 512, } } + + /// Structure templates (`structure/*.nbt`): vanilla reads them with + /// `NbtAccounter.unlimitedHeap()` (TemplateSource.readStructure), and + /// mods ship templates past the default node cap (YUNG's Better Ocean + /// Monuments' start piece, 115x64x126 blocks, holds millions of tags). + /// The byte cap stays as the only guard on the decompressed file. + pub fn templates() -> Self { + Self { + max_bytes: 1 << 28, + max_nodes: usize::MAX, + max_depth: 512, + } + } } #[derive(Clone, Debug, PartialEq, Eq)] @@ -836,6 +849,18 @@ mod tests { assert!(read_network(&bytes, limits).is_err()); } #[test] + fn templates_read_past_the_default_node_cap() { + // A big mod template (YUNG's monument start) holds more tags than the + // default cap; vanilla reads templates with an unlimited accounter. + let root = NamedTag { + name: JavaString::default(), + tag: Tag::compound([("blocks", Tag::List(vec![Tag::Byte(1); 1_000_001]))]), + }; + let bytes = write_named(&root, Limits::templates()).unwrap(); + assert!(read_named(&bytes, Limits::default()).is_err()); + assert_eq!(read_named(&bytes, Limits::templates()).unwrap().0, root); + } + #[test] fn depth_boundary_and_every_truncated_prefix() { let mut tag = Tag::Int(1); for _ in 0..512 { diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index a901a583d..00f0c64c1 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -23,6 +23,7 @@ pub struct FeatureBlockBindings<'r> { )>, physical_properties: Option<[BoundBlockProperty; 4]>, pub(crate) occlusion_faces: Option<crate::block_properties::BoundOcclusionFaces>, + pub(crate) can_occlude: Option<BoundBlockProperty>, biomes: Option<Arc<super::biome_predicate::BiomePredicateBindings>>, pub(crate) fluids: super::fluid_predicate::FluidPredicateBindings, pub(crate) codec: BlockStateJsonCodec<'r>, @@ -88,6 +89,7 @@ impl<'r> FeatureBlockBindings<'r> { properties.bind(BlockProperty::SolidRender), ]); self.occlusion_faces = Some(properties.bind_occlusion_faces()); + self.can_occlude = Some(properties.bind_can_occlude()); Ok(self) } pub fn with_biomes( @@ -156,6 +158,7 @@ impl<'r> FeatureBlockBindings<'r> { biomes: None, physical_properties: None, occlusion_faces: None, + can_occlude: None, fluids: super::fluid_predicate::FluidPredicateBindings::new(registry)?, blocks: blocks .into_iter() diff --git a/crates/horizon-world/src/worldgen/fluid_predicate.rs b/crates/horizon-world/src/worldgen/fluid_predicate.rs index d8bcb10ab..1394445c9 100644 --- a/crates/horizon-world/src/worldgen/fluid_predicate.rs +++ b/crates/horizon-world/src/worldgen/fluid_predicate.rs @@ -45,6 +45,9 @@ impl FluidPredicateBindings { self.tags = resolved; Ok(self) } + pub(crate) fn table(&self) -> &Arc<FluidStateTable> { + &self.table + } pub fn state(&self, block: BlockStateId) -> Option<crate::fluid::FluidState> { self.table.get(block) } diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 7b73d35a8..2d80130d9 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -635,6 +635,7 @@ struct Pipeline<R: RandomSource> { picker: GlobalFluidPicker, zoom: BiomeZoom, biome_cache: BiomeCache, + biome_work: ChunkWork, carver_cache: Mutex<HashMap<(i32, i32), BiomeId>>, pub(super) decoration: Option<super::generator_decoration::Decoration>, pub(super) structures: Option<super::generator_structures::StructureState>, @@ -643,6 +644,30 @@ struct Pipeline<R: RandomSource> { spawn_position: std::sync::OnceLock<[i32; 2]>, } const CACHE_LIMIT: usize = 16384; +/// Coordinates only equal missing neighbour keys. Weak entries retain no +/// computed values across eviction or explicit invalidation. Only one work +/// lock may be held at a time; finish shared prerequisites before acquiring it. +pub(super) struct ChunkWork(Mutex<HashMap<(i32, i32), std::sync::Weak<Mutex<()>>>>); +impl ChunkWork { + pub(super) fn new() -> Self { + Self(Mutex::new(HashMap::new())) + } + pub(super) fn at(&self, key: (i32, i32)) -> Arc<Mutex<()>> { + let mut work = self.0.lock().unwrap(); + if let Some(lock) = work.get(&key).and_then(std::sync::Weak::upgrade) { + return lock; + } + if work.len() >= 4096 { + // Keep every active builder/waiter on its original lock, including + // when the result cache was cleared while it was in flight. + work.retain(|_, lock| lock.strong_count() > 0); + } + let lock = Arc::new(Mutex::new(())); + work.insert(key, Arc::downgrade(&lock)); + lock + } +} + type BiomeCache = Mutex<HashMap<(i32, i32), Arc<BiomeChunk<BiomeId>>>>; fn state(registry: &BlockRegistry, raw: &Value) -> Result<BlockStateId, GeneratorError> { @@ -834,6 +859,7 @@ where extensions, picker, biome_cache: Mutex::new(HashMap::new()), + biome_work: ChunkWork::new(), carver_cache: Mutex::new(HashMap::new()), decoration: None, structures: None, @@ -867,6 +893,11 @@ where worker: &mut WorkerState, pos: ChunkPos, ) -> Result<Arc<BiomeChunk<BiomeId>>, GeneratorError> { + if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { + return Ok(chunk.clone()); + } + let work = self.biome_work.at((pos.x, pos.z)); + let _work = work.lock().unwrap(); if let Some(chunk) = self.biome_cache.lock().unwrap().get(&(pos.x, pos.z)) { return Ok(chunk.clone()); } @@ -906,7 +937,15 @@ where Ok(chunk) } fn carver_biome(&self, worker: &mut WorkerState, origin: ChunkPos) -> Result<BiomeId, String> { - if let Some(id) = self.carver_cache.lock().unwrap().get(&(origin.x, origin.z)) { + let key = (origin.x, origin.z); + if let Some(id) = worker.carver_biomes.get(&key) { + return Ok(*id); + } + if worker.carver_biomes.len() >= 4096 { + worker.carver_biomes.clear(); + } + if let Some(id) = self.carver_cache.lock().unwrap().get(&key) { + worker.carver_biomes.insert(key, *id); return Ok(*id); } let mut resolver = self.source.resolver( @@ -926,13 +965,27 @@ where if cache.len() >= CACHE_LIMIT * 4 { cache.clear(); } - cache.insert((origin.x, origin.z), id); + cache.insert(key, id); + worker.carver_biomes.insert(key, id); Ok(id) } fn generate( &self, worker: &mut WorkerState, pos: ChunkPos, + ) -> Result<ProtoChunk, GeneratorError> { + let mut context = std::mem::take(&mut worker.terrain_context); + let result = self.generate_with_context(worker, pos, &mut context); + // Release chunk-specific bindings and caches even after a sampling error. + context.reset(); + worker.terrain_context = context; + result + } + fn generate_with_context( + &self, + worker: &mut WorkerState, + pos: ChunkPos, + context: &mut SamplerContext, ) -> Result<ProtoChunk, GeneratorError> { let data = &self.data; let (min, height, sea) = ( @@ -985,13 +1038,12 @@ where ), None => Vec::new(), }; - let mut context = SamplerContext::cached(); if let Some(beard) = self .structures .as_ref() .and_then(|s| s.beardifier(&references, pos)) { - context = context.with_world_fields( + *context = std::mem::take(context).with_world_fields( horizon_core::density::WorldFields::default().with_field( horizon_core::density::WorldField::Beardifier, Arc::new(beard), @@ -1016,7 +1068,7 @@ where .fork_positional(), RegistryAquiferBlockStates::new(data.registry).map_err(stage("aquifer"))?, volume, - &mut context, + context, ) .map_err(stage("aquifer"))?, ), @@ -1030,7 +1082,7 @@ where &mut chunk, volume, self.router.get(RouterField::FinalDensity).as_ref(), - &mut context, + context, aquifer.as_mut(), self.settings.default_block, ) @@ -1051,7 +1103,7 @@ where possible: Some(possible), }, preliminary_surface: self.preliminary.clone(), - density_context: &mut context, + density_context: context, write_min_y: min, write_max_y: min + height - 1, }, @@ -1086,7 +1138,7 @@ where possible: None, }, preliminary_surface: self.preliminary.clone(), - density_context: &mut context, + density_context: context, }, aquifer.as_mut(), &data.carving_blocks, @@ -1270,15 +1322,23 @@ where self.pipeline.generation() } fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { + self.noise_biomes(&[quart])[0] + } + fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec<BiomeId> { let mut resolver = self.pipeline.source.resolver( &self.pipeline.climate, self.pipeline.router.get(RouterField::Erosion).as_ref(), ); - resolver - .sample(&mut self.worker.carver_context, quart) - .ok() - .and_then(|name| self.pipeline.data.biome_id(name)) - .unwrap_or(BiomeId(0)) + quarts + .iter() + .map(|&quart| { + resolver + .sample(&mut self.worker.carver_context, quart) + .ok() + .and_then(|name| self.pipeline.data.biome_id(name)) + .unwrap_or(BiomeId(0)) + }) + .collect() } fn set_valid_biomes(&mut self, biomes: &BTreeSet<BiomeId>) { self.valid = biomes.clone(); @@ -1391,8 +1451,12 @@ pub struct StageTimings { /// thread-local caches and never change results. pub(super) struct WorkerState { pub(super) temperatures: Vec<BiomeTemperature>, + terrain_context: SamplerContext, biome_context: SamplerContext, carver_context: SamplerContext, + /// Seed/dimension-bound lookups avoid the shared mutex for overlapping + /// carver neighborhoods. Bounded independently of the shared cache. + carver_biomes: HashMap<(i32, i32), BiomeId>, timings: StageTimings, heights: HashMap<(i32, i32, u8), i32>, /// Decorate with structure pieces only (for structure parity checks). @@ -1866,8 +1930,10 @@ impl OverworldGenerator { .iter() .map(|s| BiomeTemperature::new(*s)) .collect(), + terrain_context: SamplerContext::cached(), biome_context: SamplerContext::cached(), carver_context: SamplerContext::default(), + carver_biomes: HashMap::new(), timings: StageTimings::default(), structures_only: false, heights: HashMap::new(), @@ -1947,10 +2013,8 @@ impl GeneratorWorker { mod tests { use super::*; - /// Generators of one seed and dimension share their ring positions; - /// another seed or generator gets its own, and old entries go. #[test] - fn ring_positions_are_shared_by_seed_and_dimension() { + fn local_carver_cache_is_worker_owned_and_eviction_preserves_terrain() { let root = std::env::var_os("HORIZON_RESOURCES") .map(std::path::PathBuf::from) .unwrap_or_else(|| { @@ -1960,10 +2024,95 @@ mod tests { eprintln!("skipping: no worldgen bundle at {}", root.display()); return; } + let registry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).unwrap(); + let generator = OverworldGenerator::new(data.clone(), 12345).unwrap(); + let mut first = generator.worker(); + let mut second = generator.worker(); + let pos = ChunkPos::new(0, 0); + let before = first.generate_proto(pos).unwrap(); + assert!(!first.state.carver_biomes.is_empty()); + assert!(second.state.carver_biomes.is_empty()); + second.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, second.state.carver_biomes); + let expected = first.state.carver_biomes.clone(); + first.state.carver_biomes.clear(); + // Fill unrelated origins to force eviction on the next local miss. + for x in 0..4096 { + first.state.carver_biomes.insert((x, 100_000), BiomeId(0)); + } + let after = first.generate_proto(pos).unwrap(); + assert_eq!(first.state.carver_biomes, expected); + for y in -64..320 { + for z in 0..16 { + for x in 0..16 { + assert_eq!(before.block(x, y, z), after.block(x, y, z)); + assert_eq!(before.biome_id_at(x, y, z), after.biome_id_at(x, y, z)); + } + } + } + assert!( + OverworldGenerator::new(data, -1) + .unwrap() + .worker() + .state + .carver_biomes + .is_empty() + ); + assert_eq!(second.state.carver_biomes, expected); + } + + /// The prepared worldgen data, if this checkout has it. + fn prepared_data() -> Option<Arc<GeneratorData>> { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return None; + } let registry: &'static BlockRegistry = Box::leak(Box::new( crate::level::data::load_registry(&root).expect("registry"), )); - let data = GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data"); + Some(GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data")) + } + + /// Seed 1234's strongholds where vanilla 26.3 puts them + /// (VanillaStructureStartOracle with HORIZON_RINGS). Each search sampled + /// its quarts through fresh resolvers, which broke climate ties their own + /// way: three of the 128 were up to 6 chunks off. + #[test] + fn stronghold_rings_match_vanilla() { + let Some(data) = prepared_data() else { + return; + }; + let generator = OverworldGenerator::new(data, 1234).expect("generator"); + generator.worker().structure_starts(ChunkPos::new(0, 0)); + let rings = generator + .ring_positions("minecraft:strongholds") + .expect("ring positions"); + assert_eq!(rings.len(), 128); + for (i, x, z) in [ + (0, -100, -125), + (1, 131, -12), + (111, 1190, -560), + (113, 1305, -112), + ] { + assert_eq!(rings[i], ChunkPos::new(x, z), "stronghold {i}"); + } + } + + /// Generators of one seed and dimension share their ring positions; + /// another seed or generator gets its own, and old entries go. + #[test] + fn ring_positions_are_shared_by_seed_and_dimension() { + let Some(data) = prepared_data() else { + return; + }; let first = OverworldGenerator::new(data.clone(), 1234).expect("generator"); let again = OverworldGenerator::new(data.clone(), 1234).expect("generator"); { @@ -2013,4 +2162,121 @@ mod tests { .is_err() ); } + #[test] + fn neighbour_work_cleanup_keeps_active_keys_and_releases_idle_keys() { + let work = ChunkWork::new(); + let first = work.at((0, 0)); + let held = first.lock().unwrap(); + let same = work.at((0, 0)); + assert!(Arc::ptr_eq(&first, &same)); + assert!(!Arc::ptr_eq(&first, &work.at((1, 0)))); + // Sweep many expired weak entries while a builder and a prospective + // waiter retain their key. Cleanup must not split their coordination. + for x in 1..8192 { + drop(work.at((x, 1))); + } + assert!(work.0.lock().unwrap().len() <= 4096); + assert!(Arc::ptr_eq(&same, &work.at((0, 0)))); + let weak = Arc::downgrade(&first); + drop(held); + drop((first, same)); + assert!(weak.upgrade().is_none()); + let next = work.at((0, 0)); + assert_eq!(Arc::strong_count(&next), 1); + } + + /// Equal concurrent misses share one biome volume and the same mutable + /// structure pieces. Exercise cold ring startup before work coordination, + /// then cache eviction and explicit start invalidation with old Arcs alive. + #[test] + fn concurrent_neighbours_share_results_and_survive_invalidation() { + let root = std::env::var_os("HORIZON_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("worldgen/world_presets.json").exists() { + eprintln!("skipping: no worldgen bundle at {}", root.display()); + return; + } + let registry = Box::leak(Box::new( + crate::level::data::load_registry(&root).expect("registry"), + )); + let data = GeneratorData::load(&root.join("worldgen"), registry).expect("worldgen data"); + let preset: Value = serde_json::from_str(&data.world_presets["minecraft:normal"]).unwrap(); + let generator_json = &preset["dimensions"]["minecraft:overworld"]["generator"]; + let settings: Value = + serde_json::from_str(&data.settings[generator_json["settings"].as_str().unwrap()]) + .unwrap(); + let pipeline = Arc::new( + Pipeline::new( + data, + 12345, + XoroshiroRandom::new(12345), + generator_json, + &settings, + true, + Some((-64, 384)), + ) + .expect("pipeline"), + ); + let generator = OverworldGenerator { + pipeline: pipeline.clone(), + }; + let barrier = std::sync::Barrier::new(6); + let pos = ChunkPos::new(11, -11); // ancient city for this seed + let results = std::thread::scope(|scope| { + let handles: Vec<_> = (0..6) + .map(|_| { + scope.spawn(|| { + let mut worker = generator.worker(); + barrier.wait(); + let biomes = pipeline.biome_chunk(&mut worker.state, pos).unwrap(); + let starts = pipeline.structure_starts(&mut worker.state, pos); + (biomes, starts) + }) + }) + .collect(); + handles + .into_iter() + .map(|h| h.join().unwrap()) + .collect::<Vec<_>>() + }); + let (biomes, starts) = &results[0]; + assert!(!starts.is_empty(), "fixture must exercise shared pieces"); + for (b, s) in &results[1..] { + assert!(Arc::ptr_eq(biomes, b)); + assert_eq!(starts.len(), s.len()); + for (first, other) in starts.iter().zip(s) { + assert!(Arc::ptr_eq(first, other)); + } + } + // Force the existing whole-cache biome eviction threshold. + { + let mut cache = pipeline.biome_cache.lock().unwrap(); + cache.clear(); + for x in 0..CACHE_LIMIT as i32 { + cache.insert((x, 10000), biomes.clone()); + } + } + let mut worker = generator.worker(); + let rebuilt = pipeline.biome_chunk(&mut worker.state, pos).unwrap(); + assert!(!Arc::ptr_eq(biomes, &rebuilt)); + assert_eq!(pipeline.biome_cache.lock().unwrap().len(), 1); + for section in 0..24 { + assert_eq!(biomes.section(section), rebuilt.section(section)); + } + worker.forget_structure_starts(); + let fresh = worker.structure_starts(pos); + assert_eq!(starts.len(), fresh.len()); + for (old, new) in starts.iter().zip(&fresh) { + assert!(!Arc::ptr_eq(old, new)); + assert_eq!(old.name, new.name); + assert_eq!(old.bounding_box, new.bounding_box); + } + let again = worker.structure_starts(pos); + for (first, hit) in fresh.iter().zip(&again) { + assert!(Arc::ptr_eq(first, hit)); + } + } } diff --git a/crates/horizon-world/src/worldgen/generator_structures.rs b/crates/horizon-world/src/worldgen/generator_structures.rs index e78ce0772..1e4913c95 100644 --- a/crates/horizon-world/src/worldgen/generator_structures.rs +++ b/crates/horizon-world/src/worldgen/generator_structures.rs @@ -2,7 +2,7 @@ use super::{ biome::BiomeId, block_feature::FeatureBlockBindings, - generator::{GeneratorData, GeneratorError}, + generator::{ChunkWork, GeneratorData, GeneratorError}, structure::{ StructureResources, start::{ @@ -17,7 +17,7 @@ use std::collections::BTreeMap; use std::{ collections::{BTreeSet, HashMap}, sync::{ - Arc, Condvar, Mutex, OnceLock, + Arc, Condvar, Mutex, OnceLock, RwLock, atomic::{AtomicUsize, Ordering}, }, }; @@ -30,7 +30,8 @@ pub(super) struct StructureState { possible_sets: Vec<usize>, /// Structure indices of each decoration step, in registry order. pub(super) by_step: Vec<Vec<usize>>, - starts: Mutex<HashMap<(i32, i32), Starts>>, + starts: StartCache, + start_work: ChunkWork, /// Concentric ring positions, computed on first use and shared with /// later generators of the same seed and dimension. rings: Arc<OnceLock<Rings>>, @@ -73,14 +74,14 @@ impl RingWork { fn help<'a>( &self, preferred: impl Fn(usize) -> &'a BTreeSet<BiomeId>, - biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + biomes: &mut dyn FnMut(&[[i32; 3]]) -> Vec<BiomeId>, ) { loop { let i = self.next.fetch_add(1, Ordering::Relaxed); let Some((set, search)) = self.searches.get(i) else { break; }; - let _ = self.found[i].set(search.find(preferred(*set), biome)); + let _ = self.found[i].set(search.find(preferred(*set), biomes)); let mut left = self.left.lock().unwrap(); *left -= 1; if *left == 0 { @@ -108,6 +109,45 @@ impl RingWork { } } const START_CACHE_LIMIT: usize = 65536; +const START_SHARDS: usize = 64; + +/// The built starts by chunk, in shards: a lookup locks one shard for +/// reading. Each generated chunk reads the 289 start chunks around it +/// (`references`) and the server thread reads the starts of the chunks its +/// mobs and players are in; with one lock for all, the server thread waited +/// on the workers. +struct StartCache { + shards: Box<[RwLock<HashMap<(i32, i32), Starts>>]>, +} +impl StartCache { + fn new() -> Self { + Self { + shards: (0..START_SHARDS).map(|_| RwLock::default()).collect(), + } + } + fn shard(&self, key: (i32, i32)) -> &RwLock<HashMap<(i32, i32), Starts>> { + let hash = + (key.0 as u32).wrapping_mul(0x9E37_79B9) ^ (key.1 as u32).wrapping_mul(0x85EB_CA6B); + &self.shards[(hash >> (32 - START_SHARDS.trailing_zeros())) as usize] + } + fn get(&self, key: (i32, i32)) -> Option<Starts> { + self.shard(key).read().unwrap().get(&key).cloned() + } + /// Keeps `starts` unless another thread built the same chunk's first: + /// everyone keeps the first, so placement state on its pieces is shared. + fn insert_first(&self, key: (i32, i32), starts: Starts) -> Starts { + let mut shard = self.shard(key).write().unwrap(); + if shard.len() >= START_CACHE_LIMIT / START_SHARDS { + shard.clear(); + } + shard.entry(key).or_insert(starts).clone() + } + fn clear(&self) { + for shard in &self.shards { + shard.write().unwrap().clear(); + } + } +} fn biome_set(data: &GeneratorData, value: &Value) -> Result<BTreeSet<BiomeId>, super::DecodeError> { let names: Vec<&str> = match value { @@ -156,18 +196,27 @@ impl StructureState { for (i, def) in registry.structures.iter().enumerate() { by_step[def.step].push(i); } - let bindings = FeatureBlockBindings::with_tags( + let mut bindings = FeatureBlockBindings::with_tags( data.registry(), data.integers().clone(), &data.block_tags, )?; + // Processors that test what a block is made of read canOcclude. + if let Some(blocks) = data + .feature_resources + .as_ref() + .and_then(|r| r.blocks.as_ref()) + { + bindings = bindings.with_block_properties(&blocks.properties)?; + } Ok(Some(Self { registry, resources: resources.clone(), bindings, possible_sets, by_step, - starts: Mutex::new(HashMap::new()), + starts: StartCache::new(), + start_work: ChunkWork::new(), rings, ring_work: OnceLock::new(), })) @@ -190,8 +239,8 @@ impl StructureState { ) }); let registry = &self.registry; - work.help(|set| registry.ring_biomes(set), &mut |q| { - context.noise_biome(q) + work.help(|set| registry.ring_biomes(set), &mut |quarts| { + context.noise_biomes(quarts) }); self.rings .get_or_init(|| work.rings(|set| registry.sets[set].name.clone())) @@ -199,7 +248,9 @@ impl StructureState { /// Drop the cached starts, so that later chunks build fresh pieces (the /// pieces keep per-start placement state such as a shipwreck's height). pub(super) fn forget_starts(&self) { - self.starts.lock().unwrap().clear(); + // As before, a build already in flight can publish after this clear. + // Do not wait for work locks or retain initialized entries here. + self.starts.clear(); } /// The (cached) structure starts owned by a chunk. pub(super) fn starts_at( @@ -207,10 +258,17 @@ impl StructureState { context: &mut impl super::structure::start::StartContext, chunk: ChunkPos, ) -> Starts { - if let Some(found) = self.starts.lock().unwrap().get(&(chunk.x, chunk.z)) { - return found.clone(); + if let Some(found) = self.starts.get((chunk.x, chunk.z)) { + return found; } + // Ring searches enlist other workers and wait for them: never hold a + // chunk-work lock while helping, even when this chunk has no starts. let rings = self.rings(context); + let work = self.start_work.at((chunk.x, chunk.z)); + let _work = work.lock().unwrap(); + if let Some(found) = self.starts.get((chunk.x, chunk.z)) { + return found; + } let starts: Starts = Arc::new( create_starts( &self.registry, @@ -225,13 +283,7 @@ impl StructureState { .map(Arc::new) .collect(), ); - let mut cache = self.starts.lock().unwrap(); - if cache.len() >= START_CACHE_LIMIT { - cache.clear(); - } - // Another thread may have built the same starts meanwhile: everyone - // keeps the first, so placement state on its pieces is shared. - cache.entry((chunk.x, chunk.z)).or_insert(starts).clone() + self.starts.insert_first((chunk.x, chunk.z), starts) } /// ChunkGenerator.findNearestMapStructure: the nearest start of one of /// `names` from block `from` (rings: every ring chunk; random spreads: @@ -385,13 +437,51 @@ mod tests { use super::*; use crate::worldgen::structure::stronghold::{ring_positions, ring_searches}; + /// The start cache keeps the first starts built for a chunk, spreads a + /// chunk's 289 reference lookups over the shards, and forgets on clear. + #[test] + fn start_cache_keeps_first_and_spreads_neighbours() { + let cache = StartCache::new(); + let first: Starts = Arc::new(Vec::new()); + let second: Starts = Arc::new(Vec::new()); + assert!(cache.get((3, -4)).is_none()); + assert!(Arc::ptr_eq( + &cache.insert_first((3, -4), first.clone()), + &first + )); + assert!(Arc::ptr_eq(&cache.insert_first((3, -4), second), &first)); + assert!(Arc::ptr_eq(&cache.get((3, -4)).unwrap(), &first)); + for (cx, cz) in [(0, 0), (-1000, 77), (i32::MAX - 8, i32::MIN + 8)] { + let mut used = vec![0; START_SHARDS]; + for x in cx - 8..=cx + 8 { + for z in cz - 8..=cz + 8 { + let shard = cache.shard((x, z)) as *const _; + let i = cache + .shards + .iter() + .position(|s| std::ptr::eq(s, shard)) + .unwrap(); + used[i] += 1; + } + } + assert!(used.iter().all(|&n| n > 0 && n < 20), "{used:?}"); + } + cache.clear(); + assert!(cache.get((3, -4)).is_none()); + } + /// Searches shared between threads give the positions of one thread /// running them in order, set by set. #[test] fn ring_work_shared_between_threads_matches_serial_search() { let preferred: BTreeSet<BiomeId> = (0..20).map(|b| BiomeId(b * 3)).collect(); - let biome = |q: [i32; 3]| { - BiomeId((q[0].wrapping_mul(31) ^ q[2].wrapping_mul(17)).rem_euclid(64) as u32) + let biomes = |quarts: &[[i32; 3]]| -> Vec<BiomeId> { + quarts + .iter() + .map(|q| { + BiomeId((q[0].wrapping_mul(31) ^ q[2].wrapping_mul(17)).rem_euclid(64) as u32) + }) + .collect() }; let none = BTreeSet::new(); for seed in [0, 1234, -77, i64::MAX] { @@ -403,12 +493,12 @@ mod tests { let sets = [&preferred, &none, &preferred]; std::thread::scope(|scope| { for _ in 0..4 { - scope.spawn(|| work.help(|set| sets[set], &mut { biome })); + scope.spawn(|| work.help(|set| sets[set], &mut { biomes })); } }); let rings = work.rings(|set| format!("set{set}")); let serial = |s: i64, distance, spread, count, preferred| { - ring_positions(s, distance, spread, count, preferred, &mut { biome }) + ring_positions(s, distance, spread, count, preferred, &mut { biomes }) }; assert_eq!(rings["set0"], serial(seed, 32, 3, 128, &preferred)); assert_eq!(rings["set1"], Vec::new()); diff --git a/crates/horizon-world/src/worldgen/rule_test.rs b/crates/horizon-world/src/worldgen/rule_test.rs index d9f836961..5202baa31 100644 --- a/crates/horizon-world/src/worldgen/rule_test.rs +++ b/crates/horizon-world/src/worldgen/rule_test.rs @@ -3,7 +3,11 @@ use super::{ DecodeError, Object, block_feature::FeatureBlockBindings, density::identifier, integer, number_text, required, }; -use crate::registry::BlockStateId; +use crate::{ + block_properties::BoundBlockProperty, + fluid::{FluidKind, FluidStateTable}, + registry::BlockStateId, +}; use horizon_core::random::RandomSource; use serde_json::value::RawValue; use std::{collections::BTreeSet, sync::Arc}; @@ -21,6 +25,85 @@ enum Node { RandomStates(Arc<BTreeSet<BlockStateId>>, f32), RandomState(BlockStateId, f32), Height(i32, i32), + Phase(Box<MatterPhase>), +} +/// `horizon:matter_phase`: Repurposed Structures' MatterPhaseRuleTest, which +/// its mineshafts and Nether monument use to match a block by what it is +/// made of (`phase_to_test_for`), optionally inverted (`invert_condition`). +#[derive(Clone, Debug)] +struct MatterPhase { + phase: Phase, + invert: bool, + air: [BlockStateId; 3], + fluids: Arc<FluidStateTable>, + /// Only for `SOLID`. + can_occlude: Option<BoundBlockProperty>, + /// Blocks.RAIL and Blocks.CHAIN (26.3's iron chain). + rail_or_chain: BTreeSet<BlockStateId>, +} +#[derive(Clone, Copy, Debug)] +enum Phase { + Solid, + Liquid, + Air, + AirRailOrChain, + LiquidRailOrChain, +} +impl MatterPhase { + fn decode(object: &Object, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> { + let name: String = serde_json::from_str(required(object, "phase_to_test_for")?.get())?; + let phase = match name.as_str() { + "SOLID" => Phase::Solid, + "LIQUID" => Phase::Liquid, + "AIR" => Phase::Air, + "AIR_RAIL_OR_CHAIN" => Phase::AirRailOrChain, + "LIQUID_RAIL_OR_CHAIN" => Phase::LiquidRailOrChain, + _ => return Err(DecodeError::Field("matter phase")), + }; + let invert = match object.get("invert_condition") { + Some(v) => serde_json::from_str(v.get())?, + None => false, + }; + let can_occlude = match phase { + Phase::Solid => Some( + bindings + .can_occlude + .clone() + .ok_or(DecodeError::Field("matter phase block properties"))?, + ), + _ => None, + }; + let mut rail_or_chain = BTreeSet::new(); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + rail_or_chain.extend(bindings.blocks.get(name).into_iter().flat_map(|s| s.iter())); + } + Ok(Self { + phase, + invert, + air: bindings.air, + fluids: bindings.fluids.table().clone(), + can_occlude, + rail_or_chain, + }) + } + fn test(&self, state: BlockStateId) -> bool { + let air = self.air.contains(&state); + let liquid = self + .fluids + .get(state) + .is_some_and(|f| f.kind() != FluidKind::Empty); + let rail_or_chain = || self.rail_or_chain.contains(&state); + let matched = match self.phase { + Phase::Solid => { + !air && !liquid && self.can_occlude.as_ref().is_some_and(|c| c.contains(state)) + } + Phase::Liquid => liquid, + Phase::Air => air, + Phase::AirRailOrChain => air || rail_or_chain(), + Phase::LiquidRailOrChain => liquid || rail_or_chain(), + }; + matched != self.invert + } } impl RuleTest { pub fn from_json(json: &str, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> { @@ -104,6 +187,9 @@ impl RuleTest { Node::Any(values) } } + "horizon:matter_phase" => { + Node::Phase(Box::new(MatterPhase::decode(&object, bindings)?)) + } _ => return Err(DecodeError::Field("replacement rule type")), }; Ok(Self(node)) @@ -128,6 +214,7 @@ impl RuleTest { state == *expected && random.next_float() < *probability } Node::Height(min, max) => *min <= position[1] && position[1] <= *max, + Node::Phase(phase) => phase.test(state), } } } diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 361b2c1d0..4dbbc9ade 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -10,6 +10,7 @@ pub mod mineshaft; pub mod monument; pub mod nether_fossil; pub mod ocean_ruin; +pub mod piece_limited; pub mod processor; pub mod ruined_portal; pub mod simple; @@ -18,6 +19,7 @@ pub mod start_checks; pub mod stronghold; pub mod template; pub mod temple; +pub mod yung; use crate::{ nbt::{self, Limits}, @@ -342,11 +344,7 @@ impl StructureResources { flate2::read::GzDecoder::new(bytes.as_slice()) .read_to_end(&mut raw) .ok()?; - let limits = Limits { - max_bytes: 1 << 28, - ..Limits::default() - }; - let tag = nbt::read_named(&raw, limits).ok()?.0.tag; + let tag = nbt::read_named(&raw, Limits::templates()).ok()?.0.tag; Some(Arc::new(StructureTemplate::from_nbt( &tag, self.registry, diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index a50275941..27651268d 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -30,7 +30,7 @@ pub enum Projection { Rigid, TerrainMatching, } -#[derive(Debug)] +#[derive(Clone, Debug)] pub enum PoolElement { Empty, Single { @@ -39,6 +39,9 @@ pub enum PoolElement { legacy: bool, projection: Projection, waterlogging: Option<bool>, + /// YUNG's API's rules on the piece (`"horizon:yungsapi"`), read only + /// by its assembler ([`super::yung`]). + yung: Option<Box<super::yung::Rules>>, }, Feature { feature: String, @@ -81,11 +84,12 @@ fn opposite(d: Direction) -> Direction { Direction::East => Direction::West, } } -fn step(d: Direction) -> [i32; 3] { +pub(super) fn step(d: Direction) -> [i32; 3] { let n = d.normal(); [n[0], n[1], n[2]] } -fn shuffle<T>(list: &mut [T], random: &mut impl RandomSource) { +/// Util.shuffle. +pub(super) fn shuffle<T>(list: &mut [T], random: &mut impl RandomSource) { for i in (2..=list.len()).rev() { let swap = random.next_int_bound(i as i32).unwrap_or(0) as usize; list.swap(i - 1, swap); @@ -135,6 +139,10 @@ impl PoolElement { Some("ignore_waterlogging") => Some(false), _ => None, }, + yung: value + .get("horizon:yungsapi") + .map(|rules| super::yung::Rules::decode(rules, resources).map(Box::new)) + .transpose()?, } } "minecraft:feature_pool_element" => Self::Feature { @@ -219,10 +227,13 @@ impl PoolElement { .first() .map(|e| e.shuffled_jigsaws(resources, position, rotation, random)) .unwrap_or_default(), - Self::Single { template, .. } => { + Self::Single { template, yung, .. } => { let mut jigsaws = template_jigsaws(resources, template, position, rotation); shuffle(&mut jigsaws, random); - jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + // YUNG's elements keep the shuffled order. + if yung.is_none() { + jigsaws.sort_by_key(|j| std::cmp::Reverse(j.selection_priority)); + } jigsaws } } @@ -230,6 +241,13 @@ impl PoolElement { pub fn ground_level_delta(&self) -> i32 { 1 } + /// YUNG's API's rules, on a piece of one of its structures. + pub fn yung(&self) -> Option<&super::yung::Rules> { + match self { + Self::Single { yung, .. } => yung.as_deref(), + _ => None, + } + } } /// StructureTemplate.getJigsaws: palette chosen by a position-seeded random. fn template_jigsaws( @@ -274,7 +292,7 @@ fn template_jigsaws( }) .collect() } -fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { +pub(super) fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { source.front == opposite(target.front) && (source.rollable || source.top == target.top) && target @@ -285,12 +303,15 @@ fn can_attach(source: &Jigsaw, target: &Jigsaw) -> bool { #[derive(Debug)] pub struct Pool { - templates: Vec<Arc<PoolElement>>, - fallback: String, + /// Each element repeated by its weight. + pub(super) templates: Vec<Arc<PoolElement>>, + /// The elements with their weights, in file order (`rawTemplates`). + pub(super) raw: Vec<(Arc<PoolElement>, i32)>, + pub(super) fallback: String, max_size: OnceLock<i32>, } impl Pool { - fn random_template(&self, random: &mut impl RandomSource) -> Arc<PoolElement> { + pub(super) fn random_template(&self, random: &mut impl RandomSource) -> Arc<PoolElement> { if self.templates.is_empty() { return Arc::new(PoolElement::Empty); } @@ -304,7 +325,7 @@ impl Pool { shuffle(&mut copy, random); copy } - fn max_size(&self) -> i32 { + pub(super) fn max_size(&self) -> i32 { *self.max_size.get_or_init(|| { self.templates .iter() @@ -343,7 +364,7 @@ impl Pools { } let pool = self.raw.get(name).and_then(|json| { let value: Value = serde_json::from_str(json).ok()?; - let mut templates = Vec::new(); + let (mut templates, mut raw) = (Vec::new(), Vec::new()); for entry in value["elements"].as_array()? { let element = match PoolElement::decode(&entry["element"], resources, bindings, None) { @@ -355,12 +376,15 @@ impl Pools { return None; } }; - for _ in 0..entry["weight"].as_i64().unwrap_or(1) { + let weight = entry["weight"].as_i64().unwrap_or(1); + for _ in 0..weight { templates.push(element.clone()); } + raw.push((element, weight as i32)); } Some(Arc::new(Pool { templates, + raw, fallback: value["fallback"] .as_str() .unwrap_or("minecraft:empty") @@ -376,7 +400,7 @@ impl Pools { } } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Junction { pub source_x: i32, pub source_ground_y: i32, @@ -393,7 +417,7 @@ pub struct PoolPiece { pub waterlogging: bool, } impl PoolPiece { - fn moved(&mut self, dy: i32) { + pub(super) fn moved(&mut self, dy: i32) { self.position[1] += dy; self.bounding_box = self.bounding_box.moved([0, dy, 0]); } @@ -466,6 +490,7 @@ fn place_element<W: FeatureWorld + PlacementContext, R: RandomSource>( legacy, projection, waterlogging: override_liquid, + .. } => { let ignore = if *legacy { IGNORE_STRUCTURE_AND_AIR.get_or_init(|| { @@ -547,13 +572,13 @@ pub struct JigsawConfig<'a> { /// Free space for children: an inclusive container box minus placed boxes. #[derive(Debug)] -struct Free { - container: BoundingBox, - removed: Vec<BoundingBox>, +pub(super) struct Free { + pub(super) container: BoundingBox, + pub(super) removed: Vec<BoundingBox>, } impl Free { /// Whether every point of the (0.25-deflated) box lies in free space. - fn fits(&self, b: &BoundingBox) -> bool { + pub(super) fn fits(&self, b: &BoundingBox) -> bool { (0..3).all(|i| b.min[i] >= self.container.min[i] && b.max[i] <= self.container.max[i]) && !self.removed.iter().any(|r| r.intersects(b)) } diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs new file mode 100644 index 000000000..753df0258 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -0,0 +1,1055 @@ +//! The piece-limited jigsaw assembler of Repurposed Structures and Moog's +//! Structure Lib (PieceLimitedJigsawManager, the same code in both), for +//! their structures carried over from a modpack (docs/modpacks.md). Carry +//! maps their jigsaw types to `minecraft:jigsaw` with a +//! `"horizon:piece_limited"` key; vanilla data never has it. +//! +//! ```json +//! "horizon:piece_limited": { +//! "library": "moogs", // or "repurposed": their few differences +//! "min_y": 40, "max_y": 120, // y_allowance: pieces stay inside, unless buried +//! "burying": "lowest_corner", // or "average_land", "lowest_side" +//! "no_liquid": true, // cannot_spawn_in_liquid, as burying reads it +//! "ignore_bounds_pools": ["x:pool"], +//! "land_search": "highest_land", // the Nether variants: or "lowest_land", "fixed_height" +//! "ledge_offset_y": 2, +//! "pieces": [{"name": "x:piece", "required": 1, "min_depth": 3, "max": 2}], +//! "layout": "mineshaft" // Repurposed's mineshafts: moved under the terrain +//! } +//! ``` +//! +//! It differs from vanilla's JigsawPlacement: a fresh random seeded by the +//! chunk, the start piece drawn uniformly and moved to the surface at its +//! center, a bounding volume 120 blocks down and 180 up, children drawn by +//! weight from the pools' weighted entries in order (`nextInt(total) + 1`, +//! counted down), pieces capped by template (`max`) and some required +//! (`required`, from `min_depth`), the whole layout retried up to 40 times +//! until every required piece is in, and after it the pieces centred on the +//! chunk corner, then buried in the terrain or moved onto Nether land. +//! Repurposed's overworld mineshafts are not centred: their top goes 15 +//! blocks under the terrain around the chunk. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, Junction, PoolElement, PoolPiece, Pools, Projection, can_attach, + shuffle, step, + }, + start::StartContext, +}; +use crate::{ + heightmap::HeightmapType, identifier::Identifier, java_hash_map::JavaHashMap, + worldgen::block_feature::FeatureBlockBindings, +}; +use horizon_core::{ + position::ChunkPos, + random::{LegacyRandom, RandomSource, WorldgenRandom}, +}; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashSet, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// Which mod's copy of the code: they differ in a few post-layout steps. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Library { + Moogs, + Repurposed, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Burying { + LowestCorner, + AverageLand, + LowestSide, +} + +/// The structure type's postLayoutAdjustments. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Layout { + /// GenericJigsawStructure's: centred, then buried or moved onto land. + Generic, + /// Repurposed Structures' MineshaftStructure. + Mineshaft, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum LandSearch { + Highest, + Lowest, + Fixed, +} + +/// One template's counts (`*_pieces_spawn_counts`). +#[derive(Clone, Debug)] +struct Counted { + required: Option<i32>, + min_depth: i32, + max: Option<i32>, +} + +/// `"horizon:piece_limited"` of a jigsaw structure. +#[derive(Debug)] +pub struct Config { + library: Library, + min_y: Option<i32>, + max_y: Option<i32>, + burying: Option<Burying>, + no_liquid: bool, + ignore_bounds: HashSet<String>, + land_search: Option<LandSearch>, + ledge: i32, + layout: Layout, + /// Counted templates by id, in the order of Java's HashMap of the + /// required pieces (the first one still short is forced in first). + pieces: Vec<(Identifier, Counted)>, +} + +impl Config { + pub fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let mut pieces: Vec<(Identifier, Counted)> = Vec::new(); + for p in v["pieces"].as_array().into_iter().flatten() { + let Some(id) = p["name"].as_str().and_then(|n| Identifier::parse(n).ok()) else { + continue; + }; + let counted = Counted { + required: p["required"].as_i64().map(|n| n as i32), + min_depth: p["min_depth"].as_i64().unwrap_or(0) as i32, + max: p["max"].as_i64().map(|n| n as i32), + }; + // A later entry for the same piece replaces it, as HashMap.put. + match pieces.iter_mut().find(|(k, _)| *k == id) { + Some(slot) => slot.1 = counted, + None => pieces.push((id, counted)), + } + } + // getRequirePieces builds a HashMap of the required ones and the + // assembler copies it (new HashMap(map)): iterate as that copy does. + let mut map = JavaHashMap::default(); + for (i, (id, c)) in pieces.iter().enumerate() { + if c.required.is_some() { + map.put(id.clone(), i); + } + } + let order: Vec<usize> = map.copied().entries().map(|(_, &i)| i).collect(); + let mut sorted: Vec<(Identifier, Counted)> = + order.iter().map(|&i| pieces[i].clone()).collect(); + sorted.extend(pieces.iter().filter(|(_, c)| c.required.is_none()).cloned()); + Self { + library: match v["library"].as_str() { + Some("repurposed") => Library::Repurposed, + _ => Library::Moogs, + }, + min_y: int("min_y"), + max_y: int("max_y"), + burying: match v["burying"].as_str() { + Some("lowest_corner") => Some(Burying::LowestCorner), + Some("average_land") => Some(Burying::AverageLand), + Some("lowest_side") => Some(Burying::LowestSide), + _ => None, + }, + no_liquid: v["no_liquid"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds_pools"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| Some(p.as_str()?.to_owned())) + .collect(), + land_search: match v["land_search"].as_str() { + Some("highest_land") => Some(LandSearch::Highest), + Some("lowest_land") => Some(LandSearch::Lowest), + Some("fixed_height") => Some(LandSearch::Fixed), + _ => None, + }, + ledge: int("ledge_offset_y").unwrap_or(0), + layout: match v["layout"].as_str() { + Some("mineshaft") => Layout::Mineshaft, + _ => Layout::Generic, + }, + pieces: sorted, + } + } + fn required(&self) -> impl Iterator<Item = &Counted> { + self.pieces + .iter() + .map(|(_, c)| c) + .filter(|c| c.required.is_some()) + } +} + +/// The counted templates, loaded, in [`Config::pieces`] order. +struct Counts(Vec<Arc<StructureTemplate>>); +impl Counts { + fn new(limits: &Config, resources: &StructureResources) -> Self { + Self( + limits + .pieces + .iter() + .map(|(id, _)| { + resources + .template(&id.to_string()) + .unwrap_or_else(|| Arc::new(StructureTemplate::empty())) + }) + .collect(), + ) + } + /// The index of a single element's template among the counted ones. + fn of(&self, element: &PoolElement) -> Option<usize> { + let PoolElement::Single { template, .. } = element else { + return None; + }; + self.0.iter().position(|t| Arc::ptr_eq(t, template)) + } +} + +/// PieceLimitedJigsawManager.assembleJigsawStructure and the structure's +/// postLayoutAdjustments: the start's center and the pieces, or None when +/// nothing starts. `start` is the chunk's corner at the sampled start height. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + chunk: ChunkPos, + start: [i32; 3], +) -> Option<([i32; 3], Vec<PoolPiece>)> { + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_large_feature_seed(context.seed(), chunk.x, chunk.z); + let rotation = Rotation::random(&mut random); + let pool = pools.get(config.start_pool, resources, bindings)?; + // An empty start pool crashes the mod's generation; nothing starts. + if pool.templates.is_empty() { + return None; + } + let element = pool.random_template(&mut random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let mut first = PoolPiece { + bounding_box: element.bounding_box(start, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = first.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let top = limits.max_y.unwrap_or(i32::MAX); + let bottom = limits.min_y.unwrap_or(i32::MIN); + let cy = match config.project_to { + Some(kind) => { + let y = start[1] + context.base_height(cx, cz, kind); + if y > top || y < bottom { + return None; + } + y + } + None => start[1], + }; + first.moved(cy - (b.min[1] + first.ground_level_delta)); + let start_box = first.bounding_box; + let (start_position, start_rotation) = (first.position, first.rotation); + let counts = Counts::new(limits, resources); + let run_once = limits.required().next().is_none(); + let mut pieces = vec![first]; + let mut attempts = 0; + // `for (attempts = 0; runOnce || doesNotHaveAllRequiredPieces(...); attempts++)`: + // the first test sees the start piece alone. + while run_once || lacks_required(limits, &counts, &pieces) { + if attempts == 40 { + break; + } + if attempts > 0 { + let element = pool.random_template(&mut random); + pieces = vec![PoolPiece { + bounding_box: element.bounding_box(start_position, start_rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: start_position, + rotation: start_rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }]; + } else { + pieces.truncate(1); + } + if config.max_depth > 0 { + let r = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - r, cy - 120, cz - r], [cx + r, cy + 180, cz + r]), + removed: vec![start_box], + })); + let buried = limits.burying.is_some(); + let mut assembler = Assembler { + config, + limits, + counted: &counts, + pools, + resources, + bindings, + pieces: std::mem::take(&mut pieces), + states: vec![(free, 0)], + counts: vec![0; limits.pieces.len()], + max_y: if buried { i32::MAX } else { top }, + min_y: if buried { i32::MIN } else { bottom }, + }; + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, &mut random); + } + pieces = assembler.pieces; + } + if run_once { + break; + } + attempts += 1; + } + adjust(config, limits, context, start, &mut pieces); + if pieces.is_empty() { + return None; + } + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + // The builder is cleared when the layout reaches past the build height. + if whole.max[1] > context.max_y() + 1 { + return None; + } + Some(([cx, cy, cz], pieces)) +} + +/// doesNotHaveAllRequiredPieces. +fn lacks_required(limits: &Config, counts: &Counts, pieces: &[PoolPiece]) -> bool { + let mut left: Vec<i32> = limits + .pieces + .iter() + .map(|(_, c)| c.required.unwrap_or(0)) + .collect(); + for p in pieces { + if let Some(i) = counts.of(&p.element) { + left[i] -= 1; + } + } + left.iter().any(|&n| n > 0) +} + +/// Moves a piece; Repurposed Structures' movePieceProperly also writes its +/// junctions, all three setters into the source X, so only the last sticks. +fn shift(limits: &Config, piece: &mut PoolPiece, d: [i32; 3]) { + piece.position = std::array::from_fn(|i| piece.position[i] + d[i]); + piece.bounding_box = piece.bounding_box.moved(d); + if limits.library == Library::Repurposed { + for j in &mut piece.junctions { + j.source_x = j.source_z + d[2]; + } + } +} +fn shift_all(limits: &Config, pieces: &mut [PoolPiece], d: [i32; 3]) { + for p in pieces { + shift(limits, p, d); + } +} + +/// The structure's postLayoutAdjustments. +fn adjust( + config: &JigsawConfig<'_>, + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut Vec<PoolPiece>, +) { + if pieces.is_empty() { + return; + } + if limits.layout == Layout::Mineshaft { + below_terrain(limits, context, start, pieces); + return; + } + // GeneralUtils.centerAllPieces on the chunk's corner. + let center = pieces[0].bounding_box.center(); + let d = [start[0] - center[0], 0, start[2] - center[2]]; + for p in pieces.iter_mut() { + // Centring uses StructurePiece.move in both mods. + p.position = std::array::from_fn(|i| p.position[i] + d[i]); + p.bounding_box = p.bounding_box.moved(d); + } + let offset_y = start[1]; + let sea = context.sea_level(); + if let Some(search) = limits.land_search { + nether(limits, context, search, offset_y, pieces); + return; + } + let Some(burying) = limits.burying else { + return; + }; + let kind = config.project_to.unwrap_or(HeightmapType::WorldSurfaceWg); + let ocean_floor = matches!( + kind, + HeightmapType::OceanFloorWg | HeightmapType::OceanFloor + ); + let box0 = pieces[0].bounding_box; + let mut land = match burying { + Burying::LowestCorner => [ + (box0.min[0], box0.min[2]), + (box0.min[0], box0.max[2]), + (box0.max[0], box0.min[2]), + (box0.max[0], box0.max[2]), + ] + .into_iter() + .map(|(x, z)| context.base_height(x, z, kind) - 1) + .min() + .unwrap_or(0), + Burying::LowestSide => { + let c = box0.center(); + let mut highest = i32::MAX; + for (x, z) in [ + (box0.min[0], c[2]), + (c[0], box0.max[2]), + (c[0], box0.min[2]), + (box0.max[0], c[2]), + ] { + // getFirstOccupiedHeight (Repurposed's cached free height - 1). + let land = context.base_height(x, z, kind) - 1; + match limits.min_y { + Some(min) if land >= min => highest = land, + Some(_) => {} + None => highest = highest.min(land), + } + } + if let Some(min) = limits.min_y.filter(|_| highest == i32::MAX) { + highest = min; + } + highest + } + Burying::AverageLand => { + average_land(limits, context, kind, ocean_floor, offset_y, pieces); + return; + } + }; + if limits.no_liquid || !ocean_floor { + land = land.max(sea); + } else { + land = land.min(sea - box0.span()[1]); + } + // offsetToNewHeight. + if limits.max_y.is_some() + && let Some(min) = limits.min_y + && box0.max[1] + offset_y < min + { + land = land.max(limits.max_y.unwrap_or(land)); + } + if let Some(min) = limits.min_y + && box0.min[1] + offset_y < min + { + land = land.min(min); + } + let dy = land - box0.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// MineshaftStructure.postLayoutAdjustments: the layout's top moved to 15 +/// blocks under the lowest ocean floor at the chunk's middle and 16 blocks +/// to each side, within y_allowance; never up. +fn below_terrain( + limits: &Config, + context: &mut impl StartContext, + start: [i32; 3], + pieces: &mut [PoolPiece], +) { + let target = mineshaft_top(start, limits.min_y, |x, z| { + context.base_height(x, z, HeightmapType::OceanFloorWg) + }); + let top = pieces + .iter() + .map(|p| p.bounding_box.max[1]) + .max() + .unwrap_or(i32::MIN); + if target < limits.max_y.unwrap_or(i32::MAX) && target < top { + shift_all(limits, pieces, [0, target - top, 0]); + } +} + +/// Where [`below_terrain`] puts a mineshaft's top: `floor` is the first free +/// height over the ocean floor (getFirstFreeHeight, OCEAN_FLOOR_WG). +fn mineshaft_top( + start: [i32; 3], + min_y: Option<i32>, + mut floor: impl FnMut(i32, i32) -> i32, +) -> i32 { + let (x, z) = (start[0] + 7, start[2] + 7); + let mut terrain = floor(x, z) - 1; + // Plane.HORIZONTAL's order; the mod takes one more off after each. + for (dx, dz) in [(0, -16), (16, 0), (0, 16), (-16, 0)] { + terrain = terrain.min(floor(x + dx, z + dz)) - 1; + } + (terrain - 15).max(min_y.unwrap_or(i32::MIN)) +} + +/// AVERAGE_LAND: the mean land height over a grid on the first piece's +/// footprint; no structure when none of the heights is allowed. +fn average_land( + limits: &Config, + context: &mut impl StartContext, + kind: HeightmapType, + ocean_floor: bool, + offset_y: i32, + pieces: &mut Vec<PoolPiece>, +) { + let b = pieces[0].bounding_box; + let c = b.center(); + let (lx, lz) = (b.max[0] - b.min[0], b.max[2] - b.min[2]); + let radius = (f64::from(lx * lx + lz * lz).sqrt() as i32) / 2; + // The mod's loop never ends with a step of 0; one block apart instead. + let step = (radius / 2).max(1); + let (min, max) = ( + limits.min_y.unwrap_or(i32::MIN), + limits.max_y.unwrap_or(i32::MAX), + ); + let (mut sum, mut n) = (0i64, 0i64); + let mut x = -radius; + while x <= radius { + let mut z = -radius; + while z <= radius { + let h = context.base_height(c[0] + x, c[2] + z, kind) - 1; + if h > min && h < max { + sum += i64::from(h); + n += 1; + } + z += step; + } + x += step; + } + let mut average = (n > 0).then(|| sum as f64 / n as f64); + if average.is_none() { + average = limits.max_y.or(limits.min_y).map(f64::from); + } + let Some(mut average) = average else { + pieces.clear(); + return; + }; + if limits.no_liquid && !ocean_floor { + average = average.max(f64::from(context.sea_level())); + if let Some(max) = limits.max_y { + // Math.max, as the mod has it. + average = average.max(f64::from(max)); + } + } + let dy = average as i32 - b.min[1] + offset_y; + shift_all(limits, pieces, [0, dy, 0]); +} + +/// The Nether variants: onto the highest or lowest land at the layout's +/// center (or a fixed height), a ledge above it, within y_allowance. +fn nether( + limits: &Config, + context: &mut impl StartContext, + search: LandSearch, + offset_y: i32, + pieces: &mut [PoolPiece], +) { + let mut whole = pieces[0].bounding_box; + for p in &pieces[1..] { + whole.encapsulate(&p.bounding_box); + } + let sea = context.sea_level(); + let generation = context.generation(); + let terrain_limit = generation.min_y + generation.height; + let base = pieces[0].bounding_box.min[1]; + let found = |context: &mut dyn ColumnQuery, highest: bool| { + let c = whole.center(); + context.land(c[0], c[2], highest, !limits.no_liquid, sea, terrain_limit) + }; + let mut target = match (limits.library, search) { + (Library::Moogs, LandSearch::Fixed) => offset_y + limits.ledge, + (library, search) => { + let y = found(context, search == LandSearch::Highest); + let at = if y < terrain_limit && y > sea + 1 { + y + } else { + sea + }; + if library == Library::Repurposed { + shift_all(limits, pieces, [0, at + limits.ledge - base, 0]); + return; + } + at + limits.ledge + offset_y + } + }; + let height = whole.max[1] - whole.min[1]; + let below = whole.min[1] - base; + if let Some(top) = limits.max_y { + target = target.min(top - height - below); + } + if let Some(bottom) = limits.min_y { + target = target.max(bottom - below); + } + shift_all(limits, pieces, [0, target - base, 0]); +} + +/// GeneralUtils.getHighestLand and getLowestLand on the noise column. +trait ColumnQuery { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32; +} +impl<C: StartContext> ColumnQuery for C { + fn land( + &mut self, + x: i32, + z: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, + ) -> i32 { + let min = self.generation().min_y; + let mut columns = self.base_columns( + x, + z, + &[HeightmapType::WorldSurfaceWg, HeightmapType::OceanFloorWg], + ); + let solid = columns.pop().unwrap_or_default(); + let filled = columns.pop().unwrap_or_default(); + land_in(&filled, &solid, min, highest, on_liquid, sea, terrain_limit) + } +} + +/// The land search over one noise column: `filled` (not air) and `solid` +/// (canOcclude, for the noise's own blocks) from `min` up; past the +/// column's ends a NoiseColumn reads air. +fn land_in( + filled: &[bool], + solid: &[bool], + min: i32, + highest: bool, + on_liquid: bool, + sea: i32, + terrain_limit: i32, +) -> i32 { + let at = |c: &[bool], y: i32| { + usize::try_from(y - min) + .ok() + .and_then(|i| c.get(i).copied()) + .unwrap_or(false) + }; + let air = |y: i32| !at(filled, y); + let stands = |y: i32| if on_liquid { !air(y) } else { at(solid, y) }; + if highest { + let mut y = terrain_limit - 40; + while y > sea { + if at(solid, y) && air(y + 3) && stands(y) { + return y; + } + y -= 1; + } + y + } else { + let mut y = sea + 1; + while y <= terrain_limit - 40 { + if stands(y) && air(y + 1) && air(y + 5) { + return y + 1; + } + y += 1; + } + sea + } +} + +/// PieceLimitedJigsawManager.Assembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + limits: &'a Config, + counted: &'a Counts, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec<PoolPiece>, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc<RefCell<Free>>, i32)>, + /// Pieces placed per counted template. + counts: Vec<i32>, + max_y: i32, + min_y: i32, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +struct Slot<'s> { + source: usize, + jigsaw: &'s super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc<RefCell<Free>>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option<Arc<super::jigsaw::Pool>> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// generatePiece: one child per jigsaw where one fits, from the target + /// pool unless the piece is at the last depth, else from its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque<usize>, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option<Rc<RefCell<Free>>> = None; + for jigsaw in element.shuffled_jigsaws(self.resources, position, rotation, random) { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw: &jigsaw, + target_pos, + free, + depth, + }; + if depth != self.config.max_depth + && self.process(&slot, target.raw.clone(), false, queue, context, random) + { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + let ignore = self.limits.ignore_bounds.contains(&target.fallback); + self.process(&slot, fallback.raw.clone(), ignore, queue, context, random); + } + } + /// processList: whether a piece was placed. + fn process( + &mut self, + slot: &Slot<'_>, + mut candidates: Vec<(Arc<PoolElement>, i32)>, + ignore_bounds: bool, + queue: &mut VecDeque<usize>, + context: &mut impl StartContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = + |context: &mut dyn SurfaceQuery| *surface.get_or_insert_with(|| context.surface(x, z)); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() { + let mut chosen = None; + // The first required piece still short is forced in once deep enough. + let needed = self + .limits + .pieces + .iter() + .enumerate() + .find(|(i, (_, c))| c.required.is_some_and(|r| self.counts[*i] < r)); + if let Some((need_index, (_, need))) = needed { + let need_template = &self.counted.0[need_index]; + let found = candidates.iter().position(|(e, _)| { + matches!(e.as_ref(), PoolElement::Single { template, .. } + if Arc::ptr_eq(template, need_template)) + }); + if let Some(i) = found { + if slot.depth >= (self.config.max_depth - 1).min(need.min_depth) { + chosen = Some(i); + } else { + total -= candidates[i].1; + candidates.remove(i); + } + } + } + let index = match chosen { + Some(i) => i, + None => { + if total <= 0 || candidates.is_empty() { + return false; + } + let mut weight = random.next_int_bound(total).unwrap_or(0) + 1; + let mut found = candidates.len() - 1; + for (i, (_, w)) in candidates.iter().enumerate() { + weight -= w; + if weight <= 0 { + found = i; + break; + } + } + found + } + }; + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let counted = self.counted.of(&target); + let full = counted.is_some_and(|i| { + self.limits.pieces[i] + .1 + .max + .is_some_and(|m| self.counts[i] >= m) + }); + if full { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if target_box.max[1] > self.max_y || target_box.min[1] < self.min_y { + continue; + } + if !ignore_bounds && !slot.free.borrow().fits(&target_box) { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + self.pieces[slot.source].junctions.push(Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some(i) = counted { + self.counts[i] += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +/// The surface height query, object-safe for the per-call cache. +trait SurfaceQuery { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl<C: StartContext> SurfaceQuery for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + #[test] + fn required_pieces_follow_javas_hash_map() { + let limits = Config::decode(&json!({"library": "repurposed", "pieces": [ + {"name": "rs:city/a", "required": 1}, + {"name": "rs:city/x", "max": 2}, + {"name": "rs:city/b", "required": 1, "min_depth": 3}, + {"name": "rs:city/c", "required": 2}, + {"name": "rs:city/a", "required": 4}]})); + let names: Vec<String> = limits.pieces.iter().map(|(id, _)| id.to_string()).collect(); + // Buckets 3, 2, 1 of the copied map's 4: c, b, a; then the capped one. + assert_eq!(names, ["rs:city/c", "rs:city/b", "rs:city/a", "rs:city/x"]); + assert_eq!( + limits.pieces[2].1.required, + Some(4), + "a later entry replaces" + ); + assert_eq!(limits.pieces[1].1.min_depth, 3); + assert_eq!(limits.library, Library::Repurposed); + } + + #[test] + fn mineshafts_go_under_the_lowest_floor_around() { + // Floor 80 at the middle (7, 7), 70 north, 90 east, 60 south, 85 west. + let floor = |x, z| match (x, z) { + (7, 7) => 80, + (7, -9) => 70, + (23, 7) => 90, + (7, 23) => 60, + (-9, 7) => 85, + other => panic!("{other:?}"), + }; + // 79, min(79, 70) - 1 = 69, 68, min(68, 60) - 1 = 59, 58; 15 under it. + assert_eq!(mineshaft_top([0, 50, 0], None, floor), 43); + assert_eq!(mineshaft_top([0, 50, 0], Some(48), floor), 48); + } + + #[test] + fn nether_land_is_found_in_the_column() { + // A column from y 0: netherrack to 40, lava 41..=45, air, a ledge 70..=72. + let (mut filled, mut solid) = (vec![false; 128], vec![false; 128]); + for y in 0..=45 { + filled[y] = true; + solid[y] = y <= 40; + } + for y in 70..=72 { + filled[y] = true; + solid[y] = true; + } + // Highest: from 88 down, a solid block with air 3 above. + assert_eq!(land_in(&filled, &solid, 0, true, true, 32, 128), 72); + // Lowest: from 33 up, a block to stand on with air 1 and 5 above; one up. + assert_eq!(land_in(&filled, &solid, 0, false, true, 32, 128), 46); + assert_eq!(land_in(&filled, &solid, 0, false, false, 32, 128), 73); + // Nothing found: the highest search stops at the sea level. + let empty = vec![false; 128]; + assert_eq!(land_in(&empty, &empty, 0, true, true, 32, 128), 32); + assert_eq!(land_in(&empty, &empty, 0, false, true, 32, 128), 32); + } + + #[test] + fn repurposed_moves_junctions_as_its_code_does() { + let template = Arc::new(StructureTemplate::empty()); + let element = Arc::new(PoolElement::Single { + template, + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: None, + }); + let piece = || PoolPiece { + bounding_box: BoundingBox::new([0; 3], [4; 3]), + ground_level_delta: 1, + element: element.clone(), + position: [0; 3], + rotation: Rotation::None, + junctions: vec![Junction { + source_x: 1, + source_ground_y: 2, + source_z: 3, + }], + waterlogging: true, + }; + let moogs = Config::decode(&json!({})); + let rs = Config::decode(&json!({"library": "repurposed"})); + let (mut a, mut b) = (piece(), piece()); + shift(&moogs, &mut a, [10, 20, 30]); + shift(&rs, &mut b, [10, 20, 30]); + assert_eq!(a.bounding_box, BoundingBox::new([10, 20, 30], [14, 24, 34])); + assert_eq!(a.position, [10, 20, 30]); + assert_eq!(a.junctions[0].source_x, 1); + // movePieceProperly sets the source X three times; Z + dz is left. + assert_eq!(b.junctions[0].source_x, 33); + assert_eq!(b.junctions[0].source_ground_y, 2); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index b5bf2e22f..dd65ccd56 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -21,6 +21,8 @@ use horizon_core::{ use serde_json::Value; use std::{collections::BTreeSet, sync::Arc}; +mod lithostitched; + /// The draws processors make from StructurePlaceSettings' random. pub trait ProcessorRandom { fn float(&mut self) -> f32; @@ -49,6 +51,22 @@ enum PosRule { max_dist: i32, axis: Option<usize>, }, + /// `horizon:piece_origin_axis_aligned_linear_pos`: Repurposed Structures' + /// PieceOriginAxisAlignedLinearPosRuleTest, vanilla's axis-aligned chance + /// over the block's distance from the template's origin along one axis. + PieceOrigin { + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + axis: usize, + }, + /// `horizon:y_value`: Repurposed Structures' YValuePosRuleTest, the + /// block's world height in `min_y_value..=max_y_value`. + YValue { + min: i32, + max: i32, + }, } #[derive(Clone, Debug)] enum Modifier { @@ -56,6 +74,188 @@ enum Modifier { Clear, AppendLoot(String), AppendStatic(Compound), + /// `horizon:edit`: `remove`'s keys taken out of the block entity, then + /// `data` merged in as append_static does. The data form of the mods' + /// processors that copy a block entity and change parts of it (Moog's + /// trial spawners and vaults drop their saved state). + Edit { + remove: Vec<String>, + data: Compound, + }, +} +impl PosRule { + /// A rule's `position_predicate` (always true when missing). Types are + /// identifiers: `"always_true"` is `minecraft:always_true`, as vanilla + /// reads it. + fn decode(value: Option<&Value>) -> Result<Self, DecodeError> { + let Some(p) = value else { + return Ok(Self::Always); + }; + let kind = p["predicate_type"] + .as_str() + .unwrap_or("minecraft:always_true"); + Ok(match super::super::tags::identifier(kind)?.as_str() { + "minecraft:always_true" => Self::Always, + kind @ ("minecraft:linear_pos" | "minecraft:axis_aligned_linear_pos") => Self::Linear { + min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) as i32, + max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) as i32, + axis: (kind == "minecraft:axis_aligned_linear_pos").then(|| { + match p.get("axis").and_then(Value::as_str) { + Some("x") => 0, + Some("z") => 2, + _ => 1, + } + }), + }, + "horizon:piece_origin_axis_aligned_linear_pos" => { + let int = |key| p.get(key).and_then(Value::as_i64).unwrap_or(0) as i32; + let (min_dist, max_dist) = (int("min_dist"), int("max_dist")); + if min_dist >= max_dist { + return Err(DecodeError::Field("position predicate distance range")); + } + Self::PieceOrigin { + min_chance: p.get("min_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + max_chance: p.get("max_chance").and_then(Value::as_f64).unwrap_or(0.) as f32, + min_dist, + max_dist, + axis: match p.get("axis").map(|a| a.as_str()) { + Some(Some("x")) => 0, + None | Some(Some("y")) => 1, + Some(Some("z")) => 2, + _ => return Err(DecodeError::Field("position predicate axis")), + }, + } + } + "horizon:y_value" => { + let int = |key| { + p.get(key) + .and_then(Value::as_i64) + .map(|v| v as i32) + .ok_or(DecodeError::Field("position predicate y value")) + }; + let (min, max) = (int("min_y_value")?, int("max_y_value")?); + if min > max { + return Err(DecodeError::Field("position predicate y range")); + } + Self::YValue { min, max } + } + _ => return Err(DecodeError::Field("position predicate")), + }) + } + /// PosRuleTest.test for a block at `world`, `relative` in its template, + /// in a piece placed at `reference`. + fn test( + &self, + relative: [i32; 3], + world: [i32; 3], + reference: [i32; 3], + random: &mut impl RandomSource, + ) -> bool { + match *self { + Self::Always => true, + Self::Linear { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = match axis { + None => (0..3).map(|i| (world[i] - reference[i]).abs()).sum::<i32>(), + Some(a) => ((world[a] - reference[a]) as f32).abs() as i32, + }; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::PieceOrigin { + min_chance, + max_chance, + min_dist, + max_dist, + axis, + } => { + let dist = (relative[axis] as f32).abs() as i32; + random.next_float() + <= clamped_chance(min_chance, max_chance, min_dist, max_dist, dist) + } + Self::YValue { min, max } => (min..=max).contains(&world[1]), + } + } +} +/// Mth.clampedLerp(min_chance, max_chance, Mth.inverseLerp(dist, min_dist, max_dist)). +fn clamped_chance( + min_chance: f32, + max_chance: f32, + min_dist: i32, + max_dist: i32, + dist: i32, +) -> f32 { + let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; + if t < 0. { + min_chance + } else if t > 1. { + max_chance + } else { + min_chance + t * (max_chance - min_chance) + } +} +impl Modifier { + /// A rule's `block_entity_modifier` (passthrough when missing). + fn decode(value: Option<&Value>) -> Result<Self, DecodeError> { + let Some(m) = value else { + return Ok(Self::Passthrough); + }; + Ok( + match super::super::tags::identifier(m["type"].as_str().unwrap_or(""))?.as_str() { + "minecraft:passthrough" => Self::Passthrough, + "minecraft:clear" => Self::Clear, + "minecraft:append_loot" => { + Self::AppendLoot(m["loot_table"].as_str().unwrap_or_default().to_owned()) + } + "minecraft:append_static" => match json_to_nbt(&m["data"]) { + Tag::Compound(c) => Self::AppendStatic(c), + _ => Self::AppendStatic(Compound::new()), + }, + "horizon:edit" => Self::Edit { + remove: m["remove"] + .as_array() + .into_iter() + .flatten() + .map(|k| k.as_str().map(str::to_owned)) + .collect::<Option<_>>() + .ok_or(DecodeError::Field("block entity modifier keys"))?, + data: match json_to_nbt(&m["data"]) { + Tag::Compound(c) => c, + _ => Compound::new(), + }, + }, + _ => return Err(DecodeError::Field("block entity modifier")), + }, + ) + } +} +/// A block entity with `remove`'s keys taken out and `data` merged in +/// (append_static is the one with nothing to remove). +fn edited(nbt: Option<&Compound>, remove: &[String], data: &Compound) -> Compound { + let mut nbt = nbt.cloned().unwrap_or_default(); + for key in remove { + nbt.remove(&JavaString::from(key.as_str())); + } + merge(&mut nbt, data); + nbt +} +/// CompoundTag.merge: compounds in both are merged, anything else replaced. +fn merge(into: &mut Compound, other: &Compound) { + for (key, value) in other { + match (into.get_mut(key), value) { + (Some(Tag::Compound(mine)), Tag::Compound(theirs)) => merge(mine, theirs), + _ => { + into.insert(key.clone(), value.clone()); + } + } + } } #[derive(Clone, Debug)] pub struct Rule { @@ -87,10 +287,322 @@ pub enum Processor { BlockAge(f32), LavaSubmerged, BlackstoneReplace, + SpawnerMobs(Box<SpawnerMobs>), + Pick(Box<Pick>), + CountCap(Box<CountCap>), + /// `horizon:block_swap` (Lithostitched's `block_swap`): blocks by name + /// become others, keeping the properties both have. + BlockSwap(std::collections::BTreeMap<String, String>), + /// `horizon:apply_random` (Lithostitched's `apply_random`): a processor + /// list drawn by weight runs on the block. + ApplyRandom(Box<lithostitched::ApplyRandom>), + /// `horizon:condition` (Lithostitched's `condition`): `then` or `else` + /// runs on the block, by a test of it. + Condition(Box<lithostitched::Conditional>), + /// `horizon:set_block` (Lithostitched's `set_block`). + SetBlock(Box<lithostitched::SetBlock>), } #[derive(Clone, Debug, Default)] pub struct ProcessorList(pub Vec<Processor>); +/// The spawner fields `horizon:spawner_mobs` writes: its JSON key, the NBT +/// key and the default (BaseSpawner's). +const SPAWNER_FIELDS: [(&str, &str, i16); 7] = [ + ("delay", "Delay", 20), + ("min_spawn_delay", "MinSpawnDelay", 200), + ("max_spawn_delay", "MaxSpawnDelay", 800), + ("spawn_count", "SpawnCount", 4), + ("max_nearby_entities", "MaxNearbyEntities", 6), + ("required_player_range", "RequiredPlayerRange", 16), + ("spawn_range", "SpawnRange", 4), +]; + +/// `horizon:pick`, which `horizon-port-pack` writes for the mods' processors +/// that turn a placeholder block into one of several (YUNG's, written in +/// Java): a block of `block` takes the first of `picks` whose `below` is past +/// one `settings.getRandom(pos).nextFloat()`, else `default` (no float is +/// drawn when there are no picks; with no default the block stays). +#[derive(Clone, Debug)] +pub struct Pick { + block: String, + picks: Vec<(f32, Outcome)>, + default: Option<Outcome>, +} +#[derive(Clone, Debug)] +struct Outcome { + /// The state, or one of them by `nextInt(len)` (Util.getRandom), drawn + /// after the pick. + states: Vec<BlockStateId>, + /// The new block entity; the block's own stays when missing. + nbt: Option<Compound>, + /// Keys set to lists of `count` strings, each the first of `values` + /// whose bound is past a new `nextFloat`, else `default` (pot sherds). + lists: Vec<PickedList>, +} +#[derive(Clone, Debug)] +struct PickedList { + key: String, + count: usize, + values: Vec<(f32, String)>, + default: String, +} +fn below(v: &Value) -> Result<f32, DecodeError> { + v["below"] + .as_f64() + .map(|b| b as f32) + .ok_or(DecodeError::Field("pick bound")) +} +impl Pick { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let outcome = |v: &Value| -> Result<Outcome, DecodeError> { + let states = match v.get("states") { + Some(list) => list + .as_array() + .ok_or(DecodeError::Field("pick states"))? + .iter() + .map(&state) + .collect::<Result<Vec<_>, _>>()?, + None => vec![state(&v["state"])?], + }; + if states.is_empty() { + return Err(DecodeError::Field("pick states")); + } + let nbt = match v.get("nbt").map(json_to_nbt) { + Some(Tag::Compound(c)) => Some(c), + Some(_) => return Err(DecodeError::Field("pick nbt")), + None => None, + }; + let text = |v: &Value| { + v.as_str() + .map(str::to_owned) + .ok_or(DecodeError::Field("pick list")) + }; + let lists = v["lists"] + .as_array() + .into_iter() + .flatten() + .map(|l| { + Ok(PickedList { + key: text(&l["key"])?, + count: l["count"].as_u64().ok_or(DecodeError::Field("pick list"))? as usize, + values: l["values"] + .as_array() + .into_iter() + .flatten() + .map(|e| Ok((below(e)?, text(&e["value"])?))) + .collect::<Result<_, DecodeError>>()?, + default: text(&l["default"])?, + }) + }) + .collect::<Result<_, DecodeError>>()?; + Ok(Outcome { states, nbt, lists }) + }; + Ok(Self { + block: value["block"] + .as_str() + .map(|b| super::super::tags::identifier(b).map(|i| i.to_string())) + .ok_or(DecodeError::Field("pick block"))??, + picks: value["picks"] + .as_array() + .into_iter() + .flatten() + .map(|p| Ok((below(p)?, outcome(p)?))) + .collect::<Result<_, DecodeError>>()?, + default: value.get("default").map(outcome).transpose()?, + }) + } + fn apply(&self, info: BlockInfo, random: &mut dyn ProcessorRandom) -> BlockInfo { + let outcome = match self.picks.is_empty() { + true => self.default.as_ref(), + false => { + let f = random.float(); + self.picks + .iter() + .find(|(b, _)| f < *b) + .map(|(_, o)| o) + .or(self.default.as_ref()) + } + }; + let Some(outcome) = outcome else { + return info; + }; + let state = match outcome.states.as_slice() { + [one] => *one, + many => many[random.int(many.len() as i32) as usize], + }; + let mut nbt = outcome.nbt.clone().or(info.nbt); + for list in &outcome.lists { + let values = (0..list.count) + .map(|_| { + let f = random.float(); + let v = list + .values + .iter() + .find(|(b, _)| f < *b) + .map_or(&list.default, |(_, v)| v); + Tag::String(v.as_str().into()) + }) + .collect(); + nbt.get_or_insert_with(Compound::new) + .insert(list.key.as_str().into(), Tag::List(values)); + } + BlockInfo { + pos: info.pos, + state, + nbt, + } + } +} + +/// `horizon:count_cap`, which `horizon-port-pack` writes for Better +/// Dungeons' chest processor (Java in the mod): of the `blocks` one +/// placement meets, the first `min` stay, the rest each stay when +/// `settings.getRandom(pos).nextFloat() <= chance` until `max` have, and the +/// others become `replacement`. The count is the placement's (the mod's +/// DungeonContext, set up per StructureTemplate.placeInWorld: one chunk of +/// the piece), shared by every such processor in it. +#[derive(Clone, Debug)] +pub struct CountCap { + blocks: BTreeSet<String>, + min: u32, + max: u32, + chance: f32, + replacement: BlockStateId, +} +impl CountCap { + fn decode( + value: &Value, + state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let count = |key: &'static str| { + value[key] + .as_u64() + .and_then(|n| u32::try_from(n).ok()) + .ok_or(DecodeError::Field(key)) + }; + Ok(Self { + blocks: value["blocks"] + .as_array() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|b| { + let b = b.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(super::super::tags::identifier(b)?.to_string()) + }) + .collect::<Result<_, DecodeError>>()?, + min: count("min")?, + max: count("max")?, + chance: float(value, "chance")?, + replacement: state(&value["replacement"])?, + }) + } + /// Whether a counted block stays, counting it if so. + fn keeps(&self, counted: &mut u32, roll: impl FnOnce() -> f32) -> bool { + let keep = *counted < self.min || (*counted < self.max && roll() <= self.chance); + *counted += u32::from(keep); + keep + } +} + +/// `horizon:spawner_mobs`, which `horizon-port-pack` writes for the spawner +/// randomizing processors of Moog's Structure Lib and Repurposed Structures +/// (Java code in the mods): a spawner gets one mob of a weighted list, +/// picked with `settings.getRandom(pos).nextFloat()` as theirs do, and the +/// spawner NBT they write. With no mob to pick it becomes `replacement`. +#[derive(Clone, Debug)] +pub struct SpawnerMobs { + /// Each mob's entity compound (its `id` and any NBT) and weight. + mobs: Vec<(Compound, f64)>, + /// [`SPAWNER_FIELDS`]' values. + fields: [i16; 7], + /// `custom_spawn_rules`, in `SpawnData` and the potential alike. + rules: Option<Compound>, + replacement: BlockStateId, +} +impl SpawnerMobs { + fn decode( + value: &Value, + replacement: impl FnOnce(Option<&Value>) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let mobs = value["mobs"] + .as_array() + .ok_or(DecodeError::Field("spawner_mobs mobs"))? + .iter() + .map( + |m| match (json_to_nbt(&m["entity"]), m["weight"].as_f64()) { + (Tag::Compound(entity), Some(weight)) + if entity.contains_key(&JavaString::from("id")) => + { + Ok((entity, weight)) + } + _ => Err(DecodeError::Field("spawner_mobs mob")), + }, + ) + .collect::<Result<_, _>>()?; + let mut fields = [0; 7]; + for (field, (key, _, default)) in fields.iter_mut().zip(SPAWNER_FIELDS) { + // The mods' codecs read ints; the spawner saves them as shorts. + *field = value + .get(key) + .map_or(Some(default), |v| v.as_i64().map(|v| v as i16)) + .ok_or(DecodeError::Field("spawner_mobs field"))?; + } + let rules = match value.get("custom_spawn_rules").map(json_to_nbt) { + None => None, + Some(Tag::Compound(c)) => Some(c), + Some(_) => return Err(DecodeError::Field("spawner_mobs custom_spawn_rules")), + }; + Ok(Self { + mobs, + fields, + rules, + replacement: replacement(value.get("replacement"))?, + }) + } + /// The mob for a spawner, drawing from `random` only when there is one + /// to pick (pickWeightedRandom; Repurposed Structures' getSpawnerMob, + /// whose float product can round differently only on a boundary). + fn pick(&self, random: impl FnOnce() -> f32) -> Option<&Compound> { + let total: f64 = self.mobs.iter().map(|m| m.1).sum(); + if self.mobs.is_empty() || total <= 0. { + return None; + } + let mut pick = f64::from(random()) * total; + for (entity, weight) in &self.mobs { + pick -= weight; + if pick <= 0. { + return Some(entity); + } + } + self.mobs.last().map(|m| &m.0) + } + /// The spawner's NBT with `entity` as its only potential and next spawn. + fn nbt(&self, entity: &Compound) -> Compound { + let mut data = Compound::new(); + data.insert("entity".into(), Tag::Compound(entity.clone())); + if let Some(rules) = &self.rules { + data.insert("custom_spawn_rules".into(), Tag::Compound(rules.clone())); + } + let mut potential = Compound::new(); + potential.insert("data".into(), Tag::Compound(data.clone())); + potential.insert("weight".into(), Tag::Int(1)); + let mut nbt: Compound = SPAWNER_FIELDS + .iter() + .zip(self.fields) + .map(|((_, key, _), v)| (JavaString::from(*key), Tag::Short(v))) + .collect(); + nbt.insert( + "SpawnPotentials".into(), + Tag::List(vec![Tag::Compound(potential)]), + ); + nbt.insert("SpawnData".into(), Tag::Compound(data)); + nbt + } +} + fn holder_set( value: &Value, bindings: &FeatureBlockBindings<'_>, @@ -208,55 +720,8 @@ impl Processor { .iter() .map(|rule| { let test = |key| RuleTest::from_json(&rule[key].to_string(), bindings); - let position = match rule.get("position_predicate") { - Some(p) => match p["predicate_type"] - .as_str() - .unwrap_or("minecraft:always_true") - { - "minecraft:always_true" => PosRule::Always, - kind @ ("minecraft:linear_pos" - | "minecraft:axis_aligned_linear_pos") => PosRule::Linear { - min_chance: p - .get("min_chance") - .and_then(Value::as_f64) - .unwrap_or(0.) - as f32, - max_chance: p - .get("max_chance") - .and_then(Value::as_f64) - .unwrap_or(0.) - as f32, - min_dist: p.get("min_dist").and_then(Value::as_i64).unwrap_or(0) - as i32, - max_dist: p.get("max_dist").and_then(Value::as_i64).unwrap_or(0) - as i32, - axis: (kind == "minecraft:axis_aligned_linear_pos").then( - || match p.get("axis").and_then(Value::as_str) { - Some("x") => 0, - Some("z") => 2, - _ => 1, - }, - ), - }, - _ => return Err(DecodeError::Field("position predicate")), - }, - None => PosRule::Always, - }; - let modifier = match rule.get("block_entity_modifier") { - None => Modifier::Passthrough, - Some(m) => match m["type"].as_str().unwrap_or("") { - "minecraft:passthrough" => Modifier::Passthrough, - "minecraft:clear" => Modifier::Clear, - "minecraft:append_loot" => Modifier::AppendLoot( - m["loot_table"].as_str().unwrap_or_default().to_owned(), - ), - "minecraft:append_static" => match json_to_nbt(&m["data"]) { - Tag::Compound(c) => Modifier::AppendStatic(c), - _ => Modifier::AppendStatic(Compound::new()), - }, - _ => return Err(DecodeError::Field("block entity modifier")), - }, - }; + let position = PosRule::decode(rule.get("position_predicate"))?; + let modifier = Modifier::decode(rule.get("block_entity_modifier"))?; Ok(Rule { input: test("input_predicate")?, location: test("location_predicate")?, @@ -267,6 +732,37 @@ impl Processor { }) .collect::<Result<_, DecodeError>>()?, ), + "horizon:spawner_mobs" => { + Self::SpawnerMobs(Box::new(SpawnerMobs::decode(value, |v| match v { + Some(v) => state(v), + None => Ok(resources.registry.default_state("minecraft:air").unwrap()), + })?)) + } + "horizon:pick" => Self::Pick(Box::new(Pick::decode(value, state)?)), + "horizon:block_swap" => Self::BlockSwap( + value["blocks"] + .as_object() + .ok_or(DecodeError::Field("blocks"))? + .iter() + .map(|(from, to)| { + let to = to.as_str().ok_or(DecodeError::Field("blocks"))?; + Ok(( + super::super::tags::identifier(from)?.to_string(), + super::super::tags::identifier(to)?.to_string(), + )) + }) + .collect::<Result<_, DecodeError>>()?, + ), + "horizon:count_cap" => Self::CountCap(Box::new(CountCap::decode(value, state)?)), + "horizon:apply_random" => Self::ApplyRandom(Box::new( + lithostitched::ApplyRandom::decode(value, resources, bindings)?, + )), + "horizon:set_block" => { + Self::SetBlock(Box::new(lithostitched::SetBlock::decode(value, state)?)) + } + "horizon:condition" => Self::Condition(Box::new(lithostitched::Conditional::decode( + value, resources, bindings, + )?)), _ => return Err(DecodeError::Field("structure processor type")), }) } @@ -320,6 +816,8 @@ pub struct PlaceSettings<'a> { /// StructurePlaceSettings.ignoreEntities / finalizeEntities. pub ignore_entities: bool, pub finalize_entities: bool, + /// The blocks `horizon:count_cap` kept in this placement. + counted: u32, } impl<'a> PlaceSettings<'a> { pub fn new(rotation: Rotation) -> Self { @@ -334,6 +832,7 @@ impl<'a> PlaceSettings<'a> { known_shape: false, ignore_entities: false, finalize_entities: false, + counted: 0, } } pub fn with_processors(mut self, list: &'a ProcessorList) -> Self { @@ -355,6 +854,30 @@ impl<'a> PlaceSettings<'a> { } } +/// Block.withPropertiesOf: `block`'s default state with each property of +/// `from` it has too (by name, when the value is one of its own). None for +/// a block the registry does not know (the mod keeps the block then). +fn with_properties_of( + registry: &crate::registry::BlockRegistry, + block: &str, + from: BlockStateId, +) -> Option<BlockStateId> { + let default = registry.default_state(block)?; + let mut state = registry.state(default)?.clone(); + for (key, value) in ®istry.state(from)?.properties { + if let Some(own) = state.properties.get(key) + && own != value + { + let mut changed = state.clone(); + changed.properties.insert(key.clone(), value.clone()); + if registry.id(&changed).is_some() { + state = changed; + } + } + } + registry.id(&state) +} + /// BlackstoneReplaceProcessor's block map. fn blackstone(name: &str) -> Option<&'static str> { Some(match name.strip_prefix("minecraft:")? { @@ -376,11 +899,37 @@ fn blackstone(name: &str) -> Option<&'static str> { }) } type ProcessResult = Result<Option<BlockInfo>, PlacementQueryError>; +/// The processors of a list in turn, until one removes the block. +#[allow(clippy::too_many_arguments)] +fn process_list<W: PlacementContext>( + list: &ProcessorList, + world: &mut W, + resources: &StructureResources, + position: [i32; 3], + reference: [i32; 3], + relative: [i32; 3], + info: BlockInfo, + settings: &mut PlaceSettings<'_>, +) -> ProcessResult { + let mut current = info; + for processor in &list.0 { + match process_block( + processor, world, resources, position, reference, relative, current, settings, + )? { + Some(next) => current = next, + None => return Ok(None), + } + } + Ok(Some(current)) +} +/// StructureProcessor.processBlock: `position` is the piece's, `reference` +/// the structure's pivot and `relative` the block's in the template. #[allow(clippy::too_many_arguments)] fn process_block<W: PlacementContext>( processor: &Processor, world: &mut W, resources: &StructureResources, + position: [i32; 3], reference: [i32; 3], relative: [i32; 3], info: BlockInfo, @@ -469,42 +1018,9 @@ fn process_block<W: PlacementContext>( if !rule.location.test(located, info.pos, &mut random) { continue; } - let position_ok = match &rule.position { - PosRule::Always => true, - PosRule::Linear { - min_chance, - max_chance, - min_dist, - max_dist, - axis, - } => { - let dist = match axis { - None => (0..3) - .map(|i| (info.pos[i] - reference[i]).abs()) - .sum::<i32>(), - Some(a) => { - let d: [f32; 3] = std::array::from_fn(|i| { - if i == *a { - ((info.pos[i] - reference[i]) as f32).abs() - } else { - 0. - } - }); - (d[0] + d[1] + d[2]) as i32 - } - }; - let roll = random.next_float(); - let t = (dist - min_dist) as f32 / (max_dist - min_dist) as f32; - let chance = if t < 0. { - *min_chance - } else if t > 1. { - *max_chance - } else { - min_chance + t * (max_chance - min_chance) - }; - roll <= chance - } - }; + let position_ok = rule + .position + .test(relative, info.pos, reference, &mut random); if !position_ok { continue; } @@ -517,10 +1033,9 @@ fn process_block<W: PlacementContext>( nbt.insert("LootTableSeed".into(), Tag::Long(random.next_long())); Some(nbt) } - Modifier::AppendStatic(data) => { - let mut nbt = info.nbt.clone().unwrap_or_default(); - nbt.extend(data.clone()); - Some(nbt) + Modifier::AppendStatic(data) => Some(edited(info.nbt.as_ref(), &[], data)), + Modifier::Edit { remove, data } => { + Some(edited(info.nbt.as_ref(), remove, data)) } }; return Ok(Some(BlockInfo { @@ -532,6 +1047,90 @@ fn process_block<W: PlacementContext>( Some(info) } Processor::Capped { .. } => Some(info), + Processor::BlockSwap(blocks) => { + let swapped = blocks + .get(name(info.state)) + .and_then(|to| with_properties_of(registry, to, info.state)); + Some(match swapped { + Some(state) => BlockInfo { state, ..info }, + None => info, + }) + } + Processor::CountCap(cap) => match cap.blocks.contains(name(info.state)) { + true => { + let pos = info.pos; + let mut counted = settings.counted; + let keep = cap.keeps(&mut counted, || settings.with_random(pos, |r| r.float())); + settings.counted = counted; + Some(match keep { + true => info, + false => BlockInfo { + pos, + state: cap.replacement, + nbt: None, + }, + }) + } + false => Some(info), + }, + Processor::ApplyRandom(apply) => { + let seed = world.world_seed()?; + let mut random = apply.random.create(seed, position, reference, info.pos); + match apply.pick(&mut random) { + Some(list) => { + return process_list( + list, world, resources, position, reference, relative, info, settings, + ); + } + None => Some(info), + } + } + Processor::SetBlock(set) => { + let seed = world.world_seed()?; + let state = set.state(seed, position, reference, info.pos); + let state = match set.preserves() { + true => registry + .state(state) + .and_then(|s| with_properties_of(registry, &s.name, info.state)) + .unwrap_or(state), + false => state, + }; + Some(BlockInfo { state, ..info }) + } + Processor::Condition(c) => { + let seed = world.world_seed()?; + let mut random = c.random.create(seed, position, reference, info.pos); + let location = world.block_state(info.pos)?; + let passed = c + .condition + .test(info.state, location, registry, &mut random); + let list = if passed { &c.then } else { &c.otherwise }; + return process_list( + list, world, resources, position, reference, relative, info, settings, + ); + } + Processor::Pick(pick) => match name(info.state) == pick.block { + true => Some(settings.with_random(info.pos, |r| pick.apply(info, r))), + false => Some(info), + }, + Processor::SpawnerMobs(spawner) => { + if name(info.state) != "minecraft:spawner" { + return Ok(Some(info)); + } + let pos = info.pos; + let entity = spawner.pick(|| settings.with_random(pos, |r| r.float())); + Some(match entity { + Some(entity) => BlockInfo { + nbt: Some(spawner.nbt(entity)), + ..info + }, + None => BlockInfo { + pos, + state: spawner.replacement, + nbt: None, + }, + }) + } }) } fn block_age( @@ -631,6 +1230,7 @@ fn process_infos<W: PlacementContext>( reference: [i32; 3], settings: &mut PlaceSettings<'_>, ) -> Result<Vec<BlockInfo>, PlacementQueryError> { + settings.counted = 0; let whole = settings .processors .iter() @@ -657,7 +1257,7 @@ fn process_infos<W: PlacementContext>( for processor in processors { let Some(value) = current.take() else { break }; current = process_block( - processor, world, resources, reference, info.pos, value, settings, + processor, world, resources, position, reference, info.pos, value, settings, )?; } if let Some(value) = current { @@ -701,6 +1301,7 @@ fn process_infos<W: PlacementContext>( delegate, world, resources, + position, reference, original[index].pos, before.clone(), @@ -1021,3 +1622,365 @@ fn update_shape_at_edge<W: PlacementContext>( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn spawner(value: Value) -> SpawnerMobs { + SpawnerMobs::decode(&value, |v| { + assert_eq!(v, Some(&json!({"id": "minecraft:cobblestone"}))); + Ok(BlockStateId(7)) + }) + .unwrap() + } + fn id(entity: Option<&Compound>) -> Option<String> { + match entity?.get(&JavaString::from("id")) { + Some(Tag::String(s)) => Some(s.to_string_lossy()), + _ => None, + } + } + + #[test] + fn spawner_mobs_pick_by_weight() { + let s = spawner(json!({ + "mobs": [ + {"entity": {"id": "minecraft:zombie"}, "weight": 1}, + {"entity": {"id": "minecraft:husk"}, "weight": 3}], + "replacement": {"id": "minecraft:cobblestone"}})); + // pick = nextFloat * 4, less each weight in turn, until <= 0. + for (r, mob) in [ + (0., "zombie"), + (0.25, "zombie"), + (0.2501, "husk"), + (0.999, "husk"), + ] { + assert_eq!(id(s.pick(|| r)), Some(format!("minecraft:{mob}")), "{r}"); + } + let empty = spawner(json!({"mobs": [], "replacement": {"id": "minecraft:cobblestone"}})); + assert_eq!(empty.pick(|| unreachable!()), None); + assert_eq!(empty.replacement, BlockStateId(7)); + } + + #[test] + fn spawner_mobs_write_the_mods_nbt() { + let s = spawner(json!({ + "mobs": [{"entity": {"id": "minecraft:skeleton", "Health": 30}, "weight": 2}], + "delay": 10, "spawn_count": 2, + "custom_spawn_rules": {"block_light_limit": {"min_inclusive": 0, "max_inclusive": 7}}, + "replacement": {"id": "minecraft:cobblestone"}})); + let nbt = s.nbt(s.pick(|| 0.5).unwrap()); + let short = |k: &str| nbt.get(&JavaString::from(k)).cloned(); + for (k, v) in [ + ("Delay", 10), + ("MinSpawnDelay", 200), + ("MaxSpawnDelay", 800), + ("SpawnCount", 2), + ("MaxNearbyEntities", 6), + ("RequiredPlayerRange", 16), + ("SpawnRange", 4), + ] { + assert_eq!(short(k), Some(Tag::Short(v)), "{k}"); + } + let Some(Tag::Compound(data)) = short("SpawnData") else { + panic!("SpawnData") + }; + assert!(data.contains_key(&JavaString::from("custom_spawn_rules"))); + let Some(Tag::Compound(entity)) = data.get(&JavaString::from("entity")) else { + panic!("entity") + }; + assert_eq!(entity.get(&JavaString::from("Health")), Some(&Tag::Int(30))); + let Some(Tag::List(potentials)) = short("SpawnPotentials") else { + panic!("SpawnPotentials") + }; + let Tag::Compound(potential) = &potentials[0] else { + panic!("potential") + }; + assert_eq!( + potential.get(&JavaString::from("weight")), + Some(&Tag::Int(1)) + ); + assert_eq!( + potential.get(&JavaString::from("data")), + Some(&Tag::Compound(data.clone())) + ); + } + + #[test] + fn spawner_mobs_refuse_a_mob_without_an_id() { + let bad = json!({"mobs": [{"entity": {}, "weight": 1}]}); + assert!(SpawnerMobs::decode(&bad, |_| Ok(BlockStateId(0))).is_err()); + } + + #[test] + fn repurposed_position_rules() { + let decode = |v: Value| PosRule::decode(Some(&v)); + // Over 3..4 blocks from the template's origin along y, 0 to 1. + let rule = decode( + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "axis": "y", "min_chance": 0, "max_chance": 1, "min_dist": 3, "max_dist": 4}), + ) + .unwrap(); + let mut random = LegacyRandom::new(1); + let world = [100, 64, -100]; + // At or under min_dist the chance is 0, a roll of 0 aside; past max_dist it is 1. + assert!(!rule.test([9, 2, 9], world, world, &mut random)); + assert!(rule.test([0, -5, 0], world, world, &mut random)); + // The world position and the piece's do not count. + assert!(rule.test([0, 4, 0], [0, 0, 0], [50, 50, 50], &mut random)); + // Repurposed refuses an empty distance range and an unknown axis. + for bad in [ + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos"}), + json!({"predicate_type": "horizon:piece_origin_axis_aligned_linear_pos", + "min_dist": 0, "max_dist": 1, "axis": "w"}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5, "max_y_value": 4}), + json!({"predicate_type": "horizon:y_value", "min_y_value": 5}), + ] { + assert!(decode(bad.clone()).is_err(), "{bad}"); + } + let y = decode( + json!({"predicate_type": "horizon:y_value", "min_y_value": 0, "max_y_value": 31}), + ) + .unwrap(); + assert!(y.test([0; 3], [7, 31, 7], [0; 3], &mut random)); + assert!(y.test([0, 99, 0], [7, 0, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, 32, 7], [0; 3], &mut random)); + assert!(!y.test([0; 3], [7, -1, 7], [0; 3], &mut random)); + } + + #[test] + fn rule_parts_read_ids_without_a_namespace() { + // CTOV writes "always_true"; vanilla reads it as minecraft:always_true. + for kind in ["always_true", "minecraft:always_true"] { + let p = json!({"predicate_type": kind}); + assert!( + matches!(PosRule::decode(Some(&p)), Ok(PosRule::Always)), + "{kind}" + ); + } + let linear = json!({"predicate_type": "axis_aligned_linear_pos", "axis": "z", + "min_chance": 0.1, "max_dist": 8}); + assert!(matches!( + PosRule::decode(Some(&linear)), + Ok(PosRule::Linear { + axis: Some(2), + max_dist: 8, + .. + }) + )); + assert!(PosRule::decode(Some(&json!({"predicate_type": "x:unknown"}))).is_err()); + assert!(matches!(PosRule::decode(None), Ok(PosRule::Always))); + let loot = json!({"type": "append_loot", "loot_table": "minecraft:chests/x"}); + assert!( + matches!(Modifier::decode(Some(&loot)), Ok(Modifier::AppendLoot(t)) if t == "minecraft:chests/x") + ); + assert!(matches!( + Modifier::decode(Some(&json!({"type": "clear"}))), + Ok(Modifier::Clear) + )); + assert!(Modifier::decode(Some(&json!({"type": ""}))).is_err()); + } + + #[test] + fn block_entity_edits_merge_deep_and_drop_keys() { + let nbt = |v: Value| match json_to_nbt(&v) { + Tag::Compound(c) => c, + _ => unreachable!(), + }; + let vault = nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:old", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})); + // append_static merges compounds the way CompoundTag.merge does. + let Ok(Modifier::AppendStatic(data)) = Modifier::decode(Some(&json!({ + "type": "append_static", "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("append_static") + }; + let merged = edited(Some(&vault), &[], &data); + assert_eq!( + merged, + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}, + "server_data": {"state_updating_resumes_at": 533162741}})) + ); + let Ok(Modifier::Edit { remove, data }) = Modifier::decode(Some(&json!({ + "type": "horizon:edit", "remove": ["server_data"], + "data": {"config": {"loot_table": "x:new"}}}))) + else { + panic!("horizon:edit") + }; + assert_eq!( + edited(Some(&vault), &remove, &data), + nbt(json!({"id": "minecraft:vault", + "config": {"loot_table": "x:new", "key_item": {"id": "minecraft:trial_key"}}})) + ); + assert_eq!( + edited(None, &remove, &data), + nbt(json!({"config": {"loot_table": "x:new"}})) + ); + let bad = json!({"type": "horizon:edit", "remove": [1], "data": {}}); + assert!(Modifier::decode(Some(&bad)).is_err()); + } + + /// Scripted draws: floats in turn, then ints. + struct Draws(Vec<f32>, Vec<i32>); + impl ProcessorRandom for Draws { + fn float(&mut self) -> f32 { + self.0.remove(0) + } + fn int(&mut self, bound: i32) -> i32 { + let i = self.1.remove(0); + assert!(i < bound); + i + } + fn long(&mut self) -> i64 { + unreachable!() + } + } + + #[test] + fn picks_follow_yungs_cascade() { + // States by name: sand 1, sandstone 2, the four stairs 10..13. + let id = |v: &Value| { + Ok(BlockStateId(match v["Name"].as_str() { + Some("minecraft:sand") => 1, + Some("minecraft:sandstone") => 2, + Some("minecraft:suspicious_sand") => 3, + _ => { + 10 + ["north", "east", "south", "west"] + .iter() + .position(|f| v["Properties"]["facing"] == *f) + .unwrap_or(9) as u32 + } + })) + }; + let stairs: Vec<Value> = ["north", "east", "south", "west"] + .iter() + .map(|f| json!({"Name": "minecraft:sandstone_stairs", "Properties": {"facing": f}})) + .collect(); + let pick = Pick::decode( + &json!({"block": "red_stained_glass", "picks": [ + {"below": 0.01, "state": {"Name": "minecraft:suspicious_sand"}, + "nbt": {"LootTable": "minecraft:archaeology/desert_pyramid"}}, + {"below": 0.3, "state": {"Name": "minecraft:sand"}}, + {"below": 0.75, "state": {"Name": "minecraft:sandstone"}}], + "default": {"states": stairs}}), + id, + ) + .unwrap(); + assert_eq!(pick.block, "minecraft:red_stained_glass"); + let glass = || BlockInfo { + pos: [1, 2, 3], + state: BlockStateId(0), + nbt: Some(Compound::new()), + }; + let run = |f: f32, i: Vec<i32>| pick.apply(glass(), &mut Draws(vec![f], i)); + let sus = run(0.005, vec![]); + assert_eq!(sus.state, BlockStateId(3)); + assert!( + sus.nbt + .unwrap() + .contains_key(&JavaString::from("LootTable")) + ); + assert_eq!(run(0.01, vec![]).state, BlockStateId(1)); + assert_eq!(run(0.2999, vec![]).nbt, Some(Compound::new())); + assert_eq!(run(0.3, vec![]).state, BlockStateId(2)); + // The stairs' facing: Plane.HORIZONTAL[nextInt(4)] after the pick. + assert_eq!(run(0.75, vec![2]).state, BlockStateId(12)); + assert_eq!(run(0.99, vec![1]).state, BlockStateId(11)); + + let pot = Pick::decode( + &json!({"block": "minecraft:decorated_pot", "default": { + "state": {"Name": "minecraft:sand"}, + "lists": [{"key": "sherds", "count": 4, "default": "minecraft:brick", + "values": [{"below": 0.05, "value": "minecraft:archer_pottery_sherd"}, + {"below": 0.1, "value": "minecraft:miner_pottery_sherd"}]}]}}), + id, + ) + .unwrap(); + // No picks: no float for them; one float per sherd. + let out = pot.apply( + BlockInfo { + nbt: None, + ..glass() + }, + &mut Draws(vec![0.5, 0.01, 0.07, 0.1], vec![]), + ); + let Some(Tag::List(sherds)) = out.nbt.unwrap().get(&JavaString::from("sherds")).cloned() + else { + panic!("sherds") + }; + let names: Vec<String> = sherds + .iter() + .map(|t| match t { + Tag::String(s) => s.to_string_lossy(), + _ => String::new(), + }) + .collect(); + assert_eq!( + names, + [ + "minecraft:brick", + "minecraft:archer_pottery_sherd", + "minecraft:miner_pottery_sherd", + "minecraft:brick" + ] + ); + assert!(Pick::decode(&json!({"block": "a", "default": {"states": []}}), id).is_err()); + } + + #[test] + fn count_caps_keep_the_first_then_some() { + let cap = CountCap::decode( + &json!({"blocks": ["chest", "minecraft:trapped_chest"], "min": 1, "max": 2, + "chance": 0.2, "replacement": {"id": "minecraft:cave_air"}}), + |_| Ok(BlockStateId(5)), + ) + .unwrap(); + assert!(cap.blocks.contains("minecraft:chest")); + let mut counted = 0; + // The first stays without a roll. + assert!(cap.keeps(&mut counted, || unreachable!())); + // Then each stays on nextFloat <= 0.2, until two have. + assert!(!cap.keeps(&mut counted, || 0.21)); + assert!(cap.keeps(&mut counted, || 0.2)); + assert!(!cap.keeps(&mut counted, || unreachable!())); + assert_eq!(counted, 2); + assert!( + CountCap::decode(&json!({"blocks": [], "min": -1}), |_| Ok(BlockStateId(5))).is_err() + ); + } + + #[test] + fn block_swaps_keep_the_properties_both_blocks_have() { + let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]); + let facts = json!({"defaults": {"a:log": 1, "a:stairs": 4, "a:stone": 6}, + "states": [ + row("a:log", json!({"axis": "x"})), row("a:log", json!({"axis": "y"})), + row("a:stairs", json!({"facing": "east", "half": "top"})), + row("a:stairs", json!({"facing": "east", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "bottom"})), + row("a:stairs", json!({"facing": "north", "half": "top"})), + ["a:stone", false, false, "", "a:stone"]]}); + let registry = + crate::registry::BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap(); + // facing and half carried over; the default where `from` has none. + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(2)), + Some(BlockStateId(2)) + ); + assert_eq!( + with_properties_of(®istry, "a:stairs", BlockStateId(0)), + Some(BlockStateId(4)) + ); + assert_eq!( + with_properties_of(®istry, "a:stone", BlockStateId(5)), + Some(BlockStateId(6)) + ); + assert_eq!( + with_properties_of(®istry, "a:missing", BlockStateId(0)), + None + ); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor/lithostitched.rs b/crates/horizon-world/src/worldgen/structure/processor/lithostitched.rs new file mode 100644 index 000000000..f0bb1c6ba --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/processor/lithostitched.rs @@ -0,0 +1,434 @@ +//! Lithostitched's processors that pick processors, carried as data +//! (`horizon:apply_random` and `horizon:condition`): one runs a processor +//! list drawn by weight, the other one list or another by a test of the +//! block. Both draw from Lithostitched's RandomSettings: a random seeded from +//! the world seed and a name, at the block, the piece or the structure. +//! `horizon:set_block` is its `set_block`, which the conditions mostly run. +use super::{Processor, ProcessorList}; +use crate::{ + registry::{BlockRegistry, BlockStateId}, + worldgen::{DecodeError, block_feature::FeatureBlockBindings, structure::StructureResources}, +}; +use horizon_core::{ + position::BlockPos, + random::{LegacyRandom, PositionalRandom, RandomSource}, +}; +use serde_json::Value; +use std::{collections::BTreeSet, sync::Arc}; + +/// RandomSettings: where the random is taken, and the name salting it. +#[derive(Clone, Debug, PartialEq)] +pub struct RandomSettings { + mode: Mode, + /// ResourceLocation.hashCode of the name (`lithostitched:default`). + salt: i32, +} +#[derive(Clone, Copy, Debug, PartialEq)] +enum Mode { + Block, + Piece, + Structure, +} +impl RandomSettings { + /// A mode alone, or `{"mode": ..., "name": ...}`; per block when unset. + fn decode(v: Option<&Value>) -> Result<Self, DecodeError> { + let mode = Mode::decode; + let (mode, name) = match v { + None => (Mode::Block, "lithostitched:default"), + Some(Value::String(m)) => (mode(Some(m))?, "lithostitched:default"), + Some(o) => ( + mode(o["mode"].as_str())?, + o["name"] + .as_str() + .ok_or(DecodeError::Field("random name"))?, + ), + }; + let (namespace, path) = name.split_once(':').unwrap_or(("minecraft", name)); + Ok(Self { + mode, + salt: java_hash(namespace) + .wrapping_mul(31) + .wrapping_add(java_hash(path)), + }) + } + /// RandomSource.create(seed + hash).forkPositional().at(the chosen + /// position): the piece's position, the structure's pivot or the block. + pub(super) fn create( + &self, + seed: i64, + piece: [i32; 3], + pivot: [i32; 3], + block: [i32; 3], + ) -> LegacyRandom { + let [x, y, z] = self.mode.select(piece, pivot, block); + LegacyRandom::new(seed.wrapping_add(i64::from(self.salt))) + .fork_positional() + .at(BlockPos::new(x, y, z)) + } +} +impl Mode { + fn decode(m: Option<&str>) -> Result<Self, DecodeError> { + match m { + None | Some("per_block") => Ok(Self::Block), + Some("per_piece") => Ok(Self::Piece), + Some("per_structure") => Ok(Self::Structure), + _ => Err(DecodeError::Field("random mode")), + } + } + fn select(self, piece: [i32; 3], pivot: [i32; 3], block: [i32; 3]) -> [i32; 3] { + match self { + Self::Block => block, + Self::Piece => piece, + Self::Structure => pivot, + } + } +} + +/// SetBlockProcessor with a simple or weighted state provider and no block +/// entity change: the block becomes the state, keeping the properties it +/// shares with the old one unless `preserve_state` is off. +#[derive(Clone, Debug)] +pub struct SetBlock { + /// The states and their weights; one state alone is a simple provider, + /// which draws nothing. + states: Vec<(BlockStateId, i32)>, + weighted: bool, + preserve: bool, + mode: Mode, +} +impl SetBlock { + pub(super) fn decode( + v: &Value, + state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>, + ) -> Result<Self, DecodeError> { + let provider = &v["state_provider"]; + let (states, weighted) = match provider["type"].as_str() { + Some("minecraft:simple_state_provider") => { + (vec![(state(&provider["state"])?, 1)], false) + } + Some("minecraft:weighted_state_provider") => ( + provider["entries"] + .as_array() + .ok_or(DecodeError::Field("set_block entries"))? + .iter() + .map(|e| { + let weight = e["weight"] + .as_i64() + .ok_or(DecodeError::Field("set_block weight"))?; + Ok((state(&e["data"])?, weight as i32)) + }) + .collect::<Result<_, DecodeError>>()?, + true, + ), + _ => return Err(DecodeError::Field("set_block state_provider")), + }; + if states.is_empty() { + return Err(DecodeError::Field("set_block entries")); + } + Ok(Self { + states, + weighted, + preserve: v["preserve_state"].as_bool().unwrap_or(true), + mode: Mode::decode(v["random_mode"].as_str())?, + }) + } + /// The state to set, before `preserve`: drawn with + /// RandomSource.create(seed).forkPositional().at(the chosen position). + pub(super) fn state( + &self, + seed: i64, + piece: [i32; 3], + pivot: [i32; 3], + block: [i32; 3], + ) -> BlockStateId { + if !self.weighted { + return self.states[0].0; + } + let [x, y, z] = self.mode.select(piece, pivot, block); + let mut random = LegacyRandom::new(seed) + .fork_positional() + .at(BlockPos::new(x, y, z)); + let total: i32 = self.states.iter().map(|s| s.1).sum(); + let mut value = random.next_int_bound(total.max(1)).unwrap_or(0); + for (state, weight) in &self.states { + if value < *weight { + return *state; + } + value -= weight; + } + self.states[0].0 + } + pub(super) fn preserves(&self) -> bool { + self.preserve + } +} + +/// String.hashCode over UTF-16 units. +fn java_hash(s: &str) -> i32 { + s.encode_utf16() + .fold(0i32, |h, c| h.wrapping_mul(31).wrapping_add(i32::from(c))) +} + +fn list( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, +) -> Result<ProcessorList, DecodeError> { + ProcessorList::decode(&v.to_string(), resources, bindings) +} + +/// ApplyRandomStructureProcessor: a weighted list of processor lists, one +/// drawn per block with `nextInt(total)`. +#[derive(Clone, Debug)] +pub struct ApplyRandom { + pub(super) random: RandomSettings, + lists: Vec<(ProcessorList, i32)>, + total: i32, +} +impl ApplyRandom { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result<Self, DecodeError> { + let lists = v["processor_lists"] + .as_array() + .ok_or(DecodeError::Field("apply_random processor_lists"))? + .iter() + .map(|e| { + let weight = e["weight"] + .as_i64() + .ok_or(DecodeError::Field("apply_random weight"))?; + Ok((list(&e["data"], resources, bindings)?, weight as i32)) + }) + .collect::<Result<Vec<_>, DecodeError>>()?; + Ok(Self { + random: RandomSettings::decode(v.get("mode"))?, + total: lists.iter().map(|l| l.1).sum(), + lists, + }) + } + /// WeightedList.getRandom: none when the weights add up to 0. + pub(super) fn pick(&self, random: &mut impl RandomSource) -> Option<&ProcessorList> { + if self.total <= 0 { + return None; + } + let mut value = random.next_int_bound(self.total).unwrap_or(0); + for (list, weight) in &self.lists { + if value < *weight { + return Some(list); + } + value -= weight; + } + None + } +} + +/// ConditionProcessor: `then` when the condition holds for the block, else +/// `else`. +#[derive(Clone, Debug)] +pub struct Conditional { + pub(super) random: RandomSettings, + pub(super) condition: Condition, + pub(super) then: ProcessorList, + pub(super) otherwise: ProcessorList, +} +impl Conditional { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result<Self, DecodeError> { + // A processor alone or a list of them. + let processors = |key: &str| -> Result<ProcessorList, DecodeError> { + match v.get(key) { + None => Ok(ProcessorList::default()), + Some(Value::Object(p)) if p.contains_key("processor_type") => Ok(ProcessorList( + vec![Processor::decode(&v[key], resources, bindings)?], + )), + Some(other) => list(other, resources, bindings), + } + }; + Ok(Self { + random: RandomSettings::decode(v.get("random_mode"))?, + condition: Condition::decode(&v["if_true"], bindings)?, + then: processors("then")?, + otherwise: processors("else")?, + }) + } +} + +/// Lithostitched's processor conditions the game runs. +#[derive(Clone, Debug)] +pub(super) enum Condition { + True, + AllOf(Vec<Condition>), + AnyOf(Vec<Condition>), + Not(Box<Condition>), + RandomChance(f32), + /// The block placed (`input`) or the one in the world (`location`) is + /// one of these, with these property values. + MatchingBlocks { + blocks: Arc<BTreeSet<BlockStateId>>, + properties: Vec<(String, String)>, + location: bool, + }, +} +impl Condition { + fn decode(v: &Value, bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> { + let all = |a: &Value| -> Result<Vec<Condition>, DecodeError> { + a.as_array() + .ok_or(DecodeError::Field("processor conditions"))? + .iter() + .map(|c| Self::decode(c, bindings)) + .collect() + }; + if v.is_array() { + return Ok(Self::AllOf(all(v)?)); + } + let kind = v["type"].as_str().unwrap_or_default(); + Ok(match kind.strip_prefix("lithostitched:").unwrap_or(kind) { + "true" => Self::True, + "all_of" => Self::AllOf(all(&v["conditions"])?), + "any_of" => Self::AnyOf(all(&v["conditions"])?), + "not" => Self::Not(Box::new(Self::decode(&v["condition"], bindings)?)), + "random_chance" => Self::RandomChance(super::float(v, "chance")?), + "matching_blocks" => Self::MatchingBlocks { + blocks: super::holder_set(&v["blocks"], bindings)?, + properties: match v.get("properties") { + None => Vec::new(), + Some(p) => p + .as_object() + .ok_or(DecodeError::Field("matching_blocks properties"))? + .iter() + .map(|(k, x)| { + let x = x + .as_str() + .ok_or(DecodeError::Field("matching_blocks property"))?; + Ok((k.clone(), x.to_owned())) + }) + .collect::<Result<_, DecodeError>>()?, + }, + location: match v["match_type"].as_str() { + None | Some("input") => false, + Some("location") => true, + _ => return Err(DecodeError::Field("matching_blocks match_type")), + }, + }, + _ => return Err(DecodeError::Field("processor condition type")), + }) + } + /// ProcessorCondition.test with the block placed and the one there. + pub(super) fn test( + &self, + input: BlockStateId, + location: BlockStateId, + registry: &BlockRegistry, + random: &mut impl RandomSource, + ) -> bool { + match self { + Self::True => true, + Self::AllOf(all) => all + .iter() + .all(|c| c.test(input, location, registry, random)), + Self::AnyOf(any) => any + .iter() + .any(|c| c.test(input, location, registry, random)), + Self::Not(c) => !c.test(input, location, registry, random), + Self::RandomChance(chance) => random.next_float() < *chance, + Self::MatchingBlocks { + blocks, + properties, + location: at_location, + } => { + let state = if *at_location { location } else { input }; + blocks.contains(&state) + && properties.iter().all(|(k, x)| { + registry + .state(state) + .and_then(|s| s.properties.get(k)) + .is_some_and(|v| v == x) + }) + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn random_settings_salt_and_position() { + // ResourceLocation.hashCode: 31 * namespace + path. + let default = RandomSettings::decode(Some(&"per_piece".into())).unwrap(); + assert_eq!( + default.salt, + java_hash("lithostitched") + .wrapping_mul(31) + .wrapping_add(java_hash("default")) + ); + assert_eq!(java_hash("default"), 1544803905); + let (seed, piece, pivot, block) = (12345, [16, 64, -32], [8, 70, 8], [17, 65, -30]); + let mut ours = default.create(seed, piece, pivot, block); + let mut theirs = LegacyRandom::new(seed + i64::from(default.salt)) + .fork_positional() + .at(BlockPos::new(16, 64, -32)); + assert_eq!(ours.next_long(), theirs.next_long()); + let named: Value = serde_json::json!({"mode": "per_structure", "name": "v:roof"}); + let named = RandomSettings::decode(Some(&named)).unwrap(); + assert_eq!(named.mode, Mode::Structure); + assert_eq!( + named.salt, + java_hash("v") + .wrapping_mul(31) + .wrapping_add(java_hash("roof")) + ); + } + + #[test] + fn apply_random_draws_by_weight() { + let apply = ApplyRandom { + random: RandomSettings { + mode: Mode::Block, + salt: 0, + }, + lists: vec![ + (ProcessorList(vec![Processor::Nop]), 3), + (ProcessorList::default(), 1), + ], + total: 4, + }; + let mut ours = LegacyRandom::new(9); + let mut theirs = LegacyRandom::new(9); + for _ in 0..32 { + let draw = theirs.next_int_bound(4).unwrap(); + let picked = apply.pick(&mut ours).unwrap(); + assert_eq!(picked.0.len(), usize::from(draw < 3)); + } + } + + #[test] + fn set_block_draws_from_the_unsalted_seed() { + let (a, b) = (BlockStateId(1), BlockStateId(2)); + let set = SetBlock::decode( + &serde_json::json!({"state_provider": {"type": "minecraft:weighted_state_provider", + "entries": [{"weight": 1, "data": 1}, {"weight": 2, "data": 2}]}, + "random_mode": "per_piece"}), + |v| Ok(BlockStateId(v.as_u64().unwrap() as u32)), + ) + .unwrap(); + assert!(set.preserves()); + for x in 0..16 { + let mut java = LegacyRandom::new(77) + .fork_positional() + .at(BlockPos::new(x, 5, 3)); + let want = if java.next_int_bound(3).unwrap() < 1 { + a + } else { + b + }; + assert_eq!(set.state(77, [x, 5, 3], [0; 3], [9, 9, 9]), want); + } + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index a66f27509..dfb8176e0 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -57,6 +57,11 @@ pub struct JigsawDef { waterlogging: bool, /// A carried mod's start rules (`"horizon:start_checks"`). checks: super::start_checks::StartChecks, + /// Laid out by YUNG's API's assembler (`"horizon:yungsapi"`). + yung: Option<super::yung::Config>, + /// Laid out by Repurposed Structures' and Moog's piece-limited + /// assembler (`"horizon:piece_limited"`). + piece_limited: Option<super::piece_limited::Config>, } #[derive(Debug)] pub enum StructureKind { @@ -97,6 +102,9 @@ pub struct StructureDef { pub biomes: BTreeSet<BiomeId>, pub step: usize, pub terrain: TerrainAdjustment, + /// Another loaded structure turns this one's type off + /// (`"horizon:disables"`): it never starts. + pub disabled: bool, } #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Reduction { @@ -137,6 +145,107 @@ pub struct StructureSet { /// (`"horizon:exclusion_zone"`: `other_sets`, `chunk_count`). min_distance: Option<i64>, avoid: Option<(Vec<String>, i32)>, + /// `"horizon:ring_sections"`: starts only in odd rings around the origin. + rings: Option<RingSections>, + /// `"horizon:avoid_biomes"`: no start with one of these biomes near. + avoid_biomes: Option<AvoidBiomes>, +} + +/// YUNG's Better Strongholds' placement (BetterStrongholdsPlacement +/// .isPlacementChunk): the world is cut into rings `thickness` chunks wide, +/// the first one starting `distance_to_first_ring` chunks out; a start is +/// placed only in the odd ones, and in none past `max_section`. +/// +/// ```json +/// "horizon:ring_sections": {"distance_to_first_ring": 80, "thickness": 96, "max_section": 5} +/// ``` +#[derive(Debug, Clone, PartialEq, Eq)] +struct RingSections { + first: i32, + thickness: i32, + max: Option<i32>, +} +impl RingSections { + fn decode(v: &Value) -> Self { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + first: int("distance_to_first_ring").unwrap_or(0), + thickness: int("thickness").unwrap_or(1).max(1), + max: int("max_section"), + } + } + fn allows(&self, x: i32, z: i32) -> bool { + // Java int arithmetic: the squares wrap past 46,340 chunks, and the + // square root of a negative int is NaN, which casts to 0. + let squared = x.wrapping_mul(x).wrapping_add(z.wrapping_mul(z)); + let distance = f64::from(squared).sqrt() as i32; + let section = distance.wrapping_add(self.thickness - self.first) / self.thickness; + !self.max.is_some_and(|max| section > max) && section % 2 == 1 + } +} + +/// YUNG's Better Desert and Jungle Temples' placement: no start when a +/// biome of the set is found around the chunk's middle block at height `y` +/// (BiomeSource.findBiomeHorizontal with `radius` blocks and `step` quarts +/// between samples, closest first). +/// +/// ```json +/// "horizon:avoid_biomes": {"biomes": ["#minecraft:is_river", "#minecraft:is_ocean"], +/// "radius": 48, "step": 2, "y": 120} +/// ``` +#[derive(Debug)] +struct AvoidBiomes { + biomes: BTreeSet<BiomeId>, + radius: i32, + step: i32, + y: i32, +} +impl AvoidBiomes { + fn decode( + v: &Value, + biome_set: &dyn Fn(&Value) -> Result<BTreeSet<BiomeId>, DecodeError>, + ) -> Result<Self, DecodeError> { + let mut biomes = BTreeSet::new(); + match &v["biomes"] { + Value::Array(list) => { + for entry in list { + biomes.extend(biome_set(entry)?); + } + } + other => biomes = biome_set(other)?, + } + let int = |k: &str, default: i32| v[k].as_i64().map_or(default, |n| n as i32); + Ok(Self { + biomes, + radius: int("radius", 0), + step: int("step", 1).max(1), + y: int("y", 0), + }) + } + fn near(&self, chunk: ChunkPos, mut biome: impl FnMut([i32; 3]) -> BiomeId) -> bool { + // ChunkPos.getMiddleBlockPosition, then QuartPos.fromBlock. + let (cx, cz) = ((chunk.x * 16 + 8) >> 2, (chunk.z * 16 + 8) >> 2); + let (radius, y) = (self.radius >> 2, self.y >> 2); + let mut r = 0; + while r <= radius { + let mut dz = -r; + while dz <= r { + let z_edge = dz.abs() == r; + let mut dx = -r; + while dx <= r { + if (z_edge || dx.abs() == r) + && self.biomes.contains(&biome([cx + dx, y, cz + dz])) + { + return true; + } + dx += self.step; + } + dz += self.step; + } + r += self.step; + } + false + } } fn heightmap(name: &str) -> Option<HeightmapType> { @@ -182,8 +291,19 @@ impl StructureRegistry { biome_set: &dyn Fn(&Value) -> Result<BTreeSet<BiomeId>, DecodeError>, ) -> Result<Self, DecodeError> { let mut defs = Vec::new(); + let (mut types, mut disables) = (Vec::new(), BTreeSet::new()); for (name, json) in structures { let v: Value = serde_json::from_str(json)?; + types.push(v["type"].as_str().unwrap_or_default().to_owned()); + // YUNG's mods turn their vanilla counterparts off (the + // DisableVanilla*Mixin on ChunkGenerator.tryGenerateStructure). + disables.extend( + v["horizon:disables"] + .as_array() + .into_iter() + .flatten() + .filter_map(|t| Some(t.as_str()?.to_owned())), + ); let kind = match v["type"].as_str().unwrap_or_default() { "minecraft:jigsaw" => StructureKind::Jigsaw(JigsawDef { start_pool: v["start_pool"].as_str().unwrap_or_default().to_owned(), @@ -202,6 +322,10 @@ impl StructureRegistry { 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")), + yung: v.get("horizon:yungsapi").map(super::yung::Config::decode), + piece_limited: v + .get("horizon:piece_limited") + .map(super::piece_limited::Config::decode), }), "minecraft:buried_treasure" => StructureKind::BuriedTreasure, "minecraft:igloo" => StructureKind::Igloo, @@ -251,8 +375,12 @@ impl StructureRegistry { .position(|s| Some(*s) == v["step"].as_str()) .unwrap_or(4), terrain: terrain(v["terrain_adaptation"].as_str()), + disabled: false, }); } + for (def, kind) in defs.iter_mut().zip(&types) { + def.disabled = disables.contains(kind); + } let index = |name: &str| defs.iter().position(|d| d.name == name); let mut out = Vec::new(); for (name, json) in sets { @@ -314,6 +442,11 @@ impl StructureRegistry { z["chunk_count"].as_i64().unwrap_or(0) as i32, ) }), + rings: p.get("horizon:ring_sections").map(RingSections::decode), + avoid_biomes: p + .get("horizon:avoid_biomes") + .map(|a| AvoidBiomes::decode(a, biome_set)) + .transpose()?, }); } Ok(Self { @@ -420,6 +553,9 @@ impl StructureRegistry { if !placed { return false; } + if set.rings.as_ref().is_some_and(|r| !r.allows(x, z)) { + 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); @@ -571,6 +707,10 @@ pub trait StartContext: JigsawContext { fn generation(&self) -> WorldGenerationContext; /// Noise biome at a quart position (caching resolver, no zoom). fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId; + /// Noise biomes of `quarts` in order through one resolver, as + /// BiomeSource.findBiomeHorizontal samples: each climate lookup starts + /// from the previous result, which a tie keeps. + fn noise_biomes(&mut self, quarts: &[[i32; 3]]) -> Vec<BiomeId>; fn set_valid_biomes(&mut self, biomes: &BTreeSet<BiomeId>); } @@ -591,6 +731,16 @@ pub fn create_starts( if !registry.is_structure_chunk(set, seed, chunk.x, chunk.z, rings) { continue; } + // Part of the set's placement in YUNG's mods; checked here, where the + // biome source is at hand, so another set's exclusion zone naming + // this one does not see it. + if set + .avoid_biomes + .as_ref() + .is_some_and(|a| a.near(chunk, |q| context.noise_biome(q))) + { + continue; + } if set.structures.len() == 1 { if let Some(start) = try_generate( registry, @@ -640,6 +790,9 @@ fn try_generate( chunk: ChunkPos, ) -> Option<StructureStart> { let def = ®istry.structures[structure]; + if def.disabled { + return None; + } context.set_valid_biomes(&def.biomes); let seed = context.seed(); let mut random = WorldgenRandom::new(LegacyRandom::new(0)); @@ -669,16 +822,40 @@ fn try_generate( padding: jigsaw.padding, waterlogging: jigsaw.waterlogging, }; - let (position, mut pieces) = assemble( - &config, - context, - ®istry.pools, - resources, - bindings, - &mut random, - start, - )?; - if jigsaw.max_depth <= 0 { + let (position, mut pieces) = match (&jigsaw.yung, &jigsaw.piece_limited) { + (_, Some(limits)) => super::piece_limited::assemble( + &config, + limits, + context, + ®istry.pools, + resources, + bindings, + chunk, + start, + )?, + (Some(yung), None) => super::yung::assemble( + &config, + yung, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + (None, None) => assemble( + &config, + context, + ®istry.pools, + resources, + bindings, + &mut random, + start, + )?, + }; + // Vanilla's JigsawPlacement keeps no piece at size 0; the + // piece-limited assembler keeps the start piece. + if jigsaw.max_depth <= 0 && jigsaw.piece_limited.is_none() { pieces.clear(); } ( @@ -1114,3 +1291,106 @@ pub fn place_in_chunk<W: FeatureWorld + PlacementContext, R: RandomSource + 'sta } Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn registry(structures: &[(&str, Value)], sets: &[(&str, Value)]) -> StructureRegistry { + let text = |l: &[(&str, Value)]| { + l.iter() + .map(|(k, v)| ((*k).to_owned(), v.to_string())) + .collect::<BTreeMap<_, _>>() + }; + // Biome tags: `#t:one` is biome 1, `#t:two` biome 2. + StructureRegistry::new(&text(structures), &text(sets), BTreeMap::new(), &|v| { + Ok(match v.as_str() { + Some("#t:one") => BTreeSet::from([BiomeId(1)]), + Some("#t:two") => BTreeSet::from([BiomeId(2)]), + _ => BTreeSet::new(), + }) + }) + .unwrap() + } + + #[test] + fn a_structure_turns_its_vanilla_counterpart_off() { + let r = registry( + &[ + ( + "minecraft:pyramid", + json!({"type": "minecraft:desert_pyramid"}), + ), + ("minecraft:igloo", json!({"type": "minecraft:igloo"})), + ( + "yung:temple", + json!({"type": "minecraft:swamp_hut", "horizon:disables": ["minecraft:desert_pyramid"]}), + ), + ], + &[], + ); + let disabled: Vec<_> = r + .structures + .iter() + .map(|d| (d.name.as_str(), d.disabled)) + .collect(); + assert_eq!( + disabled, + [ + ("minecraft:igloo", false), + ("minecraft:pyramid", true), + ("yung:temple", false) + ] + ); + } + + #[test] + fn ring_sections_keep_the_odd_rings() { + let rings = RingSections::decode( + &json!({"distance_to_first_ring": 80, "thickness": 96, "max_section": 3}), + ); + // (d + 16) / 96: 0 inside 80 chunks, 1 to 175, 2 to 271, 3 to 367. + assert!(!rings.allows(79, 0)); + assert!(rings.allows(80, 0)); + assert!(rings.allows(0, -175)); + assert!(!rings.allows(176, 0)); + assert!(rings.allows(272, 0)); + assert!(!rings.allows(464, 0), "section 5 is past max_section 3"); + // Java's int square wraps: 50,000² + 0 is negative, its root NaN, 0. + assert!(!rings.allows(50_000, 0)); + let open = RingSections::decode(&json!({"distance_to_first_ring": 80, "thickness": 96})); + assert!(open.allows(464, 0)); + } + + #[test] + fn avoid_biomes_samples_around_the_middle_block() { + let r = registry( + &[], + &[( + "yung:temples", + json!({"structures": [], "placement": {"type": "minecraft:random_spread", + "spacing": 24, "separation": 8, "salt": 1, + "horizon:avoid_biomes": {"biomes": ["#t:one", "#t:two"], + "radius": 48, "step": 2, "y": 120}}}), + )], + ); + let avoid = r.sets[0].avoid_biomes.as_ref().unwrap(); + assert_eq!(avoid.biomes, BTreeSet::from([BiomeId(1), BiomeId(2)])); + // Chunk (1, -1): middle block (24, 120, -8), quart (6, 30, -2). + let mut asked = Vec::new(); + assert!(!avoid.near(ChunkPos::new(1, -1), |q| { + asked.push(q); + BiomeId(0) + })); + assert_eq!(asked[0], [6, 30, -2]); + // Every even offset within 12 quarts, once: 13 x 13. + assert_eq!(asked.len(), 169); + assert!(asked.contains(&[6 - 12, 30, -2 + 12])); + assert!(!asked.contains(&[7, 30, -2])); + // An ocean on the edge of the square is found. + assert!(avoid.near(ChunkPos::new(1, -1), |q| { + BiomeId(if q == [18, 30, 10] { 2 } else { 0 }) + })); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start_checks.rs b/crates/horizon-world/src/worldgen/structure/start_checks.rs index 45b991531..f182706a8 100644 --- a/crates/horizon-world/src/worldgen/structure/start_checks.rs +++ b/crates/horizon-world/src/worldgen/structure/start_checks.rs @@ -15,9 +15,15 @@ //! "terrain_radius": 1, // chunks, with terrain_range and/or min_y, max_y //! "terrain_range": 15, //! "min_y": 60, -//! "max_y": 200 +//! "max_y": 200, +//! "repurposed": "city_nether" // or "shipwreck_nether", "stronghold_end": below //! } //! ``` +//! +//! `repurposed` is the extra check of one of Repurposed Structures' jigsaw +//! types, after the others: its Nether city needs open air above the lava sea +//! in the chunks around, its Nether shipwreck open air or lava around the +//! start, and its End stronghold land around the chunk. use crate::{heightmap::HeightmapType, worldgen::biome::BiomeId}; use horizon_core::position::ChunkPos; use serde_json::Value; @@ -33,6 +39,20 @@ pub enum LiquidCheck { Lowest, } +/// The extra start check of a Repurposed Structures jigsaw type. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Repurposed { + /// CityNetherStructure: air from sea level + 20 to + 45 (or the top of + /// the noise) at the corner of each of the 8 chunks around. + CityNether, + /// ShipwreckNetherStructure: no solid block at 5×5 columns 8 apart + /// around the chunk corner, from the start height up 30 in steps of 5. + ShipwreckNether, + /// StrongholdEndStructure: land at least 45 above the bottom 35 and 70 + /// blocks away in each direction and at the chunk corner. + StrongholdEnd, +} + /// The checks of one structure; all empty for vanilla's. #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct StartChecks { @@ -42,6 +62,7 @@ pub struct StartChecks { terrain_range: Option<i32>, min_y: Option<i32>, max_y: Option<i32>, + repurposed: Option<Repurposed>, } /// The column and biome queries the checks need. @@ -53,6 +74,9 @@ pub trait CheckQueries { /// and does not block motion is a liquid. fn liquid_column(&mut self, x: i32, z: i32) -> (Vec<bool>, Vec<bool>); fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId; + fn sea_level(&self) -> i32; + /// The noise's bottom, where the columns start. + fn bottom(&self) -> i32; } impl<T: super::start::StartContext> CheckQueries for T { @@ -71,6 +95,12 @@ impl<T: super::start::StartContext> CheckQueries for T { fn noise_biome(&mut self, quart: [i32; 3]) -> BiomeId { super::start::StartContext::noise_biome(self, quart) } + fn sea_level(&self) -> i32 { + super::start::StartContext::sea_level(self) + } + fn bottom(&self) -> i32 { + self.min_y() + } } impl StartChecks { @@ -91,6 +121,12 @@ impl StartChecks { terrain_range: int("terrain_range"), min_y: int("min_y"), max_y: int("max_y"), + repurposed: match v.get("repurposed").and_then(Value::as_str) { + Some("city_nether") => Some(Repurposed::CityNether), + Some("shipwreck_nether") => Some(Repurposed::ShipwreckNether), + Some("stronghold_end") => Some(Repurposed::StrongholdEnd), + _ => None, + }, } } @@ -155,7 +191,76 @@ impl StartChecks { return false; } } - true + match self.repurposed { + Some(check) => repurposed(check, queries, chunk, y), + None => true, + } + } +} + +/// [`Repurposed`]'s checks. A noise column reads air past its ends; its +/// length is the noise's depth (GeneralUtils.getMaxTerrainLimit). +fn repurposed(check: Repurposed, queries: &mut impl CheckQueries, chunk: ChunkPos, y: i32) -> bool { + let (x0, z0) = (chunk.x * 16, chunk.z * 16); + let bottom = queries.bottom(); + let at = |column: &[bool], y: i32| { + usize::try_from(y - bottom) + .ok() + .and_then(|i| column.get(i).copied()) + .unwrap_or(false) + }; + match check { + Repurposed::CityNether => { + let sea = queries.sea_level(); + for cx in chunk.x - 1..=chunk.x + 1 { + for cz in chunk.z - 1..=chunk.z + 1 { + if (cx, cz) == (chunk.x, chunk.z) { + continue; + } + let (filled, _) = queries.liquid_column(cx << 4, cz << 4); + let top = (bottom + filled.len() as i32).min(sea + 45); + if (sea + 20..top).any(|y| at(&filled, y)) { + return false; + } + } + } + true + } + Repurposed::ShipwreckNether => { + for dx in (-16..=16).step_by(8) { + for dz in (-16..=16).step_by(8) { + let (filled, solid) = queries.liquid_column(x0 + dx, z0 + dz); + // Not air and no fluid: in a noise column, a solid block. + if (0..=30) + .step_by(5) + .any(|dy| at(&filled, y + dy) && at(&solid, y + dy)) + { + return false; + } + } + } + true + } + Repurposed::StrongholdEnd => { + let (filled, _) = queries.liquid_column(x0, z0); + let min_land = (bottom + filled.len() as i32).min(bottom + 45); + // getHeightAt: the lowest height so far, less one at every sample. + let mut land = i32::MAX; + let mut sample = |x: i32, z: i32, land: &mut i32| { + let h = queries.first_free_height(x, z, HeightmapType::WorldSurfaceWg); + *land = (*land).min(h) - 1; + *land >= min_land + }; + for distance in [70, 35] { + // Direction.Plane.HORIZONTAL: north, east, south, west. + for (dx, dz) in [(0, -1), (1, 0), (0, 1), (-1, 0)] { + if !sample(x0 + dx * distance, z0 + dz * distance, &mut land) { + return false; + } + } + } + sample(x0, z0, &mut land) + } } } @@ -172,18 +277,27 @@ mod tests { column: Vec<char>, biomes: BTreeMap<(i32, i32), u32>, asked: Vec<[i32; 3]>, + /// Columns by (x, z), instead of `column`, from y 0. + columns: BTreeMap<(i32, i32), Vec<char>>, } 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<bool>, Vec<bool>) { + fn liquid_column(&mut self, x: i32, z: i32) -> (Vec<bool>, Vec<bool>) { // '.' air, '#' stone, '~' water, from the bottom up. + let column = self.columns.get(&(x, z)).unwrap_or(&self.column); ( - self.column.iter().map(|&c| c != '.').collect(), - self.column.iter().map(|&c| c == '#').collect(), + column.iter().map(|&c| c != '.').collect(), + column.iter().map(|&c| c == '#').collect(), ) } + fn sea_level(&self) -> i32 { + 32 + } + fn bottom(&self) -> i32 { + 0 + } 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)) @@ -274,4 +388,75 @@ mod tests { assert!(bounds(0, 64).pass(&mut fake, &none, CHUNK, 0, None)); assert!(!bounds(0, 59).pass(&mut fake, &none, CHUNK, 0, None)); } + + /// A column of `n` blocks: `fill` up to `top` (exclusive), air above. + fn column(n: usize, top: usize, fill: char) -> Vec<char> { + (0..n).map(|y| if y < top { fill } else { '.' }).collect() + } + + #[test] + fn repurposed_city_needs_air_above_the_lava_sea_around() { + let none = BTreeSet::new(); + let city = checks(json!({"repurposed": "city_nether"})); + // Sea 32: air needed from 52 to 76 (128 deep), in the 8 chunks around. + let mut fake = Fake { + column: column(128, 52, '#'), + ..Fake::default() + }; + // The chunk itself is not read. + fake.columns.insert((32, -16), column(128, 100, '#')); + assert!(city.pass(&mut fake, &none, CHUNK, 33, None)); + fake.columns.insert((48, 0), column(128, 53, '#')); + assert!(!city.pass(&mut fake, &none, CHUNK, 33, None)); + // Above sea + 45 nothing is read. + fake.columns.insert((48, 0), { + let mut c = column(128, 52, '#'); + c[77] = '#'; + c + }); + assert!(city.pass(&mut fake, &none, CHUNK, 33, None)); + } + + #[test] + fn repurposed_shipwreck_needs_no_solid_block_around() { + let none = BTreeSet::new(); + let wreck = checks(json!({"repurposed": "shipwreck_nether"})); + // Lava up to 40, air above: the samples at 28..=58 meet only lava and air. + let mut fake = Fake { + column: column(128, 40, '~'), + ..Fake::default() + }; + assert!(wreck.pass(&mut fake, &none, CHUNK, 28, None)); + // Netherrack at y 43, between samples (28 + 15, + 20 are 43, 48). + let mut rock = column(128, 40, '~'); + rock[43] = '#'; + fake.columns.insert((32 - 16, -16 + 16), rock.clone()); + assert!(!wreck.pass(&mut fake, &none, CHUNK, 28, None)); + rock[43] = '.'; + rock[44] = '#'; + fake.columns.insert((16, 0), rock); + assert!(wreck.pass(&mut fake, &none, CHUNK, 28, None)); + } + + #[test] + fn repurposed_end_stronghold_needs_land_around() { + let none = BTreeSet::new(); + let end = checks(json!({"repurposed": "stronghold_end"})); + let mut fake = Fake { + column: column(256, 0, '#'), + ..Fake::default() + }; + // Every height 64 by default: 63, 62, ... 55 after the 9 samples. + assert!(end.pass(&mut fake, &none, CHUNK, 0, None)); + // Land at least 45 above the bottom, after the sample's minus one: + // 46 at the corner passes, 45 fails. + fake.heights.insert((32, -16), 46); + assert!(end.pass(&mut fake, &none, CHUNK, 0, None)); + fake.heights.insert((32, -16), 45); + assert!(!end.pass(&mut fake, &none, CHUNK, 0, None)); + // Void 70 blocks north fails at once. + fake.heights.clear(); + fake.heights.insert((32, -86), 0); + assert!(!end.pass(&mut fake, &none, CHUNK, 0, None)); + } } diff --git a/crates/horizon-world/src/worldgen/structure/stronghold.rs b/crates/horizon-world/src/worldgen/structure/stronghold.rs index 270b412af..e1a10808f 100644 --- a/crates/horizon-world/src/worldgen/structure/stronghold.rs +++ b/crates/horizon-world/src/worldgen/structure/stronghold.rs @@ -14,17 +14,18 @@ use std::{collections::BTreeSet, f64::consts::PI, sync::Mutex}; /// ChunkGeneratorStructureState.generateRingPositions with /// BiomeSource.findBiomeHorizontal (radius 112, step 1, not closest). +/// `biomes` samples a search's quarts in order, as one caching resolver. pub fn ring_positions( seed: i64, distance: i32, spread: i32, count: i32, preferred: &BTreeSet<BiomeId>, - biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + biomes: &mut dyn FnMut(&[[i32; 3]]) -> Vec<BiomeId>, ) -> Vec<ChunkPos> { ring_searches(seed, distance, spread, count) .iter() - .map(|search| search.find(preferred, biome)) + .map(|search| search.find(preferred, biomes)) .collect() } @@ -39,23 +40,30 @@ pub struct RingSearch { impl RingSearch { /// BiomeSource.findBiomeHorizontal around the ring chunk's centre: a /// random preferred biome within 112 blocks, else the ring chunk itself. + /// + /// Vanilla samples the square in order on one thread, and its climate + /// index (Climate.RTree) starts each lookup from the previous result and + /// keeps it on a tie; so `biomes` gets the whole square at once, in + /// vanilla's order. Fresh lookups moved seed 1234's first stronghold 6 + /// chunks: one quart on a lush caves / ocean tie went to the ocean. pub fn find( &self, preferred: &BTreeSet<BiomeId>, - biome: &mut dyn FnMut([i32; 3]) -> BiomeId, + biomes: &mut dyn FnMut(&[[i32; 3]]) -> Vec<BiomeId>, ) -> ChunkPos { let mut search = self.random.clone(); let (cx, cz) = ((self.x * 16 + 8) >> 2, (self.z * 16 + 8) >> 2); + let quarts: Vec<[i32; 3]> = (-28..=28) + .flat_map(|dz| (-28..=28).map(move |dx| [cx + dx, 0, cz + dz])) + .collect(); let mut found = 0; let mut result = None; - for dz in -28..=28 { - for dx in -28..=28 { - if preferred.contains(&biome([cx + dx, 0, cz + dz])) { - if result.is_none() || search.next_int_bound(found + 1).unwrap_or(1) == 0 { - result = Some(((cx + dx) << 2, (cz + dz) << 2)); - } - found += 1; + for (quart, biome) in quarts.iter().zip(biomes(&quarts)) { + if preferred.contains(&biome) { + if result.is_none() || search.next_int_bound(found + 1).unwrap_or(1) == 0 { + result = Some((quart[0] << 2, quart[2] << 2)); } + found += 1; } } match result { diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs new file mode 100644 index 000000000..8298dfb4a --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -0,0 +1,1120 @@ +//! YUNG's API's jigsaw assembler, for the structures of the "YUNG's Better" +//! mods carried over from a modpack (docs/modpacks.md). Carry maps +//! `yungsapi:yung_jigsaw` to `minecraft:jigsaw` with a `"horizon:yungsapi"` +//! key, and its pool elements to vanilla's single element with the piece's +//! rules under the same key; vanilla data never has it. +//! +//! The assembler differs from vanilla's JigsawPlacement: it picks the start +//! piece and every child by weight from the pool's weighted entries (a +//! priority piece first), lays pieces out breadth first, caps pieces by name +//! (`max_count`), limits them by depth, lets some ignore the bounds, checks +//! each piece's condition, and keeps every piece between `min_y` and +//! `max_y`. Pieces fit the same free space as vanilla's. A piece that ends +//! up with no child can be swapped for one of a dead-end pool, and once the +//! layout is done each piece's modifiers can turn it into another template +//! or place it last. +use super::{ + BoundingBox, Rotation, StructureResources, StructureTemplate, + jigsaw::{ + Free, JigsawConfig, JigsawContext, Junction, PoolElement, PoolPiece, Pools, Projection, + can_attach, shuffle, step, + }, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::random::{LegacyRandom, RandomSource, WorldgenRandom}; +use serde_json::Value; +use std::{ + cell::RefCell, + collections::{HashMap, VecDeque}, + rc::Rc, + sync::Arc, +}; + +/// A YUNG structure's own settings (`"horizon:yungsapi"` on the structure): +/// the heights every piece must stay within. +#[derive(Debug, Default)] +pub struct Config { + pub min_y: Option<i32>, + pub max_y: Option<i32>, +} +impl Config { + pub fn decode(v: &Value) -> Self { + let y = |k: &str| v[k].as_i64().map(|n| n as i32); + Self { + min_y: y("min_y"), + max_y: y("max_y"), + } + } +} + +/// A piece's rules (`"horizon:yungsapi"` on a pool element). +#[derive(Clone, Debug, Default)] +pub struct Rules { + /// Pieces sharing a name share the cap `max_count`. + name: Option<String>, + max_count: Option<i32>, + min_depth: Option<i32>, + max_depth: Option<i32>, + /// Chosen before any other piece of its pool. + priority: bool, + /// Placed even where it overlaps other pieces or leaves the bounds. + ignore_bounds: bool, + condition: Condition, + /// The pool a piece that got no child is swapped for. + deadend_pool: Option<String>, + /// Applied to the piece once the layout is done. + modifiers: Vec<Modifier>, +} +impl Rules { + pub fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + Ok(Self { + name: v["name"].as_str().map(str::to_owned), + max_count: int("max_count"), + min_depth: int("min_depth"), + max_depth: int("max_depth"), + priority: v["priority"].as_bool().unwrap_or(false), + ignore_bounds: v["ignore_bounds"].as_bool().unwrap_or(false), + condition: match v.get("condition") { + Some(c) => Condition::decode(c, resources)?, + None => Condition::True, + }, + deadend_pool: v["deadend_pool"].as_str().map(str::to_owned), + modifiers: v["modifiers"] + .as_array() + .into_iter() + .flatten() + .map(|m| Modifier::decode(m, resources)) + .collect::<Result<_, _>>()?, + }) + } + /// YungJigsawPoolElement.isAtValidDepth. + fn at_valid_depth(&self, depth: i32) -> bool { + self.min_depth.is_none_or(|d| d <= depth) && self.max_depth.is_none_or(|d| d >= depth) + } + /// The name a capped piece counts under: `max_count` without a name is + /// ignored, as YUNG's does. + fn capped(&self) -> Option<(&str, i32)> { + Some((self.name.as_deref()?, self.max_count?)) + } +} + +/// A StructureModifier: when its condition holds for the piece, its actions +/// apply to the piece (the `self` target, the only one YUNG's API has). +#[derive(Clone, Debug)] +struct Modifier { + condition: Condition, + actions: Vec<Action>, +} +impl Modifier { + fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + Ok(Self { + condition: match v.get("condition") { + Some(c) => Condition::decode(c, resources)?, + None => Condition::True, + }, + actions: v["actions"] + .as_array() + .ok_or(DecodeError::Field("modifier actions"))? + .iter() + .map(|a| Action::decode(a, resources)) + .collect::<Result<_, _>>()?, + }) + } +} + +#[derive(Clone, Debug)] +enum Action { + /// TransformAction: the piece becomes one of these templates, moved by + /// `offset` turned with the piece. + Transform { + output: Vec<Arc<StructureTemplate>>, + offset: [i32; 3], + }, + /// DelayGenerationAction: the piece is placed after every other. + DelayGeneration, +} +impl Action { + fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + Ok(match v["type"].as_str().unwrap_or_default() { + "transform" => { + let output = v["output"] + .as_array() + .into_iter() + .flatten() + .map(|t| { + let id = t.as_str().ok_or(DecodeError::Field("transform output"))?; + resources + .template(id) + .ok_or_else(|| DecodeError::Registry(format!("missing template {id}"))) + }) + .collect::<Result<Vec<_>, _>>()?; + if output.is_empty() { + return Err(DecodeError::Field("transform output")); + } + let offset = v["offset"].as_array(); + let at = |i: usize| { + offset + .and_then(|o| o.get(i)) + .and_then(Value::as_i64) + .unwrap_or(0) as i32 + }; + Self::Transform { + output, + offset: [at(0), at(1), at(2)], + } + } + "delay_generation" => Self::DelayGeneration, + _ => return Err(DecodeError::Field("YUNG modifier action type")), + }) + } +} + +/// YUNG's structure conditions, as carry writes them. +#[derive(Clone, Debug, Default)] +enum Condition { + #[default] + True, + False, + Not(Box<Condition>), + AllOf(Vec<Condition>), + AnyOf(Vec<Condition>), + Depth { + min: Option<i32>, + max: Option<i32>, + }, + Altitude { + bottom: Option<f64>, + top: Option<f64>, + }, + RandomChance(f32), + Rotation(Vec<Rotation>), + /// Another piece (of these templates, or any) within `range` blocks in + /// the direction `rotation` turns the piece's own north. + PieceInDirection { + templates: Vec<Arc<StructureTemplate>>, + range: i32, + rotation: Rotation, + }, + /// Another piece (of these templates, or any when None) within the + /// piece's box grown by these ranges, not overlapping the piece. + PieceInRange { + templates: Option<Vec<Arc<StructureTemplate>>>, + horizontal: i32, + above: i32, + below: i32, + }, +} +impl Condition { + fn decode(v: &Value, resources: &StructureResources) -> Result<Self, DecodeError> { + let list = |k: &'static str| -> Result<Vec<Condition>, DecodeError> { + v[k].as_array() + .ok_or(DecodeError::Field(k))? + .iter() + .map(|c| Self::decode(c, resources)) + .collect() + }; + let int = |k: &str| v[k].as_i64().map(|n| n as i32); + let rotation = |r: &Value| { + r.as_str() + .and_then(Rotation::from_name) + .ok_or(DecodeError::Field("condition rotation")) + }; + Ok(match v["type"].as_str().unwrap_or_default() { + "true" => Self::True, + "false" => Self::False, + "not" => Self::Not(Box::new(Self::decode(&v["condition"], resources)?)), + "all_of" => Self::AllOf(list("conditions")?), + "any_of" => Self::AnyOf(list("conditions")?), + "depth" => Self::Depth { + min: int("min_depth"), + max: int("max_depth"), + }, + "altitude" => Self::Altitude { + bottom: v["bottom"].as_f64(), + top: v["top"].as_f64(), + }, + "random_chance" => Self::RandomChance(v["chance"].as_f64().unwrap_or(0.) as f32), + "rotation" => Self::Rotation( + v["rotations"] + .as_array() + .into_iter() + .flatten() + .map(rotation) + .collect::<Result<_, _>>()?, + ), + "piece_in_horizontal_direction" => Self::PieceInDirection { + templates: v["pieces"] + .as_array() + .into_iter() + .flatten() + .filter_map(|p| resources.template(p.as_str()?)) + .collect(), + range: int("range").unwrap_or(0), + rotation: rotation(&v["rotation"])?, + }, + "piece_in_range" => { + let pieces = v["pieces"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default(); + let any = pieces.is_empty() || pieces.iter().any(|p| p == "yungsapi:all"); + Self::PieceInRange { + // An unknown template matches nothing, as YUNG's API's + // empty stand-in does. + templates: (!any).then(|| { + pieces + .iter() + .filter_map(|p| resources.template(p.as_str()?)) + .collect() + }), + horizontal: int("horizontal_range").unwrap_or(0), + above: int("above_range").unwrap_or(0), + below: int("below_range").unwrap_or(0), + } + } + _ => return Err(DecodeError::Field("YUNG condition type")), + }) + } + /// StructureCondition.passes. `at` is the piece being placed: its box, + /// rotation and depth; the start piece has no box yet. + fn passes(&self, at: &At<'_>, random: &mut impl RandomSource) -> bool { + match self { + Self::True => true, + Self::False => false, + Self::Not(c) => !c.passes(at, random), + Self::AllOf(all) => all.iter().all(|c| c.passes(at, random)), + Self::AnyOf(any) => any.iter().any(|c| c.passes(at, random)), + Self::Depth { min, max } => { + min.is_none_or(|d| d <= at.depth) && max.is_none_or(|d| d >= at.depth) + } + Self::Altitude { bottom, top } => { + let [low, high] = at.span; + bottom.is_none_or(|y| f64::from(low) >= y) + && top.is_none_or(|y| f64::from(high) <= y) + } + Self::RandomChance(chance) => random.next_float() < *chance, + Self::Rotation(valid) => valid.contains(&at.rotation), + Self::PieceInDirection { + templates, + range, + rotation, + } => { + let Some(piece) = at.piece else { + return false; + }; + let mut search = piece; + match at.rotation.get_rotated(*rotation) { + Rotation::None => search.min[2] -= range, + Rotation::Clockwise90 => search.max[0] += range, + Rotation::Clockwise180 => search.max[2] += range, + Rotation::Counterclockwise90 => search.min[0] -= range, + } + at.near(piece, &search, |template| { + templates.is_empty() || templates.iter().any(|t| Arc::ptr_eq(t, template)) + }) + } + Self::PieceInRange { + templates, + horizontal, + above, + below, + } => { + let Some(piece) = at.piece else { + return false; + }; + let search = BoundingBox::new( + [ + piece.min[0] - horizontal, + piece.min[1] - below, + piece.min[2] - horizontal, + ], + [ + piece.max[0] + horizontal, + piece.max[1] + above, + piece.max[2] + horizontal, + ], + ); + at.near(piece, &search, |template| { + templates + .as_ref() + .is_none_or(|ts| ts.iter().any(|t| Arc::ptr_eq(t, template))) + }) + } + } + } +} + +/// The surface height query, object-safe for the per-call cache. +trait JigsawContextDyn { + fn surface(&mut self, x: i32, z: i32) -> i32; +} +impl<C: JigsawContext> JigsawContextDyn for C { + fn surface(&mut self, x: i32, z: i32) -> i32 { + self.base_height(x, z, HeightmapType::WorldSurfaceWg) + } +} + +/// What a condition sees of the piece being placed (or modified). +struct At<'a> { + depth: i32, + rotation: Rotation, + piece: Option<BoundingBox>, + /// The piece's lowest and highest Y when the condition was set up. + span: [i32; 2], + pieces: &'a [PoolPiece], + /// Pieces taken out by a dead end, by index; the rest are kept. + gone: &'a [bool], +} +impl At<'_> { + /// Whether another single piece whose template matches lies in `search` + /// without overlapping `piece` (nor being exactly it). + fn near( + &self, + piece: BoundingBox, + search: &BoundingBox, + matches: impl Fn(&Arc<StructureTemplate>) -> bool, + ) -> bool { + self.pieces.iter().enumerate().any(|(i, other)| { + let PoolElement::Single { template, .. } = other.element.as_ref() else { + return false; + }; + let b = other.bounding_box; + !self.gone.get(i).copied().unwrap_or(false) + && b != piece + && matches(template) + && b.intersects(search) + && !b.intersects(&piece) + }) + } +} + +/// The index of the entry to try: the first priority piece, else one drawn +/// by weight (`nextInt(total) + 1`, counted down). +fn pick( + candidates: &[(Arc<PoolElement>, i32)], + total: i32, + random: &mut impl RandomSource, +) -> usize { + if let Some(i) = candidates + .iter() + .position(|(e, _)| e.yung().is_some_and(|r| r.priority)) + { + return i; + } + let mut chosen = random.next_int_bound(total).unwrap_or(0) + 1; + for (i, (_, weight)) in candidates.iter().enumerate() { + chosen -= weight; + if chosen <= 0 { + return i; + } + } + candidates.len() - 1 +} + +/// JigsawManager.assembleJigsawStructure: the start position and the +/// pieces, or None when no start piece fits. +#[allow(clippy::too_many_arguments)] +pub fn assemble( + config: &JigsawConfig<'_>, + yung: &Config, + context: &mut impl JigsawContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + position: [i32; 3], +) -> Option<([i32; 3], Vec<PoolPiece>)> { + let pool = pools.get(config.start_pool, resources, bindings)?; + let mut candidates = pool.raw.clone(); + shuffle(&mut candidates, random); + let rotation = Rotation::random(random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + let (element, adjusted, local) = loop { + if candidates.is_empty() || total <= 0 { + return None; + } + let index = pick(&candidates, total, random); + let (element, weight) = candidates[index].clone(); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let anchored = match config.start_jigsaw { + Some(name) => { + element + .shuffled_jigsaws(resources, position, rotation, random) + .into_iter() + .find(|j| j.name.as_deref() == Some(name))? + .pos + } + None => position, + }; + let local: [i32; 3] = std::array::from_fn(|i| anchored[i] - position[i]); + let adjusted: [i32; 3] = std::array::from_fn(|i| position[i] - local[i]); + let at = At { + depth: 0, + rotation, + piece: None, + span: [0, 0], + pieces: &[], + gone: &[], + }; + if element + .yung() + .is_some_and(|r| !r.condition.passes(&at, random)) + { + total -= weight; + candidates.remove(index); + continue; + } + break (element, adjusted, local); + }; + let mut start = PoolPiece { + bounding_box: element.bounding_box(adjusted, rotation), + ground_level_delta: element.ground_level_delta(), + element, + position: adjusted, + rotation, + junctions: Vec::new(), + waterlogging: config.waterlogging, + }; + let b = start.bounding_box; + let (cx, cz) = ((b.max[0] + b.min[0]) / 2, (b.max[2] + b.min[2]) / 2); + let bottom = match config.project_to { + Some(kind) => position[1] + context.base_height(cx, cz, kind), + None => adjusted[1], + }; + start.moved(bottom - (b.min[1] + start.ground_level_delta)); + let cy = bottom + local[1]; + let d = config.max_distance[0]; + let free = Rc::new(RefCell::new(Free { + container: BoundingBox::new([cx - d, cy - d, cz - d], [cx + d, cy + d, cz + d]), + removed: vec![start.bounding_box], + })); + let mut assembler = Assembler { + config, + yung, + pools, + resources, + bindings, + pieces: vec![start], + states: vec![(free, 0)], + origins: vec![None], + gone: vec![false], + counts: HashMap::new(), + }; + if config.max_depth > 0 { + let mut queue = VecDeque::from([0]); + while let Some(piece) = queue.pop_front() { + assembler.children(piece, &mut queue, context, random); + } + } + Some(([cx, cy, cz], assembler.modified(random))) +} + +/// JigsawStructureAssembler. +struct Assembler<'a> { + config: &'a JigsawConfig<'a>, + yung: &'a Config, + pools: &'a Pools, + resources: &'a StructureResources, + bindings: &'a FeatureBlockBindings<'a>, + pieces: Vec<PoolPiece>, + /// Per piece: the free space it was placed in, and its depth. + states: Vec<(Rc<RefCell<Free>>, i32)>, + /// Per piece: where it was placed and the junction it left on its + /// parent (none for the start piece), for a dead end to undo. + origins: Vec<Option<(Slot, Junction)>>, + /// Per piece: taken out by a dead end. + gone: Vec<bool>, + /// Pieces placed per capped name. + counts: HashMap<String, i32>, +} + +/// Where a child goes: the parent's jigsaw and what it needs. +#[derive(Clone)] +struct Slot { + source: usize, + jigsaw: super::jigsaw::Jigsaw, + target_pos: [i32; 3], + free: Rc<RefCell<Free>>, + depth: i32, +} + +impl Assembler<'_> { + fn pool(&self, name: &str) -> Option<Arc<super::jigsaw::Pool>> { + let name = self.config.aliases.get(name).map_or(name, String::as_str); + self.pools.get(name, self.resources, self.bindings) + } + /// JigsawStructureAssembler.Settings.isInBounds. + fn in_bounds(&self, y: i32, context: &impl JigsawContext) -> bool { + self.yung.max_y.is_none_or(|m| y <= m) + && self.yung.min_y.is_none_or(|m| y >= m) + && y >= context.min_y() + self.config.padding[0] + && y <= context.max_y() + 1 - self.config.padding[1] + } + /// addChildrenForPiece: one child per jigsaw where one fits, from the + /// target pool unless the piece is at the last depth, else its fallback. + fn children( + &mut self, + source: usize, + queue: &mut VecDeque<usize>, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) { + let (element, position, rotation, source_box) = { + let s = &self.pieces[source]; + (s.element.clone(), s.position, s.rotation, s.bounding_box) + }; + let (context_free, depth) = self.states[source].clone(); + let mut source_free: Option<Rc<RefCell<Free>>> = None; + let jigsaws = element.shuffled_jigsaws(self.resources, position, rotation, random); + let count = jigsaws.len(); + let mut any = false; + for jigsaw in jigsaws { + let Some(target) = self.pool(&jigsaw.pool) else { + continue; + }; + if target.templates.is_empty() && jigsaw.pool != "minecraft:empty" { + continue; + } + let Some(fallback) = self.pool(&target.fallback) else { + continue; + }; + if fallback.templates.is_empty() && target.fallback != "minecraft:empty" { + continue; + } + let s = step(jigsaw.front); + let target_pos: [i32; 3] = std::array::from_fn(|i| jigsaw.pos[i] + s[i]); + let free = if source_box.is_inside(target_pos) { + source_free + .get_or_insert_with(|| { + Rc::new(RefCell::new(Free { + container: source_box, + removed: Vec::new(), + })) + }) + .clone() + } else { + context_free.clone() + }; + let slot = Slot { + source, + jigsaw, + target_pos, + free, + depth, + }; + let placed = depth != self.config.max_depth + && self.choose(&slot, target.raw.clone(), queue, context, random); + any |= placed || self.choose(&slot, fallback.raw.clone(), queue, context, random); + } + if let Some(pool) = element.yung().and_then(|r| r.deadend_pool.as_deref()) + && !any + && count > 1 + { + self.dead_end(source, pool, queue, context, random); + } + } + /// A piece with a dead-end pool that got no child though it has other + /// jigsaws is taken out, its parent's junction and its room freed and its + /// count given back, and a piece of that pool is chosen in its place for + /// the same parent jigsaw. The start piece stays. + fn dead_end( + &mut self, + piece: usize, + pool: &str, + queue: &mut VecDeque<usize>, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) { + let Some(pool) = self.pool(pool) else { + return; + }; + let Some((slot, junction)) = self.origins[piece].clone() else { + return; + }; + let parent = &mut self.pieces[slot.source].junctions; + if let Some(i) = parent.iter().position(|j| *j == junction) { + parent.remove(i); + } + let bounds = self.pieces[piece].bounding_box; + { + let mut free = slot.free.borrow_mut(); + if let Some(i) = free.removed.iter().position(|b| *b == bounds) { + free.removed.remove(i); + } + } + self.gone[piece] = true; + let element = self.pieces[piece].element.clone(); + if let Some((name, _)) = element.yung().and_then(Rules::capped) + && let Some(count) = self.counts.get_mut(name) + { + *count -= 1; + } + self.choose(&slot, pool.raw.clone(), queue, context, random); + } + /// applyModifications: each piece's modifiers, in piece order, then the + /// delayed pieces moved last. Returns the pieces kept. + fn modified(mut self, random: &mut impl RandomSource) -> Vec<PoolPiece> { + let mut delayed = vec![false; self.pieces.len()]; + for (i, delay) in delayed.iter_mut().enumerate() { + let element = self.pieces[i].element.clone(); + let Some(rules) = element + .yung() + .filter(|r| !self.gone[i] && !r.modifiers.is_empty()) + else { + continue; + }; + let b = self.pieces[i].bounding_box; + let (depth, rotation, span) = ( + self.states[i].1, + self.pieces[i].rotation, + [b.min[1], b.max[1]], + ); + for modifier in &rules.modifiers { + let at = At { + depth, + rotation, + piece: Some(self.pieces[i].bounding_box), + span, + pieces: &self.pieces, + gone: &self.gone, + }; + if !modifier.condition.passes(&at, random) { + continue; + } + for action in &modifier.actions { + match action { + Action::Transform { output, offset } => { + transform(&mut self.pieces[i], output, *offset); + } + Action::DelayGeneration => *delay = true, + } + } + } + } + let (mut kept, mut last) = (Vec::new(), Vec::new()); + for ((piece, gone), delay) in self.pieces.into_iter().zip(self.gone).zip(delayed) { + if !gone { + if delay { &mut last } else { &mut kept }.push(piece); + } + } + kept.extend(last); + kept + } + /// chooseCandidateFromPool: whether a piece was placed. + fn choose( + &mut self, + slot: &Slot, + mut candidates: Vec<(Arc<PoolElement>, i32)>, + queue: &mut VecDeque<usize>, + context: &mut impl JigsawContext, + random: &mut impl RandomSource, + ) -> bool { + let jigsaw = &slot.jigsaw; + let (source_rigid, source_y, source_ground) = { + let s = &self.pieces[slot.source]; + ( + s.element.projection() == Projection::Rigid, + s.bounding_box.min[1], + s.ground_level_delta, + ) + }; + let local_y = jigsaw.pos[1] - source_y; + // The surface at the jigsaw, read once per call. + let mut surface = None; + let (x, z) = (jigsaw.pos[0], jigsaw.pos[2]); + let mut base = |context: &mut dyn JigsawContextDyn| { + *surface.get_or_insert_with(|| context.surface(x, z)) + }; + shuffle(&mut candidates, random); + let mut total: i32 = candidates.iter().map(|c| c.1).sum(); + while !candidates.is_empty() && total > 0 { + let index = pick(&candidates, total, random); + let (target, weight) = candidates[index].clone(); + if matches!(target.as_ref(), PoolElement::Empty) { + return false; + } + let rules = target.yung(); + let capped = rules.and_then(Rules::capped); + let full = capped + .is_some_and(|(name, max)| self.counts.get(name).copied().unwrap_or(0) >= max); + if full || rules.is_some_and(|r| !r.at_valid_depth(slot.depth)) { + total -= weight; + candidates.remove(index); + continue; + } + let mut rotations = Rotation::ALL; + shuffle(&mut rotations, random); + for rotation in rotations { + let target_jigsaws = + target.shuffled_jigsaws(self.resources, [0; 3], rotation, random); + let hack_box = target.bounding_box([0; 3], rotation); + let expand_to = if self.config.use_expansion_hack && hack_box.span()[1] <= 16 { + target_jigsaws + .iter() + .map(|tj| { + let st = step(tj.front); + if !hack_box.is_inside(std::array::from_fn(|i| tj.pos[i] + st[i])) { + return 0; + } + let child = self.pool(&tj.pool); + let child_size = child.as_ref().map_or(0, |p| p.max_size()); + let fallback_size = child + .and_then(|p| self.pool(&p.fallback)) + .map_or(0, |p| p.max_size()); + child_size.max(fallback_size) + }) + .max() + .unwrap_or(0) + } else { + 0 + }; + for target_jigsaw in &target_jigsaws { + if !can_attach(jigsaw, target_jigsaw) { + continue; + } + let target_local = target_jigsaw.pos; + let raw_position: [i32; 3] = + std::array::from_fn(|i| slot.target_pos[i] - target_local[i]); + let raw_box = target.bounding_box(raw_position, rotation); + let target_rigid = target.projection() == Projection::Rigid; + let delta_y = local_y - target_local[1] + step(jigsaw.front)[1]; + let target_y = if source_rigid && target_rigid { + source_y + delta_y + } else { + base(context) - target_local[1] + }; + let offset = target_y - raw_box.min[1]; + let mut target_box = raw_box.moved([0, offset, 0]); + let target_position = + [raw_position[0], raw_position[1] + offset, raw_position[2]]; + if expand_to > 0 { + let size = (expand_to + 1).max(target_box.max[1] - target_box.min[1]); + target_box.max[1] = target_box.min[1] + size; + } + if !self.in_bounds(target_box.max[1], context) + || !self.in_bounds(target_box.min[1], context) + { + continue; + } + if !rules.is_some_and(|r| r.ignore_bounds) + && !slot.free.borrow().fits(&target_box) + { + continue; + } + let target_ground = if target_rigid { + source_ground - delta_y + } else { + target.ground_level_delta() + }; + let junction_y = if source_rigid { + source_y + local_y + } else if target_rigid { + target_y + target_local[1] + } else { + base(context) + delta_y / 2 + }; + let at = At { + depth: slot.depth + 1, + rotation, + piece: Some(target_box), + span: [target_box.min[1], target_box.max[1]], + pieces: &self.pieces, + gone: &self.gone, + }; + if rules.is_some_and(|r| !r.condition.passes(&at, random)) { + continue; + } + let on_parent = Junction { + source_x: slot.target_pos[0], + source_ground_y: junction_y - local_y + source_ground, + source_z: slot.target_pos[2], + }; + self.pieces[slot.source].junctions.push(on_parent); + slot.free.borrow_mut().removed.push(target_box); + self.pieces.push(PoolPiece { + element: target.clone(), + position: target_position, + ground_level_delta: target_ground, + rotation, + bounding_box: target_box, + junctions: vec![Junction { + source_x: jigsaw.pos[0], + source_ground_y: junction_y - target_local[1] + target_ground, + source_z: jigsaw.pos[2], + }], + waterlogging: self.config.waterlogging, + }); + self.states.push((slot.free.clone(), slot.depth + 1)); + self.origins.push(Some((slot.clone(), on_parent))); + self.gone.push(false); + if slot.depth < self.config.max_depth { + queue.push_back(self.pieces.len() - 1); + } + if let Some((name, _)) = capped { + *self.counts.entry(name.to_owned()).or_default() += 1; + } + return true; + } + } + total -= weight; + candidates.remove(index); + } + false + } +} + +/// TransformAction: the piece takes one of `output`'s templates, picked by a +/// random seeded with setFeatureSeed(x, y, x) of its position, and moves by +/// `offset` turned with it. Like YUNG's API's new piece, it loses its +/// junctions and takes its own liquid setting (else waterlogging). +fn transform(piece: &mut PoolPiece, output: &[Arc<StructureTemplate>], offset: [i32; 3]) { + let [x, y, _] = piece.position; + let mut random = WorldgenRandom::new(LegacyRandom::new(0)); + random.set_feature_seed(i64::from(x), y, x); + let chosen = random.next_int_bound(output.len() as i32).unwrap_or(0) as usize; + let mut element = (*piece.element).clone(); + let PoolElement::Single { + template, + waterlogging, + .. + } = &mut element + else { + return; + }; + *template = output[chosen].clone(); + piece.waterlogging = waterlogging.unwrap_or(true); + let [dx, dy, dz] = offset; + let [dx, dz] = match piece.rotation { + Rotation::None => [dx, dz], + Rotation::Clockwise90 => [-dz, dx], + Rotation::Clockwise180 => [-dx, -dz], + Rotation::Counterclockwise90 => [dz, -dx], + }; + piece.position = [x + dx, y + dy, piece.position[2] + dz]; + piece.bounding_box = element.bounding_box(piece.position, piece.rotation); + piece.element = Arc::new(element); + piece.junctions.clear(); +} + +#[cfg(test)] +mod tests { + use super::*; + use horizon_core::random::LegacyRandom; + + fn single(template: &Arc<StructureTemplate>, rules: Option<Rules>) -> Arc<PoolElement> { + Arc::new(PoolElement::Single { + template: template.clone(), + processors: Default::default(), + legacy: false, + projection: Projection::Rigid, + waterlogging: None, + yung: rules.map(Box::new), + }) + } + + #[test] + fn picks_priority_pieces_then_by_weight() { + let t = Arc::new(StructureTemplate::empty()); + let plain = single(&t, None); + let first = single( + &t, + Some(Rules { + priority: true, + ..Rules::default() + }), + ); + let mut random = LegacyRandom::new(7); + let list = vec![(plain.clone(), 3), (first, 1)]; + assert_eq!(pick(&list, 4, &mut random), 1); + // By weight: nextInt(total) + 1, counted down; the first entry + // takes draws 1..=3 of 4. + let list = vec![(plain.clone(), 3), (plain, 1)]; + let mut ours = LegacyRandom::new(42); + let mut theirs = LegacyRandom::new(42); + for _ in 0..32 { + let draw = theirs.next_int_bound(4).unwrap() + 1; + assert_eq!(pick(&list, 4, &mut ours), usize::from(draw > 3)); + } + } + + #[test] + fn rules_cap_by_name_and_depth() { + let rules = Rules { + name: Some("room".into()), + max_count: Some(2), + min_depth: Some(1), + max_depth: Some(3), + ..Rules::default() + }; + assert_eq!(rules.capped(), Some(("room", 2))); + assert!(!rules.at_valid_depth(0) && rules.at_valid_depth(1) && !rules.at_valid_depth(4)); + // max_count without a name is ignored, as YUNG's does. + let unnamed = Rules { + max_count: Some(1), + ..Rules::default() + }; + assert_eq!(unnamed.capped(), None); + } + + #[test] + fn conditions() { + let t = Arc::new(StructureTemplate::empty()); + let other = Arc::new(StructureTemplate::empty()); + let neighbour = PoolPiece { + element: single(&t, None), + position: [0; 3], + ground_level_delta: 1, + rotation: Rotation::None, + bounding_box: BoundingBox::new([0, 0, -6], [4, 4, -1]), + junctions: Vec::new(), + waterlogging: true, + }; + let pieces = [neighbour]; + let at = |rotation, depth| At { + depth, + rotation, + piece: Some(BoundingBox::new([0, 10, 0], [4, 14, 4])), + span: [10, 14], + pieces: &pieces, + gone: &[], + }; + let mut random = LegacyRandom::new(1); + let depth = Condition::Depth { + min: Some(2), + max: None, + }; + assert!(!depth.passes(&at(Rotation::None, 1), &mut random)); + assert!(depth.passes(&at(Rotation::None, 2), &mut random)); + let altitude = |bottom, top| Condition::Altitude { bottom, top }; + assert!(altitude(Some(10.), Some(14.)).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(Some(10.5), None).passes(&at(Rotation::None, 0), &mut random)); + assert!(!altitude(None, Some(13.9)).passes(&at(Rotation::None, 0), &mut random)); + // North (-Z) of an unrotated piece, within 5 blocks; the neighbour + // stays below it in Y, but only X and Z are searched, and it must + // not overlap the piece itself. + let north = |templates, rotation| Condition::PieceInDirection { + templates, + range: 5, + rotation, + }; + assert!(!north(Vec::new(), Rotation::None).passes(&at(Rotation::None, 1), &mut random)); + let low = At { + piece: Some(BoundingBox::new([0, 0, 0], [4, 4, 4])), + span: [0, 4], + ..at(Rotation::None, 1) + }; + assert!(north(Vec::new(), Rotation::None).passes(&low, &mut random)); + assert!(north(vec![t.clone()], Rotation::None).passes(&low, &mut random)); + assert!(!north(vec![other], Rotation::None).passes(&low, &mut random)); + // The piece turned 180°: its north is south. + let turned = At { + rotation: Rotation::Clockwise180, + ..low + }; + assert!(!north(Vec::new(), Rotation::None).passes(&turned, &mut random)); + assert!(north(Vec::new(), Rotation::Clockwise180).passes(&turned, &mut random)); + let all = Condition::AllOf(vec![ + Condition::True, + Condition::Not(Box::new(Condition::False)), + Condition::Rotation(vec![Rotation::Clockwise180]), + ]); + assert!(all.passes(&turned, &mut random)); + assert!(!Condition::AnyOf(vec![Condition::False]).passes(&turned, &mut random)); + } + + #[test] + fn piece_in_range_searches_a_grown_box() { + let t = Arc::new(StructureTemplate::empty()); + let other = Arc::new(StructureTemplate::empty()); + let piece = BoundingBox::new([0, 0, 0], [4, 4, 4]); + let above = |gone: &'static [bool]| { + let pieces = vec![PoolPiece { + element: single(&t, None), + position: [0, 30, 0], + ground_level_delta: 1, + rotation: Rotation::None, + bounding_box: BoundingBox::new([0, 30, 0], [4, 34, 4]), + junctions: Vec::new(), + waterlogging: true, + }]; + (pieces, gone) + }; + let range = |templates, above| Condition::PieceInRange { + templates, + horizontal: 0, + above, + below: 0, + }; + let mut random = LegacyRandom::new(1); + let (pieces, gone) = above(&[]); + let at = At { + depth: 1, + rotation: Rotation::None, + piece: Some(piece), + span: [0, 4], + pieces: &pieces, + gone, + }; + // 26 blocks above the piece's top: in a 40-block search, not 20. + assert!(range(None, 40).passes(&at, &mut random)); + assert!(!range(None, 20).passes(&at, &mut random)); + assert!(range(Some(vec![t.clone()]), 40).passes(&at, &mut random)); + assert!(!range(Some(vec![other]), 40).passes(&at, &mut random)); + // An unknown template matches nothing; a piece taken out by a dead + // end is not seen. + assert!(!range(Some(Vec::new()), 40).passes(&at, &mut random)); + let (pieces, gone) = above(&[true]); + let at = At { + pieces: &pieces, + gone, + ..at + }; + assert!(!range(None, 40).passes(&at, &mut random)); + } + + #[test] + fn transform_picks_by_position_and_turns_its_offset() { + let (a, b) = ( + Arc::new(StructureTemplate::empty()), + Arc::new(StructureTemplate::empty()), + ); + let rules = Rules { + name: Some("pillar".into()), + ..Rules::default() + }; + let mut piece = PoolPiece { + element: single(&a, Some(rules)), + position: [100, 40, -7], + ground_level_delta: 1, + rotation: Rotation::Clockwise90, + bounding_box: BoundingBox::new([100, 40, -7], [104, 44, -3]), + junctions: vec![Junction { + source_x: 0, + source_ground_y: 0, + source_z: 0, + }], + waterlogging: false, + }; + transform(&mut piece, &[a.clone(), b.clone()], [-1, 2, 0]); + // setFeatureSeed(x, y, x): seed x + y + 10000 * x, then nextInt(2). + let mut java = LegacyRandom::new(100 + 40 + 10000 * 100); + let chosen = [&a, &b][java.next_int_bound(2).unwrap() as usize]; + let PoolElement::Single { template, yung, .. } = piece.element.as_ref() else { + panic!("not a single element"); + }; + assert!(Arc::ptr_eq(template, chosen)); + assert_eq!( + yung.as_ref().and_then(|r| r.name.as_deref()), + Some("pillar") + ); + // (-1, 2, 0) turned 90° clockwise is (0, 2, -1). + assert_eq!(piece.position, [100, 42, -8]); + assert!(piece.junctions.is_empty() && piece.waterlogging); + } +} diff --git a/crates/horizon-world/tests/rule_test_bounds.rs b/crates/horizon-world/tests/rule_test_bounds.rs index de4862f54..e3f614590 100644 --- a/crates/horizon-world/tests/rule_test_bounds.rs +++ b/crates/horizon-world/tests/rule_test_bounds.rs @@ -67,3 +67,80 @@ fn binding_rejects_unknown_tag_blocks_and_duplicate_canonical_tags() { ]); assert!(FeatureBlockBindings::with_tags(®istry, BTreeSet::new(), &tags).is_err()); } +#[test] +fn matter_phase_matches_what_a_block_is_made_of() { + // air, cave_air, void_air, stone, then water (level 0), rail, iron_chain. + let mut states: Vec<Tag> = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + ] + .iter() + .map(|name| Tag::compound([("id", Tag::String((*name).into()))])) + .collect(); + states.push(Tag::compound([ + ("id", Tag::String("minecraft:water".into())), + ( + "properties", + Tag::compound([("level", Tag::String("0".into()))]), + ), + ])); + for name in ["minecraft:rail", "minecraft:iron_chain"] { + states.push(Tag::compound([("id", Tag::String(name.into()))])); + } + let names = [ + "minecraft:air", + "minecraft:cave_air", + "minecraft:void_air", + "minecraft:stone", + "minecraft:water", + "minecraft:rail", + "minecraft:iron_chain", + ]; + let registry = BlockRegistry::from_nbt(&Tag::compound([ + ("DataVersion", Tag::Int(DATA_VERSION)), + ("states", Tag::List(states)), + ( + "defaults", + Tag::Compound( + names + .iter() + .enumerate() + .map(|(id, name)| ((*name).into(), Tag::Int(id as i32))) + .collect(), + ), + ), + ])) + .unwrap(); + let bindings = FeatureBlockBindings::new(®istry, BTreeSet::new()).unwrap(); + let mut random = horizon_core::random::LegacyRandom::new(0); + let matches = |phase: &str, invert: bool, random: &mut horizon_core::random::LegacyRandom| { + let json = format!( + r#"{{"predicate_type":"horizon:matter_phase","phase_to_test_for":"{phase}","invert_condition":{invert}}}"# + ); + let test = RuleTest::from_json(&json, &bindings).unwrap(); + (0..names.len() as u32) + .filter(|&id| test.test(horizon_world::registry::BlockStateId(id), [0; 3], random)) + .collect::<Vec<_>>() + }; + assert_eq!(matches("AIR", false, &mut random), [0, 1, 2]); + assert_eq!(matches("LIQUID", false, &mut random), [4]); + assert_eq!( + matches("AIR_RAIL_OR_CHAIN", false, &mut random), + [0, 1, 2, 5, 6] + ); + assert_eq!( + matches("LIQUID_RAIL_OR_CHAIN", false, &mut random), + [4, 5, 6] + ); + assert_eq!(matches("AIR", true, &mut random), [3, 4, 5, 6]); + // The phase is the enum's name as written; SOLID needs canOcclude. + for json in [ + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"air"}"#, + r#"{"predicate_type":"horizon:matter_phase","phase_to_test_for":"SOLID"}"#, + r#"{"predicate_type":"horizon:matter_phase"}"#, + ] { + assert!(RuleTest::from_json(json, &bindings).is_err(), "{json}"); + } +} diff --git a/docs/modpacks.md b/docs/modpacks.md index 1ecaed8bb..acc354f30 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -438,7 +438,87 @@ Two cases the oracle fills in: list. The structures now generate undecorated (no pillars under them, spawners as the template has them); 1,427 processors of 146 types in ATM10's mods, the most common `lithostitched:block_swap`, Formations' `biome_replacements` and Repurposed Structures' - pillar, fluid and void processors. Porting the common ones is next. + pillar, fluid and void processors. + - **Spawner processors** carried as data (`horizon-port-pack/src/processors.rs`). Most + chests in the mods' templates already name their loot table; what the Java processors add + is the spawners' mobs. Moog's and Repurposed Structures' spawner randomizing processors + become `horizon:spawner_mobs` (a weighted mob per spawner, picked with the placement's + random as theirs do, and the spawner NBT they write; Repurposed's `rs_spawners` lists are + written in). YUNG's Better Dungeons and Better Desert Temples turn a spawner or a + placeholder block (gravel, bone block, yellow wool...) into a spawner of a fixed mob: that + is vanilla's `rule` processor with an `append_static` block entity. Moog's vanilla loot + swap acts only when a "replace vanilla" preset is on, and they ship off. Moog's trial + spawner and vault processors keep the block and change its block entity: one `rule` per + block state, with the game's `horizon:edit` modifier, which takes out the state the + template was saved with (a vault saved with `state_updating_resumes_at` far in the future + never opens; a spawner's saved `spawn_data` blocks its own mobs) and merges in the + spawner's normal and ominous configs (by id: the carry upgrades `trial_spawner/` files' + mobs to 26.3's `equipment`) or the vault's loot table and key. Better Desert Temples' + placeholder blocks (orange, red and white glass, blue and yellow concrete, red wool, + polished diorite, blank pots) become what its processors make of them: the fixed swaps as + vanilla's `rule`, the random ones (suspicious sand, sand and sandstone, upside-down stairs, + cobwebs, sherds on the pots) as the game's `horizon:pick`, on the same `nextFloat` as the + mod. Better Dungeons' small dungeons keep one chest and each other one with a fifth's + chance, two at most (the game's `horizon:count_cap`, counted per placement as the mod's + DungeonContext is): 12 chests in five small dungeons at seed 1234 become 6. + Lithostitched's `block_swap` (137 lists, all in ChoiceTheorem's Overhauled Village) is the + game's `horizon:block_swap`: the same map, with Block.withPropertiesOf's properties kept; + a target block the game does not have (most of them are Nature's Spirit's and Croptopia's) + leaves the block as it is, as the mod does. Lithostitched's `reference` (CTOV builds most + of its lists from others) has the referenced lists' processors written in its place; its + `apply_random`, `condition` and `set_block` are the game's `horizon:apply_random`, + `horizon:condition` and `horizon:set_block`, with Lithostitched's random (the world seed + plus the name's hash, at the block, piece or structure). In a CTOV plains village at seed + 1234 the farms now grow carrots, potatoes and beetroot besides wheat, and 1,655 + cobblestone blocks become paths, grass, mossy cobblestone and planks. No Lithostitched processor is + dropped now (130 before), only CTOV's compat hooks for other mods inside them (142 copies). + Still taken out: Formations' biome replacements, Repurposed's pillars and fluid fixes, + blocks aged or propped up. + In the 128×128-chunk square (seed 1234), every spawner of a mod structure now has its mob: + in the Overworld 83 Better Dungeons spawners held the template's placeholder pig and 17 of + Moog's were empty (763 spawners with a mob, up from 628); in the Nether the 52 empty ones + in Moog's Nether Structures are filled (162, up from 110). Chests are unchanged: 2,777 + and 1,405 with a loot table. + - **Rule tests** written in Java. Repurposed Structures' mineshafts and Nether monument test + blocks with three of the mod's own rule tests inside vanilla `rule` processors: what a + block is made of (solid, liquid, air, with rails and chains), a chance over the distance + from the template's origin along one axis, and a world height range. The game runs them + as `horizon:matter_phase`, `horizon:piece_origin_axis_aligned_linear_pos` and + `horizon:y_value` with the mod's fields, and carry renames them (213 in 75 lists). + - **Renamed ids.** 26.3 calls 1.21.1's chain the iron chain (its datafixers rename it in + worlds). Carry renames it in recipes, loot tables and worldgen files (112 files in 5 mods: + Repurposed's mineshafts, Better Dungeons' processors, Regions Unexplored's hanging sign + recipes...), which otherwise fail to load in 26.3. With both, the 5 Nether mineshaft pools load: 47 of + Repurposed's Nether mineshafts in the 128×128-chunk square (seed 1234), under the lava sea. + - **Big templates** (#838). Vanilla reads structure templates with no limit on their tag + count; Horizon now does too (`nbt::Limits::templates`). Seven of ATM10's 8,962 carried + templates are past the old 1,000,000-tag cap: YUNG's monument start, four When Dungeons + Arise main pieces and two Nullscape pieces. They used to load as empty templates, so their + structures never started. + - **Additions to other sets and pools** (#832 in the game, #833 in carry). A set or pool file + holding `horizon:add_to` appends its entries to the sets or pools it names (docs/mods.md). + Carry writes these from lithostitched's `add_structure_set_entries` and + `add_template_pool_elements` modifiers whose load conditions hold for the mods ported + along, and from CTOV's Java registration: its 21 village types and 11 outposts join + vanilla's `villages` and `pillager_outposts` with the mod's default weights. + - **YUNG's API** (#839, #846 in the game; #840, #847 in carry). `yungsapi:yung_jigsaw` and its + elements become vanilla's jigsaw and single element, with their rules under + `horizon:yungsapi`. The game assembles them as YUNG's `JigsawManager` does: priority + pieces, caps by name, depth ranges, `ignore_bounds` and the conditions tree. YUNG's + placements become `horizon:` keys on a random spread: `horizon:exclusion_zone` for the + enhanced exclusion zone, `horizon:avoid_biomes` for the temples' ocean and river search, + `horizon:ring_sections` for Better Strongholds' rings. `horizon:disables` on a YUNG + structure turns off the vanilla type its mod's mixin turns off. It is written only when + the game can start the replacement, so vanilla mineshafts stay while Better Mineshafts (a + Java type) can't. + - **Repurposed Structures' and Moog's own assembler** (#850 in the game, #851 in carry). Both + lay out their jigsaws with `PieceLimitedJigsawManager`, not vanilla's. Their structures, the + Nether variants too, get `horizon:piece_limited`: `y_allowance`, burying, the pools whose + fallbacks ignore the bounds, liquid, the Nether land search and ledge, and each + structure's piece caps and required pieces from the mod's `*_pieces_spawn_counts` files. + The game assembles them the mods' way and runs their post-layout steps (centring, + burying, the Nether land search). + Each mod's `carry-report.json` lists what was mapped, the rules and processors lost by name, and the types left as they are. NeoForge's convention biome tags (`#c:is_forest`, ...) come @@ -453,19 +533,30 @@ Two cases the oracle fills in: ChoiceTheorem's Overhauled Village 66), and 103 convention biome tags written. - When Dungeons Arise, Structory and Towns and Towers use vanilla's types already. - Still lost, written in Java: - - YUNG's API: its own jigsaw assembler (priority pieces, per-piece caps, conditions, - enhanced terrain adaptation) and 491 elements and jigsaws, behind every "YUNG's Better" - mod; - - Formations' structure and element types (179); - - the nether jigsaw variants of Moog's and Repurposed (69), which search the column for - land after the layout; - - Moog's and Repurposed's layout rules: they centre the pieces on the start, bury or lift - the structure to the terrain and cap pieces per pool; - - Repurposed's mineshafts, mansions, monuments and cities, and MO Structures (38; its - library is only on CurseForge). - - CTOV's villages and outposts are added to vanilla's `villages` and `pillager_outposts` - sets by Java code, as lithostitched's `add_structure_set_entries` worldgen modifiers do for - many packs; a content mod has no way to add to a vanilla set yet, so none start. + - Formations' structure and element types (179): their placements read block states in the + noise column (solid, water, lava), which the structure context doesn't give yet; + - Repurposed's mineshafts, mansions and monuments, Better Mineshafts and two Better + Dungeons types: Java structure types; + - YUNG's and Moog's enhanced terrain adaptation, YUNG's piece modifiers and dead-end pools, + and the block processors written in Java (YUNG's banners, legs and decorations, Repurposed's + pillars and fluid fixes, Lithostitched's block swaps); + - MO Structures (38; its library is only on CurseForge). + + With every structure PR above, the same square (seed 1234, chunks -64..63) holds 362 + overworld starts with 22,026 pieces. CTOV has 7, Better Dungeons 72 and Better Ocean + Monuments 3, and vanilla's monuments are gone as YUNG's mod has them. In the Nether there + are 512 starts, up from 322: Moog's Nether Structures 147, Repurposed's Nether structures + 40, Better Fortresses 7, with no vanilla fortress. Over chunks -256..255: Better Strongholds 10 + (vanilla 0), Better Jungle Temples 5, Better Witch Huts 11. Vanilla's own worlds are + unchanged: the structure-start oracle still matches 35 of 35. + + Repurposed's Nether city, Nether shipwrecks and End stronghold are its generic jigsaw with + one more start check each, carried as `minecraft:jigsaw` with the check named in + `horizon:start_checks.repurposed`: open air from sea level + 20 to + 45 around the city's + chunk, no solid block in a 33×30×33 grid over a shipwreck, and land 45 blocks up at nine + points 35 and 70 blocks apart for the stronghold. Over chunks -320..319 in the Nether there + are 2 cities and 45 shipwrecks (30 and 865 without the checks); the End stronghold keeps + 8,000 blocks from the centre, and chunks 500..1139 × -320..319 hold 2 (43 without). In a world with the 40 mods, seed 1234, `/locate structure mvs:azelea_house` finds one 27 blocks from spawn and it stands there as the template builds it; When Dungeons Arise's diff --git a/docs/mods.md b/docs/mods.md index d1556abd7..bdf45f620 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -287,6 +287,22 @@ its row. The game reads this content into its block and item tables nobody registers (a block a port left out, another mod's item) is dropped, so the rest of the tag still loads; vanilla would drop the whole tag. +A mod adds to structure sets and template pools that are not its own +(vanilla's villages, another mod's houses) with a set or pool file in its own +namespace holding `horizon:add_to`, a key vanilla data never has. Its entries +are appended to each set or pool named, after every mod's own files, in mod +and file order; the file is no set or pool itself. A name nobody defines is +skipped. + +```json +{ "horizon:add_to": "minecraft:villages", + "structures": [ { "structure": "mymod:village_beach", "weight": 10 } ] } +``` + +A pool addition holds `"elements"` as a pool does. This is what lithostitched's +`add_structure_set_entries` and `add_template_pool_elements` modifiers do on +NeoForge and Fabric, and `horizon-port-pack carry` writes them from those. + ## Versions and compatibility - The API is the WIT package `horizon:mods@0.1.0`. New functions and diff --git a/docs/performance/startup-stage-3.md b/docs/performance/startup-stage-3.md new file mode 100644 index 000000000..28013e87c --- /dev/null +++ b/docs/performance/startup-stage-3.md @@ -0,0 +1,39 @@ +# Progressive world resources (#712) + +Stage 3a changes shared resource storage and accessors. Pack resources keep their existing per-game ownership for pack reloads. Stage 3b publishes core before the simulation tail, builds the real renderer using the previous device after releasing its surface, and gates backdrop streaming on that renderer. Stage 3c queues an early Play or Connect action and draws the existing level-loading progress screen while polling the worker each event-loop turn. Close and resize events continue to work. After the worker completes, the queued local/server action resumes; integrated servers receive the resource handle only after that join. The synchronous harness and dedicated path returns only fully loaded resources. + +Startup logs distinguish `core-ready`, `world renderer ready`, `starting title backdrop`, and `rest-ready`. Opt-in performance summaries carry `to_core_ms` and `to_rest_ms` separately from the existing UI-driven `to_title_ms`. Loader failures and panics propagate to the client; a tail taking more than 120 seconds fails rather than waiting indefinitely. + +## Stage 3d: interactive menu before core + +An ordinary launch now owns a `StartupMenu` inside `Loading`. The first menu atlas and panorama message makes the existing title screens interactive; assets, facts, biomes, pack tables, collision and motion continue on the resource worker. Pack-overlay and mod-content preparation also run on that worker. The live landscape still starts only after the core renderer exists. + +World browsing, world creation, server address entry and options use the existing title/options widgets. Play and Connect queue a `PendingWorldEntry`; the progress screen covers both the core and tail waits. Escape cancels the queued entry in either phase. Close and resize continue to work. The handoff transfers the title object, options screen, settings, cursor, clipboard selection, timing session and pending action instead of rebuilding the user's screen. + +Pack changes during core loading request another loader generation. The old core and tail finish before replacement begins so cache writes and tail registry initialization cannot overlap. Each generation has its own message channel and progress counter. Language/GUI metadata publication stays on the event-loop thread, using the current language selection rather than the worker's stale settings snapshot. Pack changes after the core handoff also wait for the tail before touching mob metadata. + +The menu still needs its own artwork and renderer before interaction. The core handoff still builds the full renderer and starts audio on the main thread; menu click sounds and controller navigation start with `Game`. This stage does not change synchronous harness/dedicated startup or introduce a render-facts export. + +Regression coverage publishes menu artwork while a fake core worker is blocked, edits a world draft, replaces fallback artwork without losing it, queues entry and draws progress, and checks that loader failure reaches the app. Additional checks cover server identity and cancelled-entry timing. + +## Render facts assessment + +`MeshTables::new` reads names, registry properties, class membership, collision shape flags, fluid and render properties from `BlockFacts`. `LightTables::new/load` reads emission, dampening, occlusion and shape-occlusion flags; geometry comes from `occlusion.nbt`. Neither table needs recipes, item data, AI or the other tail tables. + +A render subset is possible, but the current facts decoder also validates registry order and builds the gameplay projection from the same document. Meshing additionally depends on class chains from `block-behaviours.json`. Avoiding the 54 MB read requires an exported render-facts artifact (and its prepare/cache/version checks), or another decoder plus a second full read at world entry. This is beyond a cheap startup ownership change. Stage 4 can add that artifact and compare the resulting mesh/light tables against the full loader before moving facts out of core. + +## Measurement + +Measurements on this machine are warm runs with `HORIZON_NO_AUDIO=1`. Other compilation and parity jobs were running, so elapsed times are diagnostic rather than a controlled benchmark. + +Before phasing (3a, `42d65465`), `--offscreen --frames 3 --smoke-report` completed successfully with peak RSS 762,536 KiB. The report contained 3 frames, no chunks, no generated or meshed sections, no player, and no error. This is the synchronous harness path; the progressive path is measured separately after 3c. + +After phasing, the same warm three-frame synchronous smoke completed successfully with peak RSS 774,080 KiB, up 11,544 KiB (1.5%) from the 3a measurement. Both reports had 3 frames, no chunks, no generated or meshed sections, no player, and no error. Elapsed time is intentionally excluded from the comparison because the machine was running concurrent builds. + +The progressive checks used an overlay of the prepared resources with `mob-data.json` replaced by a FIFO. This holds WorldRest without a production delay hook. Core and the real renderer became ready, Options → Video opened, and the backdrop logged `title backdrop ready; world rest ready: false` before the FIFO was released. In an unblocked Horizon launch, core was ready at 4,776 ms, the renderer at 5,260 ms, and rest at 6,282 ms under compilation load. Backdrop generation and fade-in still take their own time; these marks measure bundle readiness separately. + +A direct singleplayer launch while the FIFO was held displayed `Loading items` and handled a window resize. Releasing the FIFO resumed entry; the run exited cleanly with a player, 85 chunks, 529 meshed sections and no error. That delayed-entry run peaked at 1,142,560 KiB, including the loaded world. Integrated-server entry also joined after release and rendered a world. Dedicated startup reached `Done`, handled `list` and `stop`, saved and exited with status 0 without constructing a renderer. + +The full parity selection against `origin/main` also includes the unmerged Stage 2 ancestors (313 harnesses). The local run was bounded at 30 minutes; its log recorded passes for `active_effects`, `active_effect_tick` and `anchor`. The remainder needs CI or a longer dedicated run. The client Rust tests, focused startup probes and memory measurements are separate from that incomplete parity run. + +Progressive-title RSS was measured separately with audio disabled, render distance 4 and a 30 FPS cap, using separate temporary game directories. The first 30-second pair measured 1,055,132 KiB before and 1,721,772 KiB after. A warm 60-second repeat in reverse order measured 1,031,948 KiB before and 1,145,776 KiB after: an increase of 113,828 KiB (about 111 MiB, 11%). These launches ran during compilation and did not advance through startup/streaming identically. They establish a memory cost to investigate, not a claim of RSS parity; a quiet-machine cold/warm comparison remains needed before merging the stack. diff --git a/docs/release-flow.md b/docs/release-flow.md index f1015a31f..b72d896b8 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -131,6 +131,7 @@ the notes. | Archive | Runs on | Checks | | --- | --- | --- | | `horizon-linux-x86_64.tar.gz` | GitHub `ubuntu-22.04` (an older glibc, so it runs on any recent distribution) | the standard loader and libraries only (`tools/check_imports.py`) | +| `horizon-server-linux-x86_64.tar.gz` | the same Linux job, after the client archive: `horizon-server`, `horizon-prepare` and the game built with `--no-default-features` as `horizon-engine` (docs/server.md) | as above, and neither `libasound.so.2` nor `libudev.so.1` (`tools/check_imports.py --server`) | | `horizon-windows-x64.zip` | GitHub `windows-latest`, C runtime linked in | system DLLs only (`tools/check_imports.py`) | | `horizon-macos-arm64.zip` | The Mac mini's runner (`vars.MAC_RUNNER=macos-latest` sends it to GitHub) | system libraries only (`otool -L`); a 1500-frame offscreen run of a new world (about 12 s; 300 frames end before the world has loaded) with resources prepared from the runner's own Minecraft (`--offscreen --world smoke --frames 1500 --smoke-report`: frames drawn, chunks generated and meshed, a player, no error) | diff --git a/docs/server.md b/docs/server.md index 941a4341b..3d8eb69c8 100644 --- a/docs/server.md +++ b/docs/server.md @@ -55,9 +55,10 @@ distance 10. The vanilla server was the pinned 26.3 `server.jar` on Java 25 with | What has to be installed | one 46.8 MB binary + 589 MB of prepared resources | Java 25 + the 62 MB jar | | Crates linked | 384 (wgpu, winit, cpal, gilrs, arboard, naga…) | n/a | -On Linux the binary loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup, even on a server. -wgpu, winit and the Wayland/X11 libraries are loaded only when a window opens. That makes a minimal -container image need ALSA and udev for a program that never plays a sound or reads a controller. +On Linux the full game loads `libasound.so.2` (cpal) and `libudev.so.1` (gilrs) at startup. wgpu, winit +and the Wayland/X11 libraries are loaded only when a window opens. The server build (`horizon-engine`, +section 3) is the same program built without its `audio` and `controllers` features, so it needs neither +library, and a minimal server image runs it as it is. The two clear losses are RAM and idle CPU. The dedicated server loads everything the client needs to draw (the HUD atlas, item renderer, block-entity models, panorama, fog and music tables, entity models), and it @@ -74,9 +75,13 @@ not tick cost, so it is in scope here (see section 9). headless client built from vanilla's own codecs, pings and joins Horizon's server and vanilla's from the same world copy. It compares every login, configuration and play packet up to the first chunk batch, the chunk bytes, chat, `/list`, failing commands, the console lines and the files left behind. Result on main: - see "Harnesses on main" below. The real vanilla GUI client (`tools/vanilla_client.py`) could not be run - here: the tool only knows Linux natives, and the Mac mini's session was locked, which stalls the client's - rendering. It runs on the desktop under vscreen. + see "Harnesses on main" below. +- **The real vanilla 26.3 client** (`tools/vanilla_client.py`, from the owner's own files, dev-only) joins + too. On 2026-10-18 it joined the server build of the game (`horizon-engine`, section 3) on the Mac mini: + `python3 tools/vanilla_client.py --name Vanilla --join localhost:PORT`. It logged in, drew the terrain + around spawn and stayed connected for four minutes, with no warning or error on the server. The tool + runs on Linux under vscreen and on macOS from the logged-in screen session, even a locked one, with vsync + off. ### What fails or is missing @@ -145,16 +150,22 @@ game built in `Game::new`, the integrated server on its own thread. On that base 1. The dedicated path skips everything only a window uses: the HUD atlas, item renderer, block-entity and entity models, panorama, fog, music, and mesh tables (perf-ticks-2 already stops server-side meshing). This is the RAM and start-time item. -2. The game moves into a library crate, with the window, audio and controller parts behind a `client` - feature. A `horizon-engine` binary built without that feature links no wgpu, winit, cpal or gilrs, and - needs neither ALSA nor udev. The supervisor finds it beside itself and falls back to `horizon-client`. +2. The game moves into a library crate, with the window parts behind a `client` feature, so + `horizon-engine` links no wgpu or winit either. Sound and controllers are already optional (the + `audio` and `controllers` features, on by default): `horizon-engine` today is the game built without + them (section 3). ## 3. Packaging -**Binaries.** The release archives already hold `horizon-client`, `horizon-ctl` and `horizon-prepare`. -`horizon-server` joins them (PR 3: `xtask package` and `release.yml` build it and check it starts). Once -`horizon-engine` exists (section 2), a separate small archive per platform -(`horizon-server-<os>-<arch>.tar.gz` or `.zip`) holds just the server's binaries. +**Binaries.** The release archives hold `horizon-client`, `horizon-ctl`, `horizon-prepare` and +`horizon-server`. On Linux the release also has `horizon-server-linux-x86_64.tar.gz`: `horizon-server`, +`horizon-prepare` and `horizon-engine`, the game built with `--no-default-features` (no sound, no +controllers), which links neither `libasound.so.2` nor `libudev.so.1`. `release.yml` builds it after the +client archive (`xtask package-server`) and fails if `tools/check_imports.py --server` finds either library; +CI lints the same build. `horizon-server` runs `horizon-engine` when it is beside it or on the PATH, else +`horizon-client`. Build it yourself with `cargo build --release -p horizon-client --no-default-features` +and copy `target/release/horizon-client` as `horizon-engine`. macOS and Windows have no such libraries to +avoid, so they keep the one archive. **Game files: the owner's own copy, as with `prepare`.** Nothing of Mojang's is redistributed and nothing is downloaded on the owner's behalf. `horizon-server` looks for prepared resources in this order: @@ -181,10 +192,16 @@ comes out of the headless-engine work. - Linux and macOS: `curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh` - The script picks the release archive for the OS and architecture (Linux x86_64, macOS arm64), downloads - it from GitHub Releases, and checks it against the SHA-256 GitHub publishes for each asset. It never asks - for sudo. Options: `--version vX.Y.Z`, `--dir` (default `~/.local/share/horizon`), `--bin` (default - `~/.local/bin`). + The script picks the release archive for the OS and architecture (on Linux x86_64 the server archive, + on macOS arm64 the game's), downloads it from GitHub Releases, and checks it against the SHA-256 GitHub + publishes for each asset. It never asks for sudo. Options: `--version vX.Y.Z`, `--dir` (default + `~/.local/share/horizon`), `--bin` (default `~/.local/bin`), and `--archive FILE` to install an archive + already on the machine (a build of your own; no download and no checksum). + A Linux release from before the server archive installs the full game, which links ALSA's and udev's + libraries (`libasound.so.2`, `libudev.so.1`); minimal server images often lack them (Debian and Ubuntu: + `sudo apt install libasound2 libudev1`, `libasound2t64` on Ubuntu 24.04 and later). Then the script lists + any that are missing, `init` warns, and `run` stops at once with what to install, rather than restarting + a game that can't load. - Windows: `irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex` The script does the same into `%LOCALAPPDATA%\Horizon` (`-Version`, `-Dir`), with junctions instead of @@ -196,8 +213,8 @@ comes out of the headless-engine work. (`horizon-prepare`, `horizon-server init`). **Docker** (`packaging/server/Dockerfile`, built the same way as the relay's image): a multi-stage build that -ends on `debian:bookworm-slim` as user `horizon`. It adds `libasound2` and `libudev1` until the headless engine -lands. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only +ends on `debian:bookworm-slim` as user `horizon`, with the server build as `horizon-engine`, so the image needs +no ALSA or udev. It uses volume `/data` for the server folder, takes the owner's prepared game files as a read-only mount on `/opt/horizon/.local/horizon-client/26.3`, exposes port `25565/tcp`, and keeps the control API (and later the panel) on 127.0.0.1 inside the container: `docker exec <name> horizon-server status|cmd|backup`. On the first start, `HORIZON_EULA=true` and `HORIZON_WORLD`, `HORIZON_SEED`, `HORIZON_PORT`, @@ -480,6 +497,30 @@ reproducible by anyone, and show the same gameplay on both sides. and every packet woke its connection's writer thread (#649). Together they took the 50-bot walking tick from 281 ms to 31 ms. At 25 walking bots most of what remains is the engine's streaming and block entity ticks, both of which grow with players (the README has the profile). +- **Mixed bots, as installed (2026-10-18,** `benchmarks/server-mixed-2026-10-18/`, the first published + run for the working version). It used the v2026.10.18.15 release as `install.sh` installs it, against + vanilla 26.3, with 1, 10, 25 and 50 `mixed` bots and vanilla's default game rules on both (Horizon has + the locator bar now). The servers ran on the ThinkPad and the bots on the Mac mini. Results: + - Both kept 20 TPS in every run. + - Horizon's RSS was 3.7 to 5.2 times smaller (1.0 GB against 4.0 GB at 50). + - Horizon's average tick was shorter with 1, 10 and 25 bots (2.4 against 17.9 ms, 12.4 against 34.5, + 24.0 against 31.6) and longer with 50 (35.2 against 29.7). Its P99 was lower at every count. + - Horizon also did more work: it kept up with the exploring bots, so it generated 1.9 to 2.9 times + the new terrain a second. +- **Mixed bots, equal work (2026-10-18,** `benchmarks/server-equal-mixed-2026-10-18/`). This is the same + run with the load made equal. The explore bots fly at 0.8 blocks a second, so every bot follows the same + path on both servers and none waits for terrain. A 300-second warm-up lets both finish the bots' first + views before the measurement. `server_bench.py` now prints a work table that compares each count's chunks + a second across servers and flags a run that isn't equal. Horizon ran as `horizon-engine`, the server + build, installed from its archive. Results, on the ThinkPad again (the desktop didn't wake): + - The work was equal at 1 and 10 bots. At 25 the chunks sent a second were equal (158.6 against 157.6), + and vanilla still sent 2.5 more first-time chunks a second while it caught up. + - Tick: 1.8 against 11.3 ms at 1 bot, 4.7 against 34.3 at 10, 11.7 against 50.5 at 25 (vanilla 19.8 TPS). + At 50 Horizon ran at 23.8 ms. Vanilla's watchdog stopped its server 30 s after the last bot joined (a + 60-second tick). This is one pass, to repeat on a bigger machine. + - Horizon's RSS was 4.1 to 4.9 times smaller (1.03 GB at 50). + - Served in full, vanilla's walking bots got 5400 to 6100 chunks each, against 640 to 1100 in the first + run. That is why vanilla held 50 bots there and not here. - **Ownership.** perf-server-1 owns making the tick faster. This work only measures it, files what it finds, and fixes startup, RAM and packaging. @@ -498,7 +539,8 @@ vanilla. archive in the release. 3. The web panel MVP: status, live TPS/MSPT/RAM/CPU, players, console, backups and login links. 4. `horizon-bots` and `tools/server_bench.py`, with a first run against vanilla (1/10/25/50 bots, `mixed`) - published in `benchmarks/`. + published in `benchmarks/`: done, `benchmarks/server-mixed-2026-10-18/`, and with equal work + `benchmarks/server-equal-mixed-2026-10-18/` (section 9). 5. Small engine fixes found on the way: logging refused logins (vanilla's lines). **Where it stands (2026-10-16):** items 1 to 4 are built and in review (section 11). What's left for the 23rd: diff --git a/launcher/src/modpacks.rs b/launcher/src/modpacks.rs index 6ff53e4be..b69ff0976 100644 --- a/launcher/src/modpacks.rs +++ b/launcher/src/modpacks.rs @@ -241,8 +241,14 @@ mod tests { .map(|a| a.to_string_lossy().into_owned()) .collect(); assert_eq!(args.len(), 4); - assert_eq!(Path::new(&args[1]), work.join("mods").join("a").join("carry")); - assert_eq!(Path::new(&args[3]), work.join("mods").join("b").join("carry")); + assert_eq!( + Path::new(&args[1]), + work.join("mods").join("a").join("carry") + ); + assert_eq!( + Path::new(&args[3]), + work.join("mods").join("b").join("carry") + ); assert_eq!(cmd.get_current_dir(), Some(profile_home(&work).as_path())); assert!(profile_home(&work).is_dir()); fs::remove_dir_all(&root).unwrap(); diff --git a/launcher/src/sources_tests.rs b/launcher/src/sources_tests.rs index b273fa4ba..6d882f032 100644 --- a/launcher/src/sources_tests.rs +++ b/launcher/src/sources_tests.rs @@ -203,6 +203,35 @@ fn prism_launcher_and_multimc_are_read_through_their_metadata() { assert_eq!(mojang.urls.lock().unwrap().len(), 1); } +/// famescare's Prism Launcher 26.3 install on Windows (#849): Prism keeps a native jar under +/// the name its metadata gives it, not at the version JSON's path, and preparing found it. +#[test] +fn prism_native_jars_are_found_through_the_linked_folder() { + let s = Scratch::new("prism-natives"); + let jar = "libraries/com/mojang/minecraft/26.3/minecraft-26.3-client.jar"; + let dir = s.launcher("PrismLauncher", "", jar); + s.write( + "PrismLauncher/meta/net.minecraft/26.3.json", + br#"{"mainJar": {"name": "com.mojang:minecraft:26.3:client"}}"#, + ); + let prism = + "libraries/com/mojang/jtracy-natives-windows/1.14.38/jtracy-natives-windows-1.14.38.jar"; + s.write(&format!("PrismLauncher/{prism}"), b"jtracy natives"); + let linked = s.0.join("linked"); + assert_eq!( + resolve_with(&dir, &[], &linked, &Mojang::new(MANIFEST)).unwrap(), + linked + ); + let official = Path::new("com/mojang/jtracy/1.14.38/jtracy-1.14.38-natives-windows.jar"); + assert!(!linked.join("libraries").join(official).exists()); + let found = horizon_prepare::artifacts::launcher_library( + &linked, + "com.mojang:jtracy:1.14.38:natives-windows", + official, + ); + assert!(same_file(&found, &dir.join(prism))); +} + #[test] fn a_main_jar_elsewhere_is_found_from_the_metadata() { let s = Scratch::new("meta-jar"); @@ -388,7 +417,10 @@ fn relinking_follows_the_launcher_the_files_now_come_from() { s.write("ModrinthApp/meta/versions/26.3/26.3.jar", CLIENT); resolve_with(&modrinth, &[], &linked, &mojang).unwrap(); let jar = linked.join("versions/26.3/26.3.jar"); - assert!(same_file(&jar, &modrinth.join("meta/versions/26.3/26.3.jar"))); + assert!(same_file( + &jar, + &modrinth.join("meta/versions/26.3/26.3.jar") + )); assert!(!same_file(&jar, &prism.join(prism_jar))); // The Modrinth App folder has no libraries or assets: the old links are gone, and the // folders they pointed at are untouched. diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java b/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java index ffac86a59..09c343f16 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/EntityTranscript.java @@ -30,7 +30,8 @@ import net.minecraft.world.phys.Vec3; * equipment, attributes and passengers, and where the position syncs leave * it (VecDeltaCodec, as handleMoveEntity and handleEntityPositionSync). * Entity ids differ between servers: an entity is named by its type and the - * block it was added in, passengers by those names. Players are left out. + * block it was added in, passengers by those names. Players are left out, but + * for the attributes the player itself is sent from its login on. */ final class EntityTranscript { private static final class Tracked { @@ -67,6 +68,21 @@ final class EntityTranscript { private final Map<Integer, Tracked> byId = new HashMap<>(); private final List<Tracked> all = new ArrayList<>(); + private int self = Integer.MIN_VALUE; + private final Map<String, String> selfAttributes = new TreeMap<>(); + + /** The player's own id (login) and attribute instances; false for any other packet. */ + boolean acceptSelf(Packet<?> packet) { + if (packet instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket p) { + self = p.playerId(); + return true; + } + if (packet instanceof ClientboundUpdateAttributesPacket p && p.getEntityId() == self) { + p.getValues().forEach(a -> selfAttributes.put(a.attribute().getRegisteredName(), a.base() + " " + a.modifiers())); + return true; + } + return false; + } private int unknown; /** Applies one packet; false when it isn't about a tracked entity. */ @@ -158,6 +174,7 @@ final class EntityTranscript { + " | attributes " + t.attributes + " | passengers " + riders + " | now " + t.codec.getBase() + " rot " + t.xRot + "," + t.yRot + " head " + t.headRot + " ground " + t.onGround + " motion " + t.motion + t.power + (t.removed ? " | removed" : "")); } + out.add("self attributes " + selfAttributes); out.sort(null); return out; } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java index e2de1b004..3eb241d5e 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java @@ -82,13 +82,16 @@ import net.minecraft.world.phys.Vec3; * players on|off} (whether each player also records the other players added * to and removed from its level, and its own respawns into a dimension), * {@code chat on|off} (whether the system chat each player receives is - * recorded too, as component JSON) and {@code end}, which writes each + * recorded too, as component JSON), {@code state on|off} (whether each player + * also records what the server changes about it: its game mode, teleports, + * inventory slots, effects and death) and {@code end}, which writes each * player's lines to OUT. */ public final class LocatorBarClient { private static volatile String step = "start"; private static volatile boolean players; private static volatile boolean chat; + private static volatile boolean state; private static final Map<UUID, String> NAMES = new LinkedHashMap<>(); public static void main(String[] args) throws Exception { @@ -122,6 +125,7 @@ public final class LocatorBarClient { case "quit" -> players.get(w[1]).close(); case "players" -> LocatorBarClient.players = w[1].equals("on"); case "chat" -> chat = w[1].equals("on"); + case "state" -> state = w[1].equals("on"); case "end" -> { try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(output, StandardCharsets.UTF_8))) { for (Player p : players.values()) { @@ -179,6 +183,8 @@ public final class LocatorBarClient { private ProtocolInfo<?> outbound; private volatile PositionMoveRotation position = new PositionMoveRotation(Vec3.ZERO, Vec3.ZERO, 0, 0); private boolean loaded; + /** This player's own entity id (ClientboundLoginPacket). */ + private volatile int id = -1; /** The other players this one was sent, by entity id. */ private final Map<Integer, String> seen = new java.util.HashMap<>(); private final Object replyLock = new Object(); @@ -287,6 +293,10 @@ public final class LocatorBarClient { while (true) { Received r = read(); Packet<?> p = r.packet; + if (p instanceof net.minecraft.network.protocol.game.ClientboundLoginPacket l) { + id = l.playerId(); + } + if (state) recordState(p); if (p instanceof net.minecraft.network.protocol.game.ClientboundAddEntityPacket a && a.getType() == net.minecraft.world.entity.EntityTypes.PLAYER) { String who = NAMES.getOrDefault(a.getUUID(), "uuid?"); @@ -319,6 +329,10 @@ public final class LocatorBarClient { } else if (p instanceof ClientboundPlayerPositionPacket t) { position = PositionMoveRotation.calculateAbsolute(position, t.change(), t.relatives()); Vec3 at = position.position(); + if (state) { + record(String.format(java.util.Locale.ROOT, "teleport %.3f %.3f %.3f %.1f %.1f", + at.x, at.y, at.z, position.yRot(), position.xRot())); + } send(new ServerboundAcceptTeleportationPacket(t.id(), at.x, at.y, at.z, position.yRot(), position.xRot())); // Only the spawn teleport is answered with a position too (VanillaProtocolClient). if (!loaded) { @@ -338,6 +352,31 @@ public final class LocatorBarClient { } } + /** What the server changed about this player ({@code state on}). */ + private void recordState(Packet<?> p) { + if (p instanceof net.minecraft.network.protocol.game.ClientboundGameEventPacket g + && g.getEvent() == net.minecraft.network.protocol.game.ClientboundGameEventPacket.CHANGE_GAME_MODE) { + record("gamemode " + (int) g.getParam()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundContainerSetSlotPacket c) { + record("slot " + c.getContainerId() + " " + c.getSlot() + " " + item(c.getItem())); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundSetPlayerInventoryPacket i) { + record("inventory " + i.slot() + " " + item(i.contents())); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundUpdateMobEffectPacket e && e.getEntityId() == id) { + record("effect " + e.getEffect().getRegisteredName() + " " + e.getEffectAmplifier() + " " + e.getEffectDurationTicks()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundRemoveMobEffectPacket e && e.entityId() == id) { + record("effect-removed " + e.effect().getRegisteredName()); + } else if (p instanceof net.minecraft.network.protocol.game.ClientboundPlayerCombatKillPacket k) { + record("killed " + net.minecraft.network.chat.ComponentSerialization.CODEC + .encodeStart(ParityData.access.createSerializationContext(com.mojang.serialization.JsonOps.INSTANCE), k.message()) + .getOrThrow()); + } + } + + private static String item(net.minecraft.world.item.ItemStack stack) { + return stack.isEmpty() ? "empty" + : net.minecraft.core.registries.BuiltInRegistries.ITEM.getKey(stack.getItem()) + " x" + stack.getCount(); + } + private record Received(Packet<?> packet, byte[] payload) {} private Received read() throws Exception { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java index 4b61558d8..8c6225401 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaCommandExecOracle.java @@ -222,6 +222,7 @@ public final class VanillaCommandExecOracle { } } case "settle" -> settle(); + case "portal" -> portal(); default -> throw new IllegalArgumentException(line); } } @@ -278,6 +279,23 @@ public final class VanillaCommandExecOracle { } /** Force-load the chunks around the player (Horizon waits for its streamed terrain). */ + /** + * Entity.handlePortal once the player's portal process finished in the + * nether portal it stands in (the oracle does not tick the player). + */ + void portal() { + ServerLevel level = player.level(); + net.minecraft.core.BlockPos entry = player.blockPosition(); + if (!level.getBlockState(entry).is(net.minecraft.world.level.block.Blocks.NETHER_PORTAL)) { + throw new IllegalStateException("portal: the player is not in a nether portal"); + } + var block = (net.minecraft.world.level.block.NetherPortalBlock) net.minecraft.world.level.block.Blocks.NETHER_PORTAL; + var transition = block.getPortalDestination(level, player, entry); + if (transition != null) { + player.teleportToPortalDestination(level, transition); + } + } + void settle() { ServerLevel level = player.level(); int cx = player.chunkPosition().x(), cz = player.chunkPosition().z(); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java index 19779739b..2002285e3 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaDispenserOracle.java @@ -170,14 +170,82 @@ public final class VanillaDispenserOracle { throw new IllegalStateException("no slots in " + be); } - /** The removal a "remove" case runs on the block at its origin. */ - static void remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) { + /** The removal a "remove" case runs on the block at its origin; a player's mining prints its statistics and held stack. */ + static List<String> remove(VanillaBlockUpdateOracle.World w, BlockPos origin, JsonObject op) throws Exception { switch (op.get("op").getAsString()) { case "set" -> w.setBlock(origin, Block.stateById(op.get("state").getAsInt()), op.get("flags").getAsInt()); case "destroy" -> w.destroyBlock(origin, op.get("drop").getAsBoolean()); case "remove" -> w.removeBlock(origin, false); + case "mine" -> { + return mine(w, origin, op); + } default -> throw new IllegalStateException(op.toString()); } + return new ArrayList<>(); + } + + /** + * A survival player three blocks south of `pos` mines it holding the case's + * item: the real `ServerPlayerGameMode.destroyBlock` (playerWillDestroy, + * removeBlock with the block entity's side effects, mineBlock, playerDestroy's + * statistic, exhaustion and drops). The statistics and the held stack follow. + */ + static List<String> mine(VanillaBlockUpdateOracle.World w, BlockPos pos, JsonObject op) throws Exception { + Miner player = (Miner) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, Miner.class); + player.world = w; + player.hand = stack(op.get("item").getAsString()); + player.offhand = ItemStack.EMPTY; + player.stats = new ArrayList<>(); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "abilities", new net.minecraft.world.entity.player.Abilities()); + VanillaBlockUpdateOracle.set(net.minecraft.world.entity.player.Player.class, player, "foodData", new net.minecraft.world.food.FoodData()); + var advancements = (net.minecraft.server.PlayerAdvancements) VanillaBlockUpdateOracle.allocate.invoke(VanillaBlockUpdateOracle.unsafe, net.minecraft.server.PlayerAdvancements.class); + VanillaBlockUpdateOracle.set(net.minecraft.server.PlayerAdvancements.class, advancements, "activeTriggers", new HashMap<>()); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayer.class, player, "advancements", advancements); + var at = net.minecraft.world.phys.Vec3.atBottomCenterOf(pos).add(0, 1, 3); + VanillaBlockUpdateOracle.set(Entity.class, player, "position", at); + VanillaBlockUpdateOracle.set(Entity.class, player, "blockPosition", BlockPos.containing(at)); + // PiglinAi.angerNearbyPiglins looks around the player's box (gold, chests, barrels...). + player.setBoundingBox(EntityTypes.PLAYER.getDimensions().makeBoundingBox(at)); + var gameMode = new net.minecraft.server.level.ServerPlayerGameMode(player); + VanillaBlockUpdateOracle.set(net.minecraft.server.level.ServerPlayerGameMode.class, gameMode, "gameModeForPlayer", + net.minecraft.world.level.GameType.SURVIVAL); + gameMode.destroyBlock(pos); + List<String> out = new ArrayList<>(player.stats); + out.add("mine held " + ParityData.canon(player.hand)); + return out; + } + + /** The player of a "mine" case: a survival `Clicker` whose selected inventory slot is its main hand. */ + static final class Miner extends net.minecraft.server.level.ServerPlayer { + VanillaBlockUpdateOracle.World world; + ItemStack hand, offhand; + List<String> stats; + Miner() { + super(null, null, null, null); + } + @Override public ServerLevel level() { return world; } + @Override public boolean hasInfiniteMaterials() { return false; } + @Override public boolean isCreative() { return false; } + @Override public boolean isSpectator() { return false; } + @Override public EntityType<?> getType() { return EntityTypes.PLAYER; } + @Override public net.minecraft.core.Holder<EntityType<?>> typeHolder() { return EntityTypes.PLAYER.builtInRegistryHolder(); } + @Override public ItemStack getItemBySlot(EquipmentSlot slot) { + return slot == EquipmentSlot.MAINHAND ? hand : slot == EquipmentSlot.OFFHAND ? offhand : ItemStack.EMPTY; + } + @Override public void setItemSlot(EquipmentSlot slot, ItemStack stack) { + if (slot == EquipmentSlot.MAINHAND) hand = stack; else if (slot == EquipmentSlot.OFFHAND) offhand = stack; + } + @Override public ItemStack getItemInHand(net.minecraft.world.InteractionHand h) { + return h == net.minecraft.world.InteractionHand.MAIN_HAND ? hand : offhand; + } + // Player.hasCorrectToolForDrops asks the inventory's selected slot: the main hand. + @Override public boolean hasCorrectToolForDrops(BlockState state) { + return !state.requiresCorrectToolForDrops() || hand.isCorrectToolForDrops(state); + } + @Override public void awardStat(net.minecraft.stats.Stat<?> stat, int count) { + stats.add("stat " + User.key(stat) + " " + BuiltInRegistries.STAT_TYPE.getKey(stat.getType()) + " " + count); + } + @Override public net.minecraft.server.players.NameAndId nameAndId() { return new net.minecraft.server.players.NameAndId(new UUID(0L, 0L), "Player"); } } static boolean hasList(Object be) { @@ -324,7 +392,7 @@ public final class VanillaDispenserOracle { BlockState state = w.getBlockState(origin); List<String> used = new ArrayList<>(); if (f.has("remove")) { - remove(w, origin, f.getAsJsonObject("remove")); + used = remove(w, origin, f.getAsJsonObject("remove")); } else if (f.has("use")) { used = use(w, origin, f.getAsJsonObject("use")); } else if (f.has("use_item")) { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java index 0be89888a..294ceacac 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGameLoopOracle.java @@ -118,13 +118,14 @@ public final class VanillaGameLoopOracle { static final class StubPlayer extends LocalPlayer { boolean scoping; + boolean spectator; StubPlayer() { super(null, null, null, null, null, Input.EMPTY, false, null, null); } @Override public boolean isScoping() { return scoping; } - @Override public boolean isSpectator() { return false; } + @Override public boolean isSpectator() { return spectator; } } static Minecraft shell; @@ -327,6 +328,12 @@ public final class VanillaGameLoopOracle { StubPlayer player = make(StubPlayer.class); Inventory inventory = make(Inventory.class); inventory.setSelectedSlot(c.get("slot").getAsInt()); + player.spectator = c.has("spectator") && c.get("spectator").getAsBoolean(); + field(net.minecraft.world.entity.player.Player.class, "abilities").set(player, new net.minecraft.world.entity.player.Abilities()); + var hud = make(net.minecraft.client.gui.Hud.class); + field(net.minecraft.client.gui.Hud.class, "spectatorGui").set(hud, + make(net.minecraft.client.gui.components.spectator.SpectatorGui.class)); + field(Gui.class, "hud").set(mc.gui, hud); field(net.minecraft.world.entity.player.Player.class, "inventory").set(player, inventory); mc.player = player; options.discreteMouseScroll().set(c.get("discrete").getAsBoolean()); @@ -336,7 +343,7 @@ public final class VanillaGameLoopOracle { for (var e : c.getAsJsonArray("ops")) { var op = e.getAsJsonArray(); h.onScroll(1L, d(op.get(0)), d(op.get(1))); - out.println(inventory.getSelectedSlot()); + out.println(inventory.getSelectedSlot() + (player.spectator ? " " + fb(player.getAbilities().getFlyingSpeed()) : "")); } } diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java new file mode 100644 index 000000000..884e5042a --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaInteractionInputOracle.java @@ -0,0 +1,161 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.*; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.multiplayer.*; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.*; +import net.minecraft.network.protocol.Packet; +import net.minecraft.world.*; +import net.minecraft.world.entity.*; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.flag.*; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.component.SwingAnimation; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.border.WorldBorder; +import net.minecraft.world.phys.*; + +/** Runs the shipped handleKeybinds; only game-mode effects and UI are shells. */ +public final class VanillaInteractionInputOracle { + static Object unsafe; + static Method allocate; + static List<String> events = new ArrayList<>(); + static Field field(Class<?> type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static <T> T make(Class<T> type) throws Exception { return type.cast(allocate.invoke(unsafe, type)); } + public static class MC extends Minecraft { + public MC() { super(null); } + @Override public boolean hasControlDown() { return false; } + } + public static class UI extends Gui { + public UI() { super(null, null, null); } + @Override public void handleKeybinds() {} + } + public static class Mouse extends MouseHandler { + public Mouse() { super(null); } + @Override public boolean isMouseGrabbed() { return true; } + } + public static class Level extends ClientLevel { + public Level() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + @Override public BlockState getBlockState(BlockPos pos) { return Blocks.STONE.defaultBlockState(); } + @Override public FeatureFlagSet enabledFeatures() { return FeatureFlags.REGISTRY.allFlags(); } + } + public static class Connection extends ClientPacketListener { + public Connection() { super(null, null, null); } + @Override public void send(Packet<?> packet) {} + } + public static class Human extends LocalPlayer { + boolean using; + ItemStack held = ItemStack.EMPTY; + public Human() { super(null, null, null, null, null, null, false, null, null); } + @Override public boolean isUsingItem() { return using; } + @Override public boolean isSpectator() { return false; } + @Override public boolean isCreative() { return false; } + @Override public boolean isHandsBusy() { return false; } + @Override public ItemStack getItemInHand(InteractionHand hand) { + return hand == InteractionHand.MAIN_HAND ? held : ItemStack.EMPTY; + } + @Override public void itemUsed(InteractionHand hand) {} + @Override public boolean cannotAttackWithItem(ItemStack item, int slot) { return false; } + @Override public boolean isWithinEntityInteractionRange(Entity e, double buffer) { return true; } + @Override public boolean swing(InteractionHand hand, SwingAnimation animation, boolean send) { return false; } + } + public static class Mode extends MultiPlayerGameMode { + boolean destroying, digOnAttack, beginUsing, passing; + Human player; + public Mode() { super(null, null); } + @Override public boolean isDestroying() { return destroying; } + @Override public boolean isSpectator() { return false; } + @Override public boolean startDestroyBlock(BlockPos pos, Direction face) { + events.add("attack"); destroying = digOnAttack; return true; + } + @Override public boolean continueDestroyBlock(BlockPos pos, Direction face) { + events.add("continue true"); return true; + } + @Override public void stopDestroyBlock() { events.add("continue false"); destroying = false; } + @Override public void attack(Player p, Entity e) { events.add("attack"); } + @Override public void releaseUsingItem(Player p) { events.add("release"); player.using = false; } + InteractionResult use() { events.add("use"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER; } + @Override public InteractionResult useItemOn(LocalPlayer p, InteractionHand h, BlockHitResult hit) { + if (passing) { events.add("block"); return InteractionResult.PASS; } + return use(); + } + @Override public InteractionResult interact(Player p, Entity e, EntityHitResult hit, InteractionHand h) { + if (passing) { events.add("entity"); return InteractionResult.PASS; } + return use(); + } + @Override public InteractionResult useItem(Player p, InteractionHand h) { + events.add("item"); player.using = beginUsing; return InteractionResult.SUCCESS_SERVER; + } + @Override public void handlePickItemFromBlock(BlockPos pos, boolean data) { events.add("pick"); } + @Override public void handlePickItemFromEntity(Entity entity, boolean data) { events.add("pick"); } + } + static boolean flag(JsonObject row, String name) { return row.get(name).getAsBoolean(); } + public static void main(String[] args) throws Exception { + ParityData.init(); + var u = Class.forName("sun.misc.Unsafe"); unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + var handle = Minecraft.class.getDeclaredMethod("handleKeybinds"); handle.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + int i = 0; + for (String line : (Iterable<String>) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + var mc = make(MC.class); var options = make(Options.class); + for (var f : Options.class.getDeclaredFields()) { + if (Modifier.isStatic(f.getModifiers())) continue; + f.setAccessible(true); + if (f.getType() == KeyMapping.class) f.set(options, make(KeyMapping.class)); + if (f.getType() == KeyMapping[].class) { + var keys = new KeyMapping[9]; + for (int n = 0; n < keys.length; n++) keys[n] = make(KeyMapping.class); + f.set(options, keys); + } + } + var player = make(Human.class); player.using = flag(row, "using"); + boolean passing = row.has("passing") && flag(row, "passing"); + player.held = passing ? new ItemStack(Blocks.STONE.asItem()) : ItemStack.EMPTY; + var level = make(Level.class); + field(ClientLevel.class, "worldBorder").set(level, new WorldBorder()); + field(Player.class, "abilities").set(player, new Abilities()); + field(LocalPlayer.class, "connection").set(player, make(Connection.class)); + var mode = make(Mode.class); mode.player = player; + mode.destroying = flag(row, "destroying"); mode.digOnAttack = flag(row, "dig_on_attack"); + mode.beginUsing = flag(row, "begin_using"); + mode.passing = passing; + field(Minecraft.class, "options").set(mc, options); + field(Minecraft.class, "gui").set(mc, make(UI.class)); + field(Minecraft.class, "mouseHandler").set(mc, make(Mouse.class)); + field(Minecraft.class, "player").set(mc, player); + field(Minecraft.class, "level").set(mc, level); + field(Minecraft.class, "gameMode").set(mc, mode); + var entity = make(net.minecraft.world.entity.item.ItemEntity.class); + field(Entity.class, "blockPosition").set(entity, BlockPos.ZERO); + field(Minecraft.class, "hitResult").set(mc, flag(row, "entity") + ? new EntityHitResult(entity, Vec3.ZERO) + : new BlockHitResult(Vec3.ZERO, Direction.UP, BlockPos.ZERO, false)); + String[] names = {"keyAttack", "keyUse", "keyPickItem"}; + for (var click : row.getAsJsonArray("clicks")) { + var key = (KeyMapping)field(Options.class, names[click.getAsInt()]).get(options); + var count = field(KeyMapping.class, "clickCount"); + count.setInt(key, count.getInt(key) + 1); + } + field(KeyMapping.class, "isDown").setBoolean(options.keyAttack, flag(row, "attack_down")); + field(KeyMapping.class, "isDown").setBoolean(options.keyUse, flag(row, "use_down")); + field(Minecraft.class, "rightClickDelay").setInt(mc, row.get("delay").getAsInt()); + events.clear(); handle.invoke(mc); + out.println("== " + i++); + for (String event : events) out.println(event); + out.println("state " + player.using + " " + mode.destroying + " " + field(Minecraft.class, "rightClickDelay").getInt(mc)); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java new file mode 100644 index 000000000..056240bb8 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaPlayerSyncOracle.java @@ -0,0 +1,109 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import io.netty.buffer.Unpooled; +import java.io.PrintWriter; +import java.lang.reflect.*; +import java.nio.file.*; +import java.util.HexFormat; +import net.minecraft.client.*; +import net.minecraft.client.multiplayer.ClientPacketListener; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.network.FriendlyByteBuf; +import net.minecraft.network.protocol.Packet; +import net.minecraft.network.protocol.game.ServerboundMovePlayerPacket; +import net.minecraft.world.entity.*; +import net.minecraft.world.phys.Vec3; + +/** Runs shipped methods; only the world lifecycle and packet sink are fixtures. */ +public final class VanillaPlayerSyncOracle { + static Object unsafe; + static Method allocate; + static PrintWriter out; + static Field field(Class<?> type, String name) throws Exception { + var f = type.getDeclaredField(name); f.setAccessible(true); return f; + } + static <T> T make(Class<T> type) throws Exception { + return type.cast(allocate.invoke(unsafe, type)); + } + public static final class Player extends LocalPlayer { + boolean ground; + public Player() { super(null, null, null, null, null, null, false, null, null); } + @Override protected boolean isControlledCamera() { return true; } + @Override public boolean isSprinting() { return false; } + @Override public boolean onGround() { return ground; } + } + public static final class Sink extends ClientPacketListener { + boolean sent; + public Sink() { super(null, null, null); } + @Override public void send(Packet<?> packet) { + sent = true; + var buf = new FriendlyByteBuf(Unpooled.buffer()); + String name; + try { + if (packet instanceof ServerboundMovePlayerPacket.PosRot p) { + name = "posrot"; ServerboundMovePlayerPacket.PosRot.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.Pos p) { + name = "pos"; ServerboundMovePlayerPacket.Pos.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.Rot p) { + name = "rot"; ServerboundMovePlayerPacket.Rot.STREAM_CODEC.encode(buf, p); + } else if (packet instanceof ServerboundMovePlayerPacket.StatusOnly p) { + name = "status"; ServerboundMovePlayerPacket.StatusOnly.STREAM_CODEC.encode(buf, p); + } else { throw new AssertionError(packet); } + byte[] bytes = new byte[buf.readableBytes()]; buf.readBytes(bytes); + out.println(name + " " + HexFormat.of().formatHex(bytes)); + } finally { buf.release(); } + } + } + static double number(JsonElement value) { + return Double.longBitsToDouble(Long.parseUnsignedLong(value.getAsString(), 16)); + } + static Vec3 vector(JsonObject row, String key) { + var a = row.getAsJsonArray(key); + return new Vec3(number(a.get(0)), number(a.get(1)), number(a.get(2))); + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + var sendPosition = LocalPlayer.class.getDeclaredMethod("sendPosition"); + sendPosition.setAccessible(true); + var minecraft = make(Minecraft.class); + var options = make(Options.class); + field(Options.class, "autoJump").set(options, OptionInstance.createBoolean("test", false)); + field(Minecraft.class, "options").set(minecraft, options); + try (var output = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]))); + var lines = Files.lines(Path.of(args[0]))) { + out = output; + for (String line : (Iterable<String>) lines::iterator) { + var row = JsonParser.parseString(line).getAsJsonObject(); + if (row.get("kind").getAsString().equals("movement")) { + var p = make(Player.class); + var sink = make(Sink.class); + field(LocalPlayer.class, "connection").set(p, sink); + field(LocalPlayer.class, "minecraft").set(p, minecraft); + for (var value : row.getAsJsonArray("ops")) { + var op = value.getAsJsonArray(); + field(Entity.class, "position").set(p, new Vec3(number(op.get(0)), number(op.get(1)), number(op.get(2)))); + field(Entity.class, "yRot").setFloat(p, (float)number(op.get(3))); + field(Entity.class, "xRot").setFloat(p, (float)number(op.get(4))); + p.ground = op.get(5).getAsBoolean(); + p.horizontalCollision = op.get(6).getAsBoolean(); + sink.sent = false; + sendPosition.invoke(p); + if (!sink.sent) out.println("-"); + } + } else { + var old = row.getAsJsonArray("old"); + var next = row.getAsJsonArray("new"); + var base = new PositionMoveRotation(Vec3.ZERO, vector(row, "velocity"), (float)number(old.get(0)), (float)number(old.get(1))); + var change = new PositionMoveRotation(Vec3.ZERO, vector(row, "delta"), (float)number(next.get(0)), (float)number(next.get(1))); + var v = PositionMoveRotation.calculateAbsolute(base, change, Relative.unpack(row.get("flags").getAsInt())).deltaMovement(); + out.printf("%016x %016x %016x%n", Double.doubleToRawLongBits(v.x), Double.doubleToRawLongBits(v.y), Double.doubleToRawLongBits(v.z)); + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java index ca366705b..b15720848 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaProtocolClient.java @@ -476,7 +476,7 @@ public final class VanillaProtocolClient { if (r != null) { Packet<?> packet = r.packet; counts.merge(r.type, 1, Integer::sum); - if (entities != null && step >= ENTITIES) entities.accept(packet); + if (entities != null && !entities.acceptSelf(packet) && step >= ENTITIES) entities.accept(packet); if (r.type.equals("minecraft:chunk_batch_start")) ordered = false; if (respawning && !respawned) { String line = respawnLine(r); diff --git a/packaging/server/Dockerfile b/packaging/server/Dockerfile index bbb74ba26..5ae395205 100644 --- a/packaging/server/Dockerfile +++ b/packaging/server/Dockerfile @@ -13,20 +13,15 @@ # start writes /data/server.toml from HORIZON_* (EULA, WORLD, SEED, PORT, WHITELIST, PLAYERS, OP); later # starts use the file. Manage it with `docker exec horizon horizon-server status|cmd|backup|logs ...`. FROM rust:1-slim-bookworm AS build -RUN apt-get update \ - && apt-get install -y --no-install-recommends pkg-config libasound2-dev libudev-dev \ - && rm -rf /var/lib/apt/lists/* WORKDIR /src COPY . . -RUN cargo build --release --locked -p horizon-client --bin horizon-client -p horizon-server --bin horizon-server \ - && mkdir /out && cp target/release/horizon-client target/release/horizon-server /out/ +# The server build of the game (no sound, no controllers: it needs neither ALSA nor udev) as horizon-engine. +RUN cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client \ + && cargo build --release --locked -p horizon-server --bin horizon-server \ + && mkdir /out && cp target/release/horizon-client /out/horizon-engine && cp target/release/horizon-server /out/ FROM debian:bookworm-slim -# The game links ALSA and udev even when it runs headless with no sound. -RUN apt-get update \ - && apt-get install -y --no-install-recommends libasound2 libudev1 \ - && rm -rf /var/lib/apt/lists/* \ - && useradd --system --home-dir /data --shell /usr/sbin/nologin horizon \ +RUN useradd --system --home-dir /data --shell /usr/sbin/nologin horizon \ && mkdir -p /data /opt/horizon/.local/horizon-client \ && chown horizon:horizon /data COPY --from=build /out/ /opt/horizon/ diff --git a/packaging/server/install.sh b/packaging/server/install.sh index 221fcf0a8..eed312c74 100755 --- a/packaging/server/install.sh +++ b/packaging/server/install.sh @@ -1,9 +1,11 @@ #!/bin/sh # Installs horizon-server (docs/server.md) on Linux or macOS: the latest Horizon release for this computer, -# downloaded from GitHub Releases and checked against the SHA-256 GitHub publishes for it. +# downloaded from GitHub Releases and checked against the SHA-256 GitHub publishes for it. On Linux that is +# the server build (horizon-server-linux-x86_64.tar.gz), which needs neither ALSA nor udev. # # curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh # curl -fsSL .../install.sh | sh -s -- --version v0.5.0 --dir /opt/horizon --bin /usr/local/bin +# sh install.sh --archive horizon-server-linux-x86_64.tar.gz --version mybuild (an archive you have) # # It needs curl, tar or unzip, and sha256sum or shasum; it never asks for sudo (pick folders you can write). # Releases go to <dir>/releases/<version>, <dir>/current points at the one in use, and <bin>/horizon-server @@ -15,6 +17,7 @@ REPO=ludovic111/horizon VERSION=latest DIR="${XDG_DATA_HOME:-$HOME/.local/share}/horizon" BIN="$HOME/.local/bin" +ARCHIVE= die() { echo "horizon install: $*" >&2; exit 1; } @@ -23,45 +26,58 @@ while [ $# -gt 0 ]; do --version) [ $# -ge 2 ] || die "--version needs a tag"; VERSION=$2; shift 2 ;; --dir) [ $# -ge 2 ] || die "--dir needs a folder"; DIR=$2; shift 2 ;; --bin) [ $# -ge 2 ] || die "--bin needs a folder"; BIN=$2; shift 2 ;; - -h|--help) sed -n '2,12p' "$0" 2>/dev/null || true; exit 0 ;; + --archive) [ $# -ge 2 ] || die "--archive needs a file"; ARCHIVE=$2; shift 2 ;; + -h|--help) sed -n '2,14p' "$0" 2>/dev/null || true; exit 0 ;; *) die "unknown option $1" ;; esac done +# The archives to look for, in order: on Linux the server build, else (releases before it) the full game. case "$(uname -s)-$(uname -m)" in - Linux-x86_64) ASSET=horizon-linux-x86_64.tar.gz ;; - Darwin-arm64) ASSET=horizon-macos-arm64.zip ;; + Linux-x86_64) ASSETS="horizon-server-linux-x86_64.tar.gz horizon-linux-x86_64.tar.gz" ;; + Darwin-arm64) ASSETS=horizon-macos-arm64.zip ;; *) die "no Horizon release for $(uname -s) $(uname -m) yet: build it from source (docs/server.md)" ;; esac -command -v curl >/dev/null || die "curl is needed" -if command -v sha256sum >/dev/null; then SHA="sha256sum" -elif command -v shasum >/dev/null; then SHA="shasum -a 256" -else die "sha256sum or shasum is needed"; fi - -if [ "$VERSION" = latest ]; then API="https://api.github.com/repos/$REPO/releases/latest" -else API="https://api.github.com/repos/$REPO/releases/tags/$VERSION"; fi -JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" "$API") || die "no release $VERSION on GitHub" - -TAG=$(printf '%s\n' "$JSON" | sed -n 's/^ "tag_name": "\([^"]*\)".*/\1/p' | head -n 1) -[ -n "$TAG" ] || die "could not read the release's tag" -# The asset's download address and digest, from its block in the release's JSON. -FIELDS=$(printf '%s\n' "$JSON" | awk -v asset="$ASSET" ' - /"name": / { line = $0; sub(/.*"name": "/, "", line); sub(/".*/, "", line); current = line } - current == asset && /"digest": / { line = $0; sub(/.*"digest": "sha256:/, "", line); sub(/".*/, "", line); digest = line } - current == asset && /"browser_download_url": / { line = $0; sub(/.*"browser_download_url": "/, "", line); sub(/".*/, "", line); url = line } - END { print url; print digest }') -URL=$(printf '%s\n' "$FIELDS" | sed -n 1p) -DIGEST=$(printf '%s\n' "$FIELDS" | sed -n 2p) -[ -n "$URL" ] || die "release $TAG has no $ASSET" -[ -n "$DIGEST" ] || die "release $TAG publishes no SHA-256 for $ASSET" - TMP=$(mktemp -d) trap 'rm -rf "$TMP"' EXIT -echo "Downloading Horizon $TAG ($ASSET)..." -curl -fL --progress-bar -o "$TMP/$ASSET" "$URL" -GOT=$($SHA "$TMP/$ASSET" | cut -d' ' -f1) -[ "$GOT" = "$DIGEST" ] || die "$ASSET doesn't match its SHA-256 (got $GOT, expected $DIGEST): not installed" +if [ -n "$ARCHIVE" ]; then + # An archive already here (a build of your own, or one fetched by hand): checking it is up to you. + [ -f "$ARCHIVE" ] || die "no archive $ARCHIVE" + if [ "$VERSION" = latest ]; then TAG=local; else TAG=$VERSION; fi + ASSET=$(basename "$ARCHIVE") + cp "$ARCHIVE" "$TMP/$ASSET" +else + command -v curl >/dev/null || die "curl is needed" + if command -v sha256sum >/dev/null; then SHA="sha256sum" + elif command -v shasum >/dev/null; then SHA="shasum -a 256" + else die "sha256sum or shasum is needed"; fi + + if [ "$VERSION" = latest ]; then API="https://api.github.com/repos/$REPO/releases/latest" + else API="https://api.github.com/repos/$REPO/releases/tags/$VERSION"; fi + JSON=$(curl -fsSL -H "Accept: application/vnd.github+json" "$API") || die "no release $VERSION on GitHub" + + TAG=$(printf '%s\n' "$JSON" | sed -n 's/^ "tag_name": "\([^"]*\)".*/\1/p' | head -n 1) + [ -n "$TAG" ] || die "could not read the release's tag" + # The first asset the release has: its download address and digest, from its block in the release's JSON. + for ASSET in $ASSETS; do + FIELDS=$(printf '%s\n' "$JSON" | awk -v asset="$ASSET" ' + /"name": / { line = $0; sub(/.*"name": "/, "", line); sub(/".*/, "", line); current = line } + current == asset && /"digest": / { line = $0; sub(/.*"digest": "sha256:/, "", line); sub(/".*/, "", line); digest = line } + current == asset && /"browser_download_url": / { line = $0; sub(/.*"browser_download_url": "/, "", line); sub(/".*/, "", line); url = line } + END { print url; print digest }') + URL=$(printf '%s\n' "$FIELDS" | sed -n 1p) + DIGEST=$(printf '%s\n' "$FIELDS" | sed -n 2p) + [ -z "$URL" ] || break + done + [ -n "$URL" ] || die "release $TAG has none of $ASSETS" + [ -n "$DIGEST" ] || die "release $TAG publishes no SHA-256 for $ASSET" + + echo "Downloading Horizon $TAG ($ASSET)..." + curl -fL --progress-bar -o "$TMP/$ASSET" "$URL" + GOT=$($SHA "$TMP/$ASSET" | cut -d' ' -f1) + [ "$GOT" = "$DIGEST" ] || die "$ASSET doesn't match its SHA-256 (got $GOT, expected $DIGEST): not installed" +fi mkdir -p "$TMP/x" case "$ASSET" in @@ -86,6 +102,18 @@ for tool in horizon-server horizon-prepare; do done echo "Installed Horizon $TAG in $RELEASE; horizon-server and horizon-prepare are in $BIN." +# The full game (releases before the server build) links ALSA and udev; minimal Linux images often lack them. +if [ "$(uname -s)" = Linux ] && [ ! -e "$RELEASE/horizon-engine" ] && command -v ldd >/dev/null; then + MISSING=$(ldd "$RELEASE/horizon-client" 2>/dev/null | awk '/not found/ { printf "%s ", $1 }') + if [ -n "$MISSING" ]; then + echo "The game needs libraries this system doesn't have: $MISSING" + echo "Install them before starting a server:" + echo " Debian, Ubuntu: sudo apt install libasound2 libudev1 (Ubuntu 24.04 and later: libasound2t64)" + echo " Fedora, RHEL: sudo dnf install alsa-lib systemd-libs" + echo " Arch: sudo pacman -S alsa-lib systemd-libs" + echo " NixOS: enable programs.nix-ld with alsa-lib and udev in its libraries" + fi +fi case ":$PATH:" in *":$BIN:"*) ;; *) echo "Add $BIN to your PATH, for example: echo 'export PATH=\"$BIN:\$PATH\"' >> ~/.profile" ;; diff --git a/tests/test_server_bench.py b/tests/test_server_bench.py new file mode 100644 index 000000000..f392297bc --- /dev/null +++ b/tests/test_server_bench.py @@ -0,0 +1,32 @@ +import unittest + +from tools.server_bench import work + + +def run(server, bots, sent, new, waited=0.0, behaviour="mixed"): + return {"server": server, "behaviour": behaviour, "bots": bots, "chunks_per_second": sent, + "unique_per_second": new, "waited_ticks_per_second": waited} + + +class ServerBenchWorkTests(unittest.TestCase): + def test_shares_of_the_busiest_server(self): + [row] = work([run("horizon", 10, 98.2, 36.5), run("vanilla", 10, 24.3, 19.1, 12.0)]) + self.assertFalse(row["equal"]) + self.assertEqual(row["servers"]["horizon"]["chunks_per_second"], {"value": 98.2, "share": 1.0}) + self.assertEqual(row["servers"]["vanilla"]["chunks_per_second"]["share"], 0.247) + self.assertEqual(row["servers"]["vanilla"]["waited_ticks_per_second"], 12.0) + + def test_equal_within_ten_percent_or_a_chunk(self): + [row] = work([run("horizon", 25, 236, 28.9), run("vanilla", 25, 252, 28.9)]) + self.assertTrue(row["equal"]) + # One bot: 0.3 against 1.1 new chunks a second is within a chunk. + [row] = work([run("horizon", 1, 9.9, 0.3), run("vanilla", 1, 9.9, 1.1)]) + self.assertTrue(row["equal"]) + + def test_only_counts_run_on_several_servers(self): + failed = dict(run("vanilla", 50, 0, 0), error="watchdog") + self.assertEqual(work([run("horizon", 50, 450, 10), failed, run("horizon", 1, 9, 0.3)]), []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/agent_control_e2e.py b/tools/agent_control_e2e.py index ab408b2b2..53296669a 100644 --- a/tools/agent_control_e2e.py +++ b/tools/agent_control_e2e.py @@ -7,7 +7,8 @@ runs through the CLI (one horizon-ctl process per command) and through `horizon- small JSON-RPC client, and saves a screenshot of each run. The ui scenario drives the menus by widget id instead: the title screen, the options (a slider set by id) and the inventory's slots; the options scenario reads and sets options.txt values by key; the events scenario waits for -states (wait-for) and reads the event log. +states (wait-for) and reads the event log; the consume scenario eats and drinks consumables (a +golden apple, milk, honey, chorus fruit) and checks their effects, remainders and teleport. python3 tools/agent_control_e2e.py # both modes python3 tools/agent_control_e2e.py --mode mcp # one of them @@ -378,7 +379,52 @@ def events_scenario(d, out): return {'events': len(events)} -SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario} +def consume_scenario(d, out): + # Consumables finish as vanilla's Consumable.onConsume: always-edible food at full hunger with its + # effects, milk and honey (no food or drink sounds) with their effects and use remainders, and + # chorus fruit's random teleport. + d('click', id='singleplayer') + if 'game' not in widgets(d): + d('click', id='create-new-world') + d('type', field='name', replace=True, text='Consume') + d('click', id='create-new-world') + d('wait_for', condition='loaded', timeout=400) + + def consume(item, seconds): + d('command', command='clear @s') + d('give', item=item, count=1) + d('use_item', hold=seconds) + d('wait', ticks=5) + state = d('state') + return state, {e['id'] for e in state['player']['effects']} + + def held(state): + return state['held'] and state['held']['item'] + + state, effects = consume('golden_apple', 2.2) + assert state['player']['food'] == 20 and {'regeneration', 'absorption'} <= effects, effects + assert held(state) is None, state['held'] + d('command', command='effect give @s minecraft:speed 60') + state, effects = consume('milk_bucket', 2.2) + assert effects == set(), effects + assert held(state) == 'minecraft:bucket', state['held'] + d('command', command='effect give @s minecraft:poison 60') + d('command', command='effect give @s minecraft:speed 60') + state, effects = consume('honey_bottle', 2.6) + assert effects == {'speed'}, effects + assert held(state) == 'minecraft:glass_bottle', state['held'] + before = d('state')['player']['position'] + state, _ = consume('chorus_fruit', 2.2) + after = state['player']['position'] + moved = [b - a for a, b in zip(before, after)] + assert held(state) is None, state['held'] + assert moved != [0, 0, 0] and abs(moved[0]) <= 8 and abs(moved[2]) <= 8, moved + d('screenshot', path=str(out / f'consume-{d.name}.png')) + return {'teleported': [round(m, 2) for m in moved]} + + +SCENARIOS = {'survival': scenario, 'ui': ui_scenario, 'options': options_scenario, 'events': events_scenario, + 'consume': consume_scenario} def run(mode, ctl, out, resources, which='survival'): diff --git a/tools/check_imports.py b/tools/check_imports.py index 8cdabe45b..85afb541d 100644 --- a/tools/check_imports.py +++ b/tools/check_imports.py @@ -5,7 +5,8 @@ Windows .exe: every DLL in the import and delay-import tables must ship with Windows (no VCRUNTIME140.dll, vulkan-1.dll, ...): Vulkan and the like are loaded at run time, so a missing driver is an error message, not a dialog. Linux ELF: the loader must be the standard one (not a /nix/store path) and the -needed libraries the ones every desktop distribution has. +needed libraries the ones every desktop distribution has. `--server`: a server +build, which may not need ALSA or udev either (minimal server images lack them). """ import argparse @@ -30,6 +31,8 @@ LINUX_SYSTEM = { "libc.so.6", "libm.so.6", "libgcc_s.so.1", "libdl.so.2", "libpthread.so.0", "librt.so.1", "ld-linux-x86-64.so.2", "libasound.so.2", "libudev.so.1", } +# The game's sound (cpal) and controllers (gilrs): a desktop has them, a server image may not. +LINUX_DESKTOP_ONLY = {"libasound.so.2", "libudev.so.1"} def windows_allowed(name): @@ -111,7 +114,7 @@ def elf_needs(data): return interpreter, needed, runpath -def check(path): +def check(path, server=False): data = Path(path).read_bytes() problems = [] if data[:2] == b"MZ": @@ -123,6 +126,8 @@ def check(path): if interpreter not in (None, LINUX_LOADER): problems.append(f"loader is {interpreter}, not {LINUX_LOADER}") problems += [f"needs {n}, which not every distribution has" for n in needed if n not in LINUX_SYSTEM] + if server: + problems += [f"needs {n}, which a server may not have" for n in needed if n in LINUX_DESKTOP_ONLY] problems += [f"has a run path to {p}" for p in runpath if "/nix/store" in p] summary = f"{interpreter}; " + ", ".join(needed) print(f"{path}: {summary}") @@ -134,8 +139,10 @@ def check(path): def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("binaries", nargs="+") + parser.add_argument("--server", action="store_true", + help="a server build: not even ALSA or udev (the game's sound and controllers)") args = parser.parse_args() - ok = all([check(path) for path in args.binaries]) + ok = all([check(path, args.server) for path in args.binaries]) sys.exit(0 if ok else 1) diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index eb99e1f1a..166ecaf70 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -2,7 +2,8 @@ Each group is a list of operations: `cmd` runs a command as the player and records its messages and results (`record: false` runs setup silently), -`tick` advances the game and `settle` loads the terrain around the player. +`tick` advances the game, `settle` loads the terrain and entities around the +player and `portal` sends the player through the nether portal it stands in. Everything happens high above the terrain (y 200 and up, where both worlds are air) after the world's entities are removed, so the results do not depend on world generation. @@ -391,6 +392,49 @@ def execute(): *setup('/kill @e[type=minecraft:armor_stand]', '/setblock 4 210 4 minecraft:air', '/setblock 5 210 5 minecraft:air', '/scoreboard objectives remove exec', '/tp @s 8.5 230 8.5 0 0'), {'op': 'tick', 'n': 25}, + *setup('/gamemode spectator'), + cmd('/execute in minecraft:the_nether if dimension minecraft:the_nether run say source dimension'), + cmd('/execute in minecraft:the_nether at @s if dimension minecraft:overworld run say entity dimension'), + cmd('/execute in minecraft:the_nether positioned as @s if dimension minecraft:the_nether run say position only'), + cmd('/execute in minecraft:the_nether if loaded 0 100 0'), + cmd('/execute in minecraft:the_nether run tp @s 0 100 0'), + {'op': 'settle'}, + cmd('/execute if dimension minecraft:the_nether run say dimension switched'), + cmd('/data get entity @s Pos'), + cmd('/execute in minecraft:the_nether positioned 80 100 -40 in minecraft:overworld run tp @s ~ ~ ~'), + {'op': 'settle'}, + cmd('/execute if dimension minecraft:overworld run say relative dimension'), + cmd('/data get entity @s Pos'), + cmd('/execute in minecraft:overworld positioned 80 100 -40 in minecraft:the_nether run tp @s ~ ~ ~ 45 30'), + {'op': 'settle'}, + cmd('/data get entity @s Pos'), + cmd('/data get entity @s Rotation'), + cmd('/execute in minecraft:overworld run tp @s 8.5 230 8.5'), + {'op': 'settle'}, + cmd('/execute if dimension minecraft:overworld run say dimension restored'), + cmd('/data get entity @s Pos'), + *setup('/gamemode creative'), + ] + + +def levels(): + """A nether portal round trip: on the way back the Overworld's entities (the + pig left by `entities`) are found and a summon names what it summoned.""" + return [ + *setup('/fill 2 231 12 5 236 12 minecraft:obsidian', '/fill 3 232 12 4 235 12 minecraft:nether_portal[axis=x]', + '/tp @s 3.5 232 12.5 0 0'), + {'op': 'portal'}, + {'op': 'settle'}, + cmd('/execute if dimension minecraft:the_nether run say through the portal'), + {'op': 'portal'}, + {'op': 'settle'}, + cmd('/execute if dimension minecraft:overworld run say back through the portal'), + cmd('/data get entity @s Pos'), + cmd('/data get entity @s Rotation'), + cmd('/execute if entity @e[type=minecraft:pig]'), + cmd('/summon minecraft:armor_stand 4.5 210 4.5 {NoGravity:1b,Tags:["lv"],CustomName:"Back"}'), + *setup('/kill @e[tag=lv]', '/fill 2 231 12 5 236 12 minecraft:air', '/tp @s 8.5 230 8.5 0 0'), + {'op': 'settle'}, ] @@ -918,6 +962,7 @@ def groups(): ('entities', entities()), ('scores, teams and bossbars', scores()), ('execute', execute()), + ('levels', levels()), ('items and loot', items_and_loot()), ('world', world_misc()), ('progression', progression()), diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 4d13b1c22..144ed6961 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -19,9 +19,21 @@ address. The script then checks, from both sides, what a guest's game used to ge - hazards: a guest in survival gets hungry sprint-jumping and is hurt by lava, a block at the eyes, drowning and the void (then respawns); - pvp: the guest and the host hit each other with a sword; with the pvp game rule off, nothing; +- respawn: a player killed is drawn dead by the other side, and alive again once it respawns (the + respawned player is a new entity to the others); the host dies, and on the server thread + the guest too; +- hurt: a pig the guest hits, and one the host hits, flashes red on the other side too (the + server's damage event) (#848); - containers: the guest's ender chest holds the guest's items, not the host's, and a double chest opens as 9x6 with the right half first; +- machines: a hopper, a dispenser and a dropper open on the guest's screen with their 5 and 9 + slots, and keep what the guest shift-clicks into them (#848); +- brewing: a brewing stand opens on the guest's screen; blaze powder, nether wart and a bottle the + guest shift-clicks go to the fuel, ingredient and bottle slots, and the stand's fuel shows + (#848); - feedback: the guest's command feedback names the guest and shows the numbers; +- chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the + server thread the host window's too; - effects: a beacon's power reaches every player in range, the host and the guest; - distance: (--server-thread) the server follows the host's render distance, past vanilla's 32 too (IntegratedServer.tickServer), and the guest's chunks follow the server's (#804) @@ -43,12 +55,22 @@ address. The script then checks, from both sides, what a guest's game used to ge pushes it, as in vanilla), not ever faster across the ground. - eat: holding right click with bread, the guest's own screen plays the eating (the item in use counts up) and the server eats one loaf and feeds the guest. +- eating: each side sees the other player eat: the item in use (LivingEntity's flags) on the + player it draws, and no longer once the bread is eaten (#803); - xp: experience orbs 4 blocks away fly to the guest, show on the guest's screen and give the guest their points (not the host). - objects: boats, minecarts, armor stands, item frames and paintings the host summons reach the guest as the host has them (kind, place, rotation, what they hold or wear, the variant). - projectiles: primed TNT (one falling), an end crystal and an arrow that lands reach the guest where the host has them; a falling block lands on both sides. +- plates: a stone pressure plate the guest steps on is pressed on both sides, and comes up once + the guest steps off (#848). +- swings: each side sees the other's arm swing while it mines a block, and the guest sees its own + swing when its hoe tills dirt (the server's use) (#848). +- time: the guest's clock is the host's: it stops with `/time pause`, and catches up with the + server's game time after the guest's game stalls for a few seconds (#848). +- growth: far from the host, the chunks around the guest tick (#890): water placed there flows + and wheat on farmland grows (random ticks), however the host runs its world. - light: the guest's light matches the host's: around a torch placed near it, under a roof and once a block of the roof is removed under the sky, and in the last chunk it tracks next to glowstone in a chunk it doesn't (only the server's light updates bring that one). @@ -69,6 +91,7 @@ import json import os import re import shutil +import signal import subprocess import sys import tempfile @@ -84,7 +107,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'containers', 'feedback', 'titles', 'commands', 'recipes', 'trials', 'clicks', 'sleep', 'push', 'eat', 'xp', 'objects', 'projectiles', 'light', 'effects', 'portals', 'distance'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'trials', 'clicks', 'sleep', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'light', 'time', 'swings', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -575,6 +598,72 @@ def check_pvp(host, guest, out): return hits +def dead_players(game, want, ticks=60): + """The other players `game`'s client draws dead, once that is `want` (empty or not) or after `ticks`.""" + for _ in range(ticks // 5): + dead = remote(game)['dead_players'] + if bool(dead) == want: + return dead + game.wait(5) + return dead + + +def check_respawn(host, guest, out): + # ServerLevel.removePlayerImmediately and addRespawnedPlayer: a respawned player is removed + # from the other players and paired again as a new entity, so their clients drop the body. + # The host window only has a client's view of the guest on the server thread. + for g in (host, guest): + back_to_game(g) + results = {} + sides = [('host', host, guest)] + ([('guest', guest, host)] if SERVER_THREAD else []) + for name, dying, watching in sides: + face_each_other(host, guest) + dying('command', command='kill @s') + dying.wait(30) + dead = dead_players(watching, True) + watching.shot(out, f'respawn-{name}-dead') + dying.raw('respawn') + dying.wait(40) + back_to_game(dying) + # Back within tracking range of the other player, wherever the respawn point is. + x, y, z = pos_of(dying) + watching('command', command=f'tp @s {x + 3:.2f} {y:.2f} {z:.2f}') + watching.wait(40) + alive = dead_players(watching, False) + watching.shot(out, f'respawn-{name}-alive') + results[name] = {'dead': dead, 'after_respawn': alive} + assert dead, f'the {name} was not drawn dead: {results}' + assert not alive, f'the {name} still lies dead after respawning: {results}' + return results + + +def check_hurt(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = pos_of(host) + # Between the two, within both players' reach; bare hands leave it alive. + host('command', command=f'summon minecraft:pig {hx + 1.5:.2f} {hy:.2f} {hz + 0.8:.2f} {{NoAI:1b}}') + host.wait(30) + + def pig(game): + return game.raw('entities', 6, 'pig')['entities'][0] + seen = {} + for name, attacker, watcher in (('guest hits', guest, host), ('host hits', host, guest)): + attacker.wait(30) # a full attack charge + attacker.raw('attack', pig(attacker)['id']) + seen[name] = {'attacker': pig(attacker)['hurt_time'], 'watcher': pig(watcher)['hurt_time']} + attacker.shot(out, 'hurt-' + name.replace(' ', '-')) + watcher.shot(out, 'hurt-' + name.replace(' ', '-') + '-seen') + attacker.wait(20) + host('command', command='kill @e[type=minecraft:pig]') + # LivingEntity.hurtTime: 10 when hurt, one less each tick; the reads come a few ticks later. + for name, sides in seen.items(): + assert all(t > 0 for t in sides.values()), f'{name}: the pig\'s hurt flash {seen}' + return seen + + def container_items(game): """The open container's stacks by slot (Horizon's container slots are 300 and up) and its size.""" slots = [s for s in game('screen').get('slots', []) if s.get('slot', 0) >= 300] @@ -637,6 +726,69 @@ def check_containers(host, guest, out): return {'ender': ender, 'double': double, 'taken': taken} +def check_machines(host, guest, out): + # After `recipes`: the stacks given here unlock recipes, which would move the book's first one. + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + seen = {} + for block in ('hopper', 'dispenser', 'dropper'): + guest('command', command='clear @s') + guest('command', command='give @s minecraft:cobblestone 4') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + size = container_items(guest)[1] + guest.shot(out, f'machines-{block}') + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:cobblestone'), 'shift') + guest.wait(10) + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # Opened again, the menu holds what the server has. + seen[block] = (size, open_container(guest, at, out, f'machines-{block}-after')[0]) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + want = {'hopper': (5, {0: 'minecraft:cobblestone'}), 'dispenser': (9, {0: 'minecraft:cobblestone'}), + 'dropper': (9, {0: 'minecraft:cobblestone'})} + assert seen == want, f'the machines on the guest: {seen}' + return seen + + +def check_brewing(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + loads = ('blaze_powder', 'nether_wart', 'glass_bottle') + for item in loads: + guest('command', command=f'give @s minecraft:{item}') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:brewing_stand') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + size = container_items(guest)[1] + # BrewingStandMenu.quickMoveStack: blaze powder to the fuel slot, an ingredient to its slot, + # a bottle to the bottle slots. + for item in loads: + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + # BrewingStandBlockEntity.serverTick burns the blaze powder into 20 uses; the guest sees them + # through the menu's data slots. + guest.wait(10) + info = guest.raw('menu')['info'] + guest.shot(out, 'brewing') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + items = open_container(guest, at, out, 'brewing-after')[0] + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + seen = {'size': size, 'items': items, 'fuel': info and info.get('fuel')} + want = {'size': 5, 'items': {0: 'minecraft:glass_bottle', 3: 'minecraft:nether_wart'}, 'fuel': 20} + assert seen == want, f'the brewing stand on the guest: {seen}' + return seen + + def slot_point(game, slot): """The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N).""" for w in game.raw('ui')['widgets']: @@ -853,6 +1005,17 @@ def check_titles(host, guest, out): return {'shown': shown, 'cleared': cleared} +def check_chat(host, guest, out): + # The agent's event log follows a remote client's chat: `wait-for chat` sees the line another + # player sends (and on the server thread the host window's own line, back from the server). + line = f'chat check {int(time.time())}' + host.raw('chat', line) + seen = {g.name: g.raw('wait-for', 'chat', line, '--timeout', 10, '--since', 0).get('ok') + for g in ((guest, host) if SERVER_THREAD else (guest,))} + guest.shot(out, 'chat') + return seen + + def png_rows(path): """The rows of an 8-bit RGB or RGBA PNG, unfiltered, as bytes of 4 (or 3) per pixel.""" data = Path(path).read_bytes() @@ -958,6 +1121,27 @@ def wait_state(game, pos, key, want, ticks): return state_of(game, pos, key) +def check_plates(host, guest, out): + guest('command', command='gamemode survival') + x, y, z = (int(v // 1) for v in pos_of(guest)) + plate = (x + 2, y, z) + guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:stone_pressure_plate') + guest.wait(10) + guest('command', command=f'tp @s {plate[0] + 0.5} {plate[1]} {plate[2] + 0.5}') + pressed = {'host': wait_state(host, plate, 'powered', 'true', 40), + 'guest': wait_state(guest, plate, 'powered', 'true', 40)} + guest.shot(out, 'plate-pressed') + guest('command', command=f'tp @s {x + 0.5} {y} {z + 0.5}') + # PressurePlateBlock.getPressedTime: a stone plate checks again every 20 ticks. + released = {'host': wait_state(host, plate, 'powered', 'false', 60), + 'guest': wait_state(guest, plate, 'powered', 'false', 60)} + guest('command', command=f'setblock {plate[0]} {plate[1]} {plate[2]} minecraft:air') + detail = {'pressed': pressed, 'released': released} + assert pressed == {'host': 'true', 'guest': 'true'}, f'the plate under the guest: {detail}' + assert released == {'host': 'false', 'guest': 'false'}, f'the plate after the guest left: {detail}' + return detail + + def check_trials(host, guest, out): # The host watches as a spectator, whom neither block detects: only the guest can wake them. hx, hy, hz = pos_of(host) @@ -1095,12 +1279,108 @@ def check_eat(host, guest, out): return detail +def watch_mining(miner, pos, seen): + """Mine the block at `pos` (by hand, for seconds) and sample `seen()` meanwhile.""" + dig = threading.Thread(target=miner.raw, args=('break', *pos)) + dig.start() + samples = [] + for _ in range(8): + time.sleep(0.25) + samples.append(seen()) + dig.join() + return samples + + +def check_swings(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + face_each_other(host, guest) + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + # Stone by hand takes 7.5 seconds: ServerboundPunchPacket every tick keeps the arm swinging. + guest('command', command=f'setblock {gx} {gy} {gz + 1} minecraft:stone') + host('command', command=f'setblock {hx} {hy} {hz + 1} minecraft:stone') + host.wait(10) + def swinging(game): + # On its server thread the host's window is a client of its server too. + if game is host and not SERVER_THREAD: + return lan_guest(host).get('model_swinging') + return any(e.get('swinging') for e in remote(game).get('player_equipment', [])) + # Most samples: a swing restarts only past its first half (SwingState.startIfAble), so a sample can + # fall between two. + host_sees = watch_mining(guest, (gx, gy, gz + 1), lambda: swinging(host)) + guest_sees = watch_mining(host, (hx, hy, hz + 1), lambda: swinging(guest)) + # A hoe on dirt: the server tills it and swings the guest's hand, on the guest's screen too. + # Where the guest stands now (an earlier check can leave it on a ledge it then drops from). + gx, gy, gz = (int(v // 1) for v in pos_of(guest)) + soil = (gx, gy - 1, gz + 1) + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:dirt') + # HoeItem.useOn tills only under air. + guest('command', command=f'setblock {soil[0]} {soil[1] + 1} {soil[2]} minecraft:air') + guest('command', command='give @s minecraft:wooden_hoe') + guest.wait(10) + guest.raw('select', 'minecraft:wooden_hoe') + before = guest('state')['swings'] + guest.raw('interact', *soil) + guest.wait(10) + hoe = {'swings': guest('state')['swings'] - before, 'soil': host.raw('block', *soil)['block']} + guest('command', command=f'setblock {soil[0]} {soil[1]} {soil[2]} minecraft:stone') + detail = {'host_sees_guest': host_sees, 'guest_sees_host': guest_sees, 'hoe': hoe} + assert sum(map(bool, host_sees)) >= 4, f'the host does not see the guest mine: {detail}' + assert sum(map(bool, guest_sees)) >= 4, f'the guest does not see the host mine: {detail}' + assert hoe == {'swings': 1, 'soil': 'minecraft:farmland'}, f'the guest\'s hoe: {detail}' + return detail + + +def check_eating(host, guest, out): + for g in (host, guest): + g('command', command='gamemode survival') + g('command', command='clear @s') + # Hungry: Player.canEat. + g('command', command='effect give @s minecraft:hunger 3 255') + host.wait(70) + for g in (host, guest): + g('command', command='effect clear @s') + g('command', command='give @s minecraft:bread 2') + host.wait(5) + face_each_other(host, guest) + + def using(game): + # On its server thread the host's window is a client of its server too. + if game is host and not SERVER_THREAD: + return lan_guest(host).get('model_using') or 0 + return max((e.get('using') or 0 for e in remote(game).get('player_equipment', [])), default=0) + seen = {} + for name, eater, watcher in (('host eats', host, guest), ('guest eats', guest, host)): + eater.raw('select', 'minecraft:bread') + hold = threading.Thread(target=eater.raw, args=('use-item', '--hold', 2.2)) + hold.start() + samples = [] + for _ in range(4): + time.sleep(0.3) + samples.append(using(watcher)) + watcher.shot(out, 'eating-' + name.replace(' ', '-')) + hold.join() + eater.wait(10) + seen[name] = {'during': samples, 'after': using(watcher)} + for name, s in seen.items(): + assert sum(1 for u in s['during'] if u > 0) >= 3 and s['after'] == 0, f'{name}: {seen}' + return seen + + def check_xp(host, guest, out): for g in (host, guest): g('command', command='gamemode survival') g('command', command='xp set @s 0 levels') g('command', command='xp set @s 0 points') + # Out of the orbs' way wherever an earlier check left the host (ExperienceOrb follows the + # nearest player who isn't a spectator). + host('command', command='gamemode spectator') guest.wait(10) + # `xp set` leaves Player.totalExperience (the score): experience from earlier checks stays in it. + total = guest('state')['player']['xp']['total'] + host_total = host('state')['player']['xp']['total'] x, y, z = pos_of(guest) # Three orbs of 7 points 4 blocks east of the guest (out of reach, within the 8 blocks orbs # follow from): they fly to the guest. @@ -1116,12 +1396,35 @@ def check_xp(host, guest, out): detail = {'seen': seen, 'guest': xp, 'host': host_xp, 'left': left} # ExperienceOrb.scanForMerges: orbs of one value side by side can merge into one. assert 1 <= seen <= 3, f'the guest saw {seen} orbs: {detail}' - assert xp['total'] == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' - assert host_xp['total'] == 0, f'the host took the orbs: {detail}' + assert xp['total'] - total == 21 and xp['level'] == 2, f'the guest\'s experience after three 7-point orbs: {detail}' + assert host_xp['total'] == host_total, f'the host took the orbs: {detail}' assert left == 0, f'orbs left on the guest\'s screen: {detail}' return {'seen': seen, 'guest': xp, 'host': host_xp} +def check_time(host, guest, out): + def times(): + return host('state')['time']['day_time'], guest('state')['time']['day_time'] + host('command', command='time set 1000') + host('command', command='time pause') + host.wait(60) + paused = times() + host('command', command='time resume') + guest.wait(20) + # A stalled game runs at most 10 missed ticks when it wakes (DeltaTracker); the server's + # game time, sent every second, moves the guest's clock on (ClientClockManager.tick). + os.kill(guest.pid, signal.SIGSTOP) + time.sleep(4) + os.kill(guest.pid, signal.SIGCONT) + guest.wait(60) + stalled = times() + detail = {'paused': paused, 'after_stall': stalled} + assert paused[0] == paused[1] and 1000 <= paused[0] < 1010, f'the clock while paused: {detail}' + # The two reads are a tick or two apart. + assert abs(stalled[0] - stalled[1]) <= 3, f'the guest\'s clock after its game stalled: {detail}' + return detail + + def objects_near(game, centre, key='objects'): """`status`'s objects within 8 blocks of centre, without their ids (each side numbers its own).""" out = [] @@ -1227,6 +1530,48 @@ def same_light(host, guest, lo, hi, what, ticks=100): f'{h["sky"][i]} block {h["block"][i]}, guest sky {g["sky"][i]} block {g["block"][i]}') +def check_growth(host, guest, out): + """Block ticks near a guest 1000 blocks from the host: only the guest's tickets tick them.""" + x0, y0, z0 = pos_of(guest) + guest('command', command='gamemode creative') + guest('command', command=f'tp @s {x0 + 1000:.2f} 200 {z0:.2f}') + guest.wait(100) + x, y, z = (int(v // 1) for v in pos_of(guest)) + # A platform in the air over wherever the guest landed: a water source two blocks east of the + # guest, wheat on farmland two blocks west. Vanilla's water spreads only towards the nearest + # drop (FlowingFluid.getSpread), so any of the source's four neighbours may take it. Wheat + # grows only in daylight (raw brightness 9 or more). + top = max(y + 12, 120) + water = (x + 2, top + 1, z) + beside = [(water[0] + dx, water[1], water[2] + dz) for dx, dz in ((1, 0), (-1, 0), (0, 1), (0, -1))] + wheat = (x - 2, top + 1, z) + flowed = [] + try: + host('command', command='time set noon') + guest('command', command=f'fill {x - 4} {top} {z - 2} {x + 4} {top} {z + 2} minecraft:stone') + guest('command', command=f'setblock {wheat[0]} {top} {wheat[2]} minecraft:farmland[moisture=7]') + guest('command', command=f'setblock {wheat[0]} {wheat[1]} {wheat[2]} minecraft:wheat[age=0]') + guest('command', command='gamerule random_tick_speed 1000') + guest('command', command=f'setblock {water[0]} {water[1]} {water[2]} minecraft:water') + for _ in range(40): + guest.wait(10) + flowed = [p for p in beside if guest.raw('block', *p).get('block') == 'minecraft:water'] + if flowed: + break + age = wait_state(guest, wheat, 'age', '7', 2400) + guest.shot(out, 'growth') + finally: + guest('command', command='gamerule random_tick_speed 3') + host('command', command='time set day') + guest('command', command=f'tp @s {x0:.2f} {y0:.2f} {z0:.2f}') + guest('command', command='gamemode survival') + guest.wait(40) + detail = {'flowed': flowed, 'wheat age': age} + assert flowed, f'the water beside the guest did not flow: {detail}' + assert age == '7', f'the wheat beside the guest did not grow: {detail}' + return detail + + def check_light(host, guest, out): gx, gy, gz = (int(v // 1) for v in pos_of(guest)) results = {} @@ -1260,9 +1605,15 @@ def check_light(host, guest, out): host('command', command=f'setblock {near} {y} {gz} minecraft:glowstone') try: lo, hi = (untracked * 16 - 16, y - 3, gz - 8), (untracked * 16 - 1, y + 3, gz + 8) + # On the server thread the host's game is a client too, as dark as the guest until the light + # update arrives: wait for it before comparing them. + for _ in range(10): + lit = guest.raw('light', near - 2, y, gz, near - 2, y, gz)['block'] + if lit == 'd': + break + host.wait(10) + assert lit == 'd', f'the border chunk by the glowstone has block light {lit}, not 13, after 100 ticks' results['border'] = same_light(host, guest, lo, hi, 'border chunk') - lit = guest.raw('light', near - 2, y, gz, near - 2, y, gz)['block'] - assert lit == 'd', f'the border chunk by the glowstone has block light {lit}, not 13' finally: host('command', command=f'setblock {near} {y} {gz} minecraft:air') results['border_cleared'] = same_light(host, guest, lo, hi, 'border chunk without the glowstone') @@ -1272,13 +1623,19 @@ def check_light(host, guest, out): CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'nametags': check_nametags, 'chest': check_chest, 'crafting': check_crafting, 'sign': check_sign, 'damage': check_damage, 'mobs': check_mobs, 'hazards': check_hazards, 'pvp': check_pvp, - 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, + 'respawn': check_respawn, + 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, + 'machines': check_machines, + 'brewing': check_brewing, + 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, 'effects': check_effects, 'portals': check_portals, 'distance': check_distance, 'clicks': check_clicks, - 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, + 'sleep': check_sleep, 'push': check_push, 'eat': check_eat, 'eating': check_eating, 'xp': check_xp, 'objects': check_objects, 'projectiles': check_projectiles, - 'light': check_light} + 'light': check_light, 'plates': check_plates, + 'swings': check_swings, + 'time': check_time, 'growth': check_growth} def run(ctl, out, resources, checks): @@ -1301,7 +1658,7 @@ def run(ctl, out, resources, checks): host('command', command='gamerule spawn_mobs false') port = host.raw('lan', 'open', 0, 'commands')['port'] host.player = host.raw('lan', 'status').get('host', 'Player') # the host's profile name - guest('launch', wait=False, offscreen=sys.platform == 'darwin') + guest.pid = guest('launch', wait=False, offscreen=sys.platform == 'darwin')['pid'] guest.raw('connect', f'127.0.0.1:{port}', GUEST_NAME) guest.raw('wait-for', 'loaded', '--timeout', 300) guest.wait(40) diff --git a/tools/server_bench.py b/tools/server_bench.py index c79d6aab1..0ba99617a 100755 --- a/tools/server_bench.py +++ b/tools/server_bench.py @@ -19,7 +19,9 @@ The bots can run on another machine, so they don't take the server's CPU: `--bot `--bots-bin` naming horizon-bots there and `--connect` the address it reaches this machine at. `--nice 19` runs every server at the lowest priority (a shared machine). The explore bots fly as fast as each server sends them chunks, so a faster server gets more terrain to generate; `--explore-speed` slows them to a rate -both servers keep up with, for equal work. +both servers keep up with, for equal work. After the runs, the work table compares the servers at each bot +count: chunks sent and new chunks generated a second, against the busiest server's. A run whose work is more +than 10 % apart isn't a fair comparison of its tick times. The vanilla side runs the pinned server jar from tools/lab.py prepare (your own copy). It needs Java 25. The Horizon side runs target/release/horizon-server with the engine beside it; build both first: @@ -306,6 +308,38 @@ def run_once(kind, bots, behaviour, args, out): return result +# How far apart two servers' chunks a second (sent, and new) may be and still count as the same work: 10 %, +# or a chunk a second when there are few. +EQUAL_WORK = 0.10 + + +def work(runs): + """Each pass and bot count that ran on more than one server: every server's chunks sent and new chunks a + second as a share of the busiest one's, the ticks a second its bots stood waiting for their own chunk, + and whether the work was equal (within EQUAL_WORK on both).""" + groups = {} + for r in runs: + if 'error' not in r: + groups.setdefault((r['behaviour'], r['bots']), []).append(r) + rows = [] + for (behaviour, bots), group in groups.items(): + if len(group) < 2: + continue + row = {'behaviour': behaviour, 'bots': bots, 'servers': {}, 'equal': True} + for key in ('chunks_per_second', 'unique_per_second'): + top = max(r.get(key) or 0 for r in group) + for r in group: + value = r.get(key) or 0 + share = round(value / top, 3) if top else 1.0 + row['servers'].setdefault(r['server'], {})[key] = {'value': value, 'share': share} + if top - value > max(EQUAL_WORK * top, 1.0): + row['equal'] = False + for r in group: + row['servers'][r['server']]['waited_ticks_per_second'] = r.get('waited_ticks_per_second') + rows.append(row) + return rows + + def main(): parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) parser.add_argument('--servers', default='horizon,vanilla') @@ -346,6 +380,7 @@ def main(): 'java': subprocess.run(['java', '--version'], capture_output=True, text=True).stdout.splitlines()[:1], 'settings': {**vars(args), 'out': str(args.out), 'properties': PROPERTIES}, 'runs': runs, + 'work': work(runs), } path = args.out or out / 'report.json' path.parent.mkdir(parents=True, exist_ok=True) @@ -356,11 +391,20 @@ def main(): if 'error' in r: print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} failed: {r["error"].splitlines()[0]}') continue - per_bot = r['chunks_per_bot'].get(r['behaviour']) + # A mixed pass: every bot's. + per_bot = r['chunks_per_bot'].get(r['behaviour']) or round((r['chunks_total'] or 0) / r['bots']) print(f'{r["server"]:8} {r["behaviour"]:8} {r["bots"]:>4} {r["start_seconds"]:>8} {r["mspt"]["average"]!s:>6} ' f'{r["mspt"]["p95"]!s:>6} {r["mspt"]["p99"]!s:>6} {r["rss_mb"]["mean"]!s:>7} {r["cpu_percent"]!s:>6} ' f'{r["chunks_per_second"]!s:>8} {per_bot!s:>6} {r["resent"]!s:>6} {r["pulled_back"]!s:>6} ' f'{r["bots_joined"]!s:>6}') + if report['work']: + print(f'\nWork, against the busiest server (chunks a second sent, new; ticks a second bots waited):') + for row in report['work']: + cells = ' '.join( + f'{server} {w["chunks_per_second"]["value"]} ({w["chunks_per_second"]["share"]:.0%}), ' + f'{w["unique_per_second"]["value"]} ({w["unique_per_second"]["share"]:.0%}), ' + f'{w["waited_ticks_per_second"]}' for server, w in row['servers'].items()) + print(f'{row["behaviour"]:8} {row["bots"]:>4} {"equal" if row["equal"] else "NOT EQUAL"} {cells}') print(f'\nWrote {path}') diff --git a/tools/test_block_removal_parity.py b/tools/test_block_removal_parity.py index 35b0fdd2b..6ebbbf1d3 100755 --- a/tools/test_block_removal_parity.py +++ b/tools/test_block_removal_parity.py @@ -5,8 +5,9 @@ A container, jukebox, lectern, campfire, decorated pot, chiseled bookshelf, shelf, shulker box or another block entity holder at the origin holds random contents; the case then replaces it with `Level.setBlock` (another block, the same block in another state, with or without UPDATE_SKIP_BLOCK_ENTITY_SIDEEFFECTS), -destroys it with `Level.destroyBlock` (with or without drops) or removes it with -`Level.removeBlock`. Vanilla runs over the headless level of the dispenser oracle +destroys it with `Level.destroyBlock` (with or without drops), removes it with +`Level.removeBlock`, or a survival player mines it (`ServerPlayerGameMode.destroyBlock`, +holding a tool or nothing, #844). Vanilla runs over the headless level of the dispenser oracle (`VanillaDispenserOracle`, "remove" cases), which replays `LevelChunk.setBlockState`'s `BlockEntity.preRemoveSideEffects`; Horizon runs its game glue in a headless game (`HORIZON_DISPENSE_FIXTURE`). Both print the block changes, the contents left, @@ -63,6 +64,10 @@ LISTED = {'chest', 'trapped_chest', 'barrel', 'hopper', 'dispenser', 'dropper', REPLACEMENTS = ['air', 'stone', 'glass', 'water', 'oak_planks', 'barrel', 'chest', 'hopper', 'blue_shulker_box', 'dirt', 'tnt', 'copper_chest', 'oxidized_copper_chest', 'lectern', 'jukebox'] FLAGS = [3, 3, 3, 2, 18, 2 | 256, 816, 3 | 64, 1] +# What a mining player holds: the right tool, a tool too weak or of another kind (swords and maces +# wear 2 a block, shears any block but fire), or nothing. +TOOLS = [plain('diamond_pickaxe'), plain('wooden_pickaxe'), plain('stone_axe'), plain('iron_shovel'), plain('iron_sword'), + plain('shears'), plain('mace'), '-'] def contents(rng, name, slots, pool): @@ -135,8 +140,12 @@ def cases(facts, count, seed, only): op = {'op': 'destroy', 'drop': True} elif roll < 0.85: op = {'op': 'destroy', 'drop': False} - else: + elif roll < 0.92: op = {'op': 'remove'} + else: + # ServerPlayerGameMode.destroyBlock: a survival player mines it (#844). The tool comes + # from the roll, not another draw, so the cases after this one stay the same. + op = {'op': 'mine', 'item': TOOLS[int(roll * 1000) % len(TOOLS)]} case = {**h.environment(rng), 'mode': 'remove', 'pos': [0, 0, 0], 'cells': cells, 'items': items, 'remove': op} case.pop('raining', None) case.pop('thundering', None) diff --git a/tools/test_dedicated_server_parity.py b/tools/test_dedicated_server_parity.py index 6ac9aecbe..e8497d7f8 100644 --- a/tools/test_dedicated_server_parity.py +++ b/tools/test_dedicated_server_parity.py @@ -268,6 +268,12 @@ def run_side(label, command, directory, client): # it stays put; experience keeps its profession). server.console('summon minecraft:villager ~1 ~ ~ {NoAI:1b,Xp:1,VillagerData:' '{profession:"minecraft:librarian",level:2,type:"minecraft:plains"}}') + # The saved world still has fluid ticks due in the area the client is sent (a lava fall + # that never settles), and they run once their chunk ticks. When that is, against when the + # chunk is sent, follows how fast the server loads the chunks around the joining player: + # each run, vanilla sends a different set of them already flowed. Frozen until the client + # has its chunks, both servers send the world as saved; blocks tick again from the chat on. + server.console('tick freeze') port = int(PROPERTIES_PORTS[label]) legacy = legacy_ping(port) # The client asks to be made an operator once it has traded, runs /kill and respawns. @@ -282,7 +288,11 @@ def run_side(label, command, directory, client): joined = threading.Thread(target=join) joined.start() deadline = time.time() + 300 + frozen = True while joined.is_alive() and not any('<Tester> ready to respawn' in l for l in server.lines): + if frozen and any('<Tester> hello from the parity client' in l for l in server.lines): + server.console('tick unfreeze') + frozen = False if time.time() > deadline: break time.sleep(0.2) diff --git a/tools/test_game_loop_parity.py b/tools/test_game_loop_parity.py index d724dc6ac..101b3f238 100644 --- a/tools/test_game_loop_parity.py +++ b/tools/test_game_loop_parity.py @@ -120,8 +120,15 @@ def scroll_cases(rng): x = rng.choice([0.0, 0.0, 0.0, 1.0, -1.0, 0.25, -0.25, 0.4, 2.0, 5.5, -7.0, rng.uniform(-3, 3)]) y = rng.choice([0.0, 1.0, -1.0, 1.0, -1.0, 0.1, -0.3, 0.5, -0.5, 2.0, -3.0, 120.0, rng.uniform(-3, 3)]) ops.append([dbits(x), dbits(y)]) - yield dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), - slot=rng.randrange(9), ops=ops) + case = dict(t='scroll', discrete=rng.random() < 0.4, sens=dbits(rng.choice([1.0, 0.01, 10.0, 0.5, 2.0, 3.1622776601683795])), + slot=rng.randrange(9), ops=ops) + yield case + yield dict(case, spectator=True) + # Bounds, recovery from each bound, fractional accumulation, and horizontal-only input. + yield dict(t='scroll', discrete=False, sens=dbits(1.0), slot=4, spectator=True, + ops=[[dbits(x), dbits(y)] for x, y in + [(0, 100), (0, -1), (0, -100), (0, 1), (0, .4), (0, .7), + (0, -.4), (0, -.7), (5, 0), (-5, 0)]]) def key_cases(rng): @@ -152,7 +159,7 @@ def main(): 'Window.calculateScale/setGuiScale and MouseHandler scaled positions, FramerateLimitTracker throttle reasons and ' 'limits (not the focus-lost exclusive-fullscreen branch, which reads SDL), MouseHandler.onMove/turnPlayer with ' 'sensitivity, cinematic smoothing, scoping and inversion, Entity.turn clamps, onScroll with ScrollWheelHandler ' - 'accumulation, discrete scrolling and hotbar selection, and ToggleKeyMapping/KeyMapping down, click and ' + 'accumulation, discrete scrolling, hotbar selection and spectator flight speed, and ToggleKeyMapping/KeyMapping down, click and ' 'screen-release state. The frame clock source (Blaze3D.getTime, System.nanoTime) is injected, so sleeping in ' 'FramerateLimiter and vsync present-mode selection are covered by Rust unit tests only.') harness.differential( diff --git a/tools/test_interaction_input_parity.py b/tools/test_interaction_input_parity.py new file mode 100644 index 000000000..1aa34a73f --- /dev/null +++ b/tools/test_interaction_input_parity.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Compare queued interaction ordering with the real Minecraft.handleKeybinds.""" +import itertools +import json +import random + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def corpus(): + rng = random.Random(0x434C49434B) + for using, destroying, attack_down, use_down, entity in itertools.product([False, True], repeat=5): + for clicks in [[], [1], [0, 1], [1, 0], [2, 1, 0], [0, 0, 1, 1, 2]]: + for delay in [0, 3]: + yield dict(using=using, destroying=destroying, attack_down=attack_down, + use_down=use_down, entity=entity, clicks=clicks, delay=delay, + dig_on_attack=rng.choice([False, True]), + begin_using=rng.choice([False, True])) + # A player interaction returning PASS must go directly to the held item. + # The level still reports a solid block underneath the entity hit. + for entity in [False, True]: + for clicks in [[1], [1, 1], [0, 1], [1, 2]]: + yield dict(using=False, destroying=False, attack_down=False, use_down=False, + entity=entity, clicks=clicks, delay=0, dig_on_attack=False, + begin_using=False, passing=True) + + +def main(): + def inputs(build): + rows = list(corpus()) + path = build / "inputs.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + return path, len(rows) + + harness.differential( + "interaction-input-parity", "VanillaInteractionInputOracle", "interaction_input_fixture", inputs, + "Invokes Minecraft.handleKeybinds itself with real KeyMapping click counters. " + "Compares attack/use/pick ordering, release gating, drained clicks during use, " + "held-button repetition and use cooldowns for block/entity targets. " + "Includes passing entity interactions over solid blocks: only the held " + "item may be tried afterward. " + "Game-mode side effects and world simulation are controlled fixtures.", + sources=[lab.ROOT / "crates/horizon-client/src/interaction_input.rs", + lab.ROOT / "crates/horizon-client/src/game/remote.rs", + lab.ROOT / "crates/horizon-client/src/game/hand.rs", + lab.ROOT / "mods/horizon/src/test/java/dev/horizonlab/parity/ParityData.java"]) + + +if __name__ == "__main__": + main() diff --git a/tools/test_player_sync_parity.py b/tools/test_player_sync_parity.py new file mode 100644 index 000000000..4c78b439f --- /dev/null +++ b/tools/test_player_sync_parity.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +"""Compare movement packet selection and teleport velocity with the pinned client.""" +import json +import random +import struct + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab, oracle_harness as harness + + +def corpus(): + # Stationary heartbeats, rotation-only updates, status changes and corrected + # positions followed by unchanged looks must retain vanilla's packet types. + yield dict(kind="movement", ops=[[0, 0, 0, 0, 0, False, False]] * 61) + yield dict(kind="movement", ops=[ + [0, 64, 0, 90, 0, True, False], + [0, 64, 0, 90, 0, True, False], + [0, 64, 0, 91, 0, True, False], + [100, 80, -20, 180, 20, False, False], + [100, 80, -20, 180, 20, True, False], + [100, 80, -20, 180, 20, True, True], + ]) + rng = random.Random(0x53594E43) + for _ in range(300): + state = [0, 0, 0, 0, 0, False, False] + ops = [] + for _ in range(80): + if rng.random() < 0.5: + axis = rng.randrange(3) + state[axis] += rng.choice([0, 0.0001, 0.0002, 0.0002000001, 0.1, 10]) + if rng.random() < 0.3: + state[3] += rng.choice([-360, -1, 0, 0.001, 1, 360]) + state[4] = rng.choice([-90, 0, 30, 90]) + if rng.random() < 0.2: + state[rng.randrange(5, 7)] = rng.choice([False, True]) + ops.append(state.copy()) + yield dict(kind="movement", ops=ops) + for flags in range(16): + for _ in range(40): + yield dict(kind="velocity", flags=flags << 5, + velocity=[rng.uniform(-4, 4) for _ in range(3)], + delta=[rng.uniform(-4, 4) for _ in range(3)], + old=[rng.uniform(-720, 720), rng.uniform(-90, 90)], + new=[rng.uniform(-720, 720), rng.uniform(-90, 90)]) + + +def main(): + def inputs(build): + rows = list(corpus()) + def bits(v): + return struct.pack(">d", v).hex() + for row in rows: + if row["kind"] == "movement": + row["ops"] = [[*map(bits, op[:5]), *op[5:]] for op in row["ops"]] + else: + for key in ["velocity", "delta", "old", "new"]: + row[key] = list(map(bits, row[key])) + path = build / "inputs.jsonl" + path.write_text("".join(json.dumps(row) + "\n" for row in rows)) + return path, len(rows) + + harness.differential( + "player-sync-parity", "VanillaPlayerSyncOracle", "player_sync_fixture", inputs, + "Actual LocalPlayer.sendPosition packet payloads over persistent movement " + "sequences; PositionMoveRotation.calculateAbsolute velocity with every " + "relative-delta/rotate-delta combination. World simulation, connection " + "scheduling and live anticheat behaviour are outside this harness.", + sources=[lab.ROOT / "crates/horizon-client/src/player_sync.rs", + lab.ROOT / "crates/horizon-client/src/game/remote.rs", + lab.ROOT / "crates/horizon-client/src/net.rs"]) + + +if __name__ == "__main__": + main() diff --git a/tools/test_server_entities_parity.py b/tools/test_server_entities_parity.py index e512239e8..500497275 100644 --- a/tools/test_server_entities_parity.py +++ b/tools/test_server_entities_parity.py @@ -6,13 +6,17 @@ world vanilla generated first, with the same server.properties (offline, view di client (VanillaProtocolClient in its entity mode) joins, and once its chunks are in it asks for the scene: the console freezes the ticks, builds a wall and a rail and summons, around the spawn, every kind of minecart (one set rolling along the rail), boats and a raft (one falling onto the ground), armor stands (posed, small, with -arms, wearing a helmet, one falling), a chicken jockey, item frames (one holding a turned diamond), paintings, -primed TNT (one falling), a floating falling block, an arrow that lands and an end crystal. The client records -for 20 seconds, the ticks running for 200 more after 3, what ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn +arms, wearing a helmet, one falling), a chicken jockey, a slime, a pig whose scale `/attribute` sets, item +frames (one holding a turned diamond), paintings, primed TNT (one falling), a floating falling block, an arrow +that lands and an end crystal. The client records for 20 seconds, the ticks running for 200 more after 3, what +ClientPacketListener would make of the packets (EntityTranscript): each entity's spawn packet (position, rotations, data, motion), the entity data it was paired with and all it was sent since, its -equipment and passengers, and where its position syncs leave it. Both transcripts must match exactly, -entity by entity (named by type and the block it was added in). Attributes are recorded but not compared yet: -Horizon sends no ClientboundUpdateAttributesPacket, for mobs either. +equipment, its attribute instances (ClientboundUpdateAttributesPacket: the ones its first tick creates, the +type's set by finalizeSpawn, the baby speed modifier, effects', equipment's and /attribute's) and passengers, and +where its position syncs leave it; and the attribute instances the player itself is sent from its login on. Both +transcripts must match exactly, entity by entity (named by type and the block it was added in), once the amounts +of vanilla's random spawn modifiers are normalised (only client-syncable attributes are sent, so follow range and +knockback resistance never show). """ import os from pathlib import Path @@ -63,6 +67,10 @@ SCENE = [ 'Pose:{Head:[10f,20f,0f],RightArm:[-30f,0f,15f]},equipment:{head:{id:"minecraft:diamond_helmet",count:1}}}', # A chicken jockey (passengers). 'summon minecraft:chicken -6.5 -60 -2.5 {NoAI:1b,Passengers:[{id:"minecraft:husk",IsBaby:1b,NoAI:1b}]}', + # Attributes: a slime's size sets its bases, /attribute a pig's scale. + 'summon minecraft:slime 2.5 -60 1.5 {Size:1,NoAI:1b}', + 'summon minecraft:pig -0.5 -60 1.5 {NoAI:1b}', + 'attribute @e[type=minecraft:pig,limit=1,x=-0.5,y=-60,z=1.5,distance=..1] minecraft:scale base set 1.5', # Frames and paintings on the wall's south face. 'summon minecraft:item_frame -3.5 -59 -4.97 {block_pos:[I;-4,-59,-5],Facing:3b,' 'Item:{id:"minecraft:diamond",count:1},ItemRotation:3b}', @@ -78,14 +86,19 @@ SCENE = [ ] +# finalizeSpawn's random modifiers on client-syncable attributes (a leader zombie's max health); their amounts +# differ from one server to the other. +RANDOM_MODIFIERS = re.compile(r'(id=minecraft:(?:random_spawn_bonus|leader_zombie_bonus), amount=)[^,]+') + + def scene_lines(lines): - """The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), - without their attributes: ClientboundUpdateAttributesPacket isn't sent by Horizon yet, for mobs either.""" + """The transcript's entities in the scene's area (the world's own animals and slimes wander elsewhere), the + amounts of random spawn modifiers normalised.""" out = [] for line in lines: m = re.match(r'play-entities entity \S+ (-?\d+),-?\d+,(-?\d+)', line) - if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10: - out.append(re.sub(r' \| attributes \{[^|]*\}', '', line)) + if m and -8 <= int(m.group(1)) <= 8 and -7 <= int(m.group(2)) <= 10 or line.startswith('play-entities self '): + out.append(RANDOM_MODIFIERS.sub(r'\1~', line)) return out @@ -171,10 +184,10 @@ def main(): schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], entities=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), - scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, item frames, paintings, primed ' - 'TNT, a falling block, an arrow and an end crystal tracked to a ' - 'vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, passengers and the ' - 'positions the syncs leave them at.')) + scope='Minecarts (one rolling), boats (one falling), armor stands, a chicken jockey, a slime, a pig with a ' + 'scale, item frames, paintings, primed TNT, a falling block, an arrow and an end crystal ' + 'tracked to a vanilla-codec client by a dedicated server: spawn packets, entity data, equipment, ' + 'attributes, passengers and the positions the syncs leave them at.')) print(f'server entities: {len(vanilla)} entities identical') diff --git a/tools/test_server_player_targets_parity.py b/tools/test_server_player_targets_parity.py new file mode 100644 index 000000000..f8f457143 --- /dev/null +++ b/tools/test_server_player_targets_parity.py @@ -0,0 +1,199 @@ +#!/usr/bin/env python3 +"""Commands acting on other players of a dedicated server, against vanilla's, seen by vanilla clients. + +EntitySelector.findPlayers and EntityArgument's player targets: names, UUIDs, `@a`, `@p`, `@r`, `@s` under +`execute as`, from the console and from an operator, with `give`, `gamemode`, `tp` (to a place, to a player, with a +rotation, and into another level by `execute in`, the console's own level or the destination's), `effect give` and +`effect clear`, and `kill`. + +A vanilla dedicated server and Horizon's (`horizon-client --dedicated --nogui`) each serve a copy of one flat world +vanilla generated first, with Alice and Bob as operators in creative. LocatorBarClient joins them both (players made +of vanilla's protocol code) and records, step by step, the system chat each receives and what the server changes +about it: game mode events, teleports, inventory slots, effects, its death (with the death message), the other +players it is sent or loses and the levels it respawns into. Each player's lines in each step are compared exactly, +in sorted order (the packets of one step may leave in another order within the tick). The locator bar's waypoints +and what a death does besides its messages are left to their own harnesses. +""" +import hashlib +import os +from pathlib import Path +import platform +import shutil +import subprocess +import sys +import time +import uuid as uuidlib + +try: + from . import lab, test_rust_parity as base + from .test_dedicated_server_parity import Server + from .test_locator_bar_parity import generate_world, server_dir +except ImportError: + import lab + import test_rust_parity as base + from test_dedicated_server_parity import Server + from test_locator_bar_parity import generate_world, server_dir + +NAME = 'server-player-targets-parity' +NETHER, OVERWORLD = 'minecraft:the_nether', 'minecraft:overworld' + + +def offline_uuid(name): + """UUIDUtil.createOfflinePlayerUUID.""" + digest = bytearray(hashlib.md5(f'OfflinePlayer:{name}'.encode()).digest()) + digest[6] = (digest[6] & 0x0F) | 0x30 + digest[8] = (digest[8] & 0x3F) | 0x80 + return str(uuidlib.UUID(bytes=bytes(digest))) + + +# (label, what the console does, what the players do). +SCRIPT = [ + ('console-give', ['give Bob minecraft:diamond 3'], []), + ('console-give-all', ['give @a minecraft:apple'], []), + ('alice-give-bob', [], ['cmd Alice give Bob minecraft:stick 2']), + ('console-give-uuid', [f'give {offline_uuid("Bob")} minecraft:iron_ingot'], []), + ('console-give-nearest', ['give @p minecraft:emerald'], []), + ('alice-give-random', [], ['cmd Alice give @r[name=Bob] minecraft:gold_ingot']), + ('console-gamemode', ['gamemode survival Bob'], []), + ('alice-gamemode-bob', [], ['cmd Alice gamemode creative Bob']), + ('alice-gamemode-all', [], ['cmd Alice gamemode adventure @a']), + ('console-gamemode-back', ['gamemode creative @a'], []), + ('console-tp', ['tp Bob 8.5 -60 8.5'], []), + ('alice-tp-bob-to-alice', [], ['cmd Alice tp Bob Alice']), + ('console-tp-rotation', ['tp Bob 4.5 -60 0.5 90 10'], []), + ('bob-tp-self', [], ['cmd Bob tp @s 6.5 -60 0.5']), + ('console-execute-as', ['execute as Bob run tp @s ~ ~ ~2'], []), + ('console-execute-at', ['execute at Bob run tp Alice ~1 ~ ~'], []), + ('alice-execute-as-all', [], ['cmd Alice execute as @a run give @s minecraft:bread']), + ('console-effect', ['effect give Bob minecraft:speed 30 1'], []), + ('alice-effect-all', [], ['cmd Alice effect give @a minecraft:haste infinite']), + ('console-effect-clear', ['effect clear Bob'], []), + ('alice-effect-clear-all', [], ['cmd Alice effect clear @a minecraft:haste']), + ('console-nether', [f'execute in {NETHER} run tp Bob 0.5 100 0.5'], []), + ('console-tp-home', ['tp Bob 4.5 -60 0.5'], []), + ('alice-nether', [], [f'cmd Alice execute in {NETHER} run tp Bob 0.5 100 0.5']), + ('console-tp-to-alice', ['tp Bob Alice'], []), + ('alice-kill-missing', [], ['cmd Alice kill Carol']), + ('console-kill', ['kill Bob'], []), +] +# What the players' locator bars show has its own harness (test_locator_bar_parity), and what a death does +# besides its messages (drops, the body leaving) the player combat ones: here only the messages of `kill`. +WAYPOINTS = ('track ', 'untrack ', 'update ') +DEATH_STEP = 'step=console-kill' +STEP_SECONDS = 2.5 + + +def run_side(label, server_command, client_command, build, world): + directory = build / label + port = server_dir(directory, world) + out = build / f'{label}.txt' + out.unlink(missing_ok=True) + server = Server(server_command, directory, label) + try: + server.wait_for(r'Done \(') + with (build / f'{label}-client.log').open('w') as log: + client = subprocess.Popen([*map(str, client_command), '127.0.0.1', str(port), str(out)], + cwd=lab.ROOT, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT, + text=True) + + def tell(line): + client.stdin.write(line + '\n') + client.stdin.flush() + try: + for name, x in (('Alice', 0.5), ('Bob', 4.5)): + tell(f'join {name}') + server.wait_for(rf'{name} joined the game', timeout=120) + tell(f'fly {name} on') + tell(f'cmd {name} tp @s {x} -60 0.5 0 0') + time.sleep(STEP_SECONDS) + for flag in ('chat', 'state', 'players'): + tell(f'{flag} on') + for step, console, actions in SCRIPT: + tell(f'step {step}') + for command in console: + server.console(command) + for action in actions: + tell(action) + time.sleep(STEP_SECONDS) + for name in ('Alice', 'Bob'): + tell(f'still {name}') + tell('end') + client.wait(timeout=60) + finally: + if client.poll() is None: + client.kill() + finally: + server.stop() + if not out.exists(): + raise AssertionError(f'{label}: the client wrote no transcript (see {build}/{label}-client.log)') + lines = out.read_text(encoding='utf-8').splitlines() + errors = [l for l in lines if ' error ' in f' {l} ' or 'disconnected' in l] + steps = {} + for line in lines: + who, step, rest = line.split(' ', 2) + # At the death, Alice picks up Bob's drops (and gets their advancements) in vanilla. + death_side = step == DEATH_STEP and (not rest.startswith(('chat ', 'killed ')) + or 'chat.type.advancement' in rest) + if rest.startswith(WAYPOINTS) or death_side: + continue + if step != 'step=start': + steps.setdefault((who, step), []).append(line) + order = {f'step={s}': i for i, (s, _, _) in enumerate(SCRIPT)} + keys = sorted(steps, key=lambda k: (k[0], order.get(k[1], -1))) + return [l for k in keys for l in sorted(steps[k])], errors + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / NAME + build.mkdir(parents=True, exist_ok=True) + report = build / 'report.json' + report.unlink(missing_ok=True) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/LocatorBarClient.java' + classes = build / 'classes' + shutil.rmtree(classes, ignore_errors=True) + classes.mkdir() + dependencies = os.pathsep.join(map(str, [jars['server'], *libraries])) + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-sourcepath', + lab.ROOT / 'mods/horizon/src/test/java', '-cp', dependencies, '-d', classes, oracle], + cwd=lab.ROOT, check=True, capture_output=True) + subprocess.run(['cargo', 'build', '--release', '-p', 'horizon-client', '--bin', 'horizon-client'], cwd=lab.ROOT, + check=True, capture_output=True) + import json + metadata = json.loads(subprocess.check_output(['cargo', 'metadata', '--no-deps', '--format-version', '1'], + cwd=lab.ROOT, text=True)) + binary = Path(metadata['target_directory']) / 'release' / ('horizon-client.exe' if os.name == 'nt' else 'horizon-client') + vanilla_server = ['java', '-Xmx2g', '-Duser.timezone=UTC', '-cp', dependencies, 'net.minecraft.server.Main', 'nogui'] + horizon_server = [binary, '--resources', lab.LOCAL / 'horizon-client/26.3', '--dedicated', '--nogui'] + client = ['java', '-Xmx1g', '-cp', str(classes) + os.pathsep + dependencies, 'dev.horizonlab.parity.LocatorBarClient'] + + world = generate_world(vanilla_server, build) + vanilla, vanilla_errors = run_side('vanilla', vanilla_server, client, build, world) + horizon, horizon_errors = run_side('horizon', horizon_server, client, build, world) + (build / 'vanilla.txt').write_text('\n'.join(vanilla) + '\n', encoding='utf-8') + (build / 'horizon.txt').write_text('\n'.join(horizon) + '\n', encoding='utf-8') + errors = vanilla_errors + horizon_errors + if errors or vanilla != horizon: + import difflib + diff = '\n'.join(difflib.unified_diff(vanilla, horizon, 'vanilla', 'horizon', n=1, lineterm='')) + raise AssertionError(f'{len(errors)} errors, transcripts differ (see {build}/vanilla.txt and horizon.txt):\n' + + '\n'.join(errors[:10]) + '\n' + diff[:8000]) + for needle in ('gamemode 0', 'minecraft:diamond x3', 'effect minecraft:speed', 'respawn ' + NETHER, + 'death.attack.genericKill'): + if not any(needle in l for l in vanilla): + raise AssertionError(f'vanilla never sent {needle!r}: the script did not run (see {build})') + lab.write_json(report, dict( + schema=1, minecraft=lock['minecraft']['version'], platform=platform.platform(), + java=subprocess.check_output(['java', '--version'], text=True).splitlines()[0], + lines=len(vanilla), output_sha256=lab.digest(build / 'horizon.txt', 'sha256'), + scope='Commands from the console and an operator acting on another player of a dedicated server: names, ' + 'UUIDs, @a, @p, @r and @s under execute as/at, with give, gamemode, tp (place, player, rotation, ' + 'execute in, across levels), effect give and clear and kill, as the players see them.')) + print(f'server player targets: {len(vanilla)} lines identical') + + +if __name__ == '__main__': + try: + main() + except AssertionError as error: + sys.exit(f'{NAME}: {error}') diff --git a/tools/vanilla_client.py b/tools/vanilla_client.py index 88c6aba5b..41ae38556 100644 --- a/tools/vanilla_client.py +++ b/tools/vanilla_client.py @@ -5,6 +5,10 @@ servers: --offlineDeveloperMode) and optionally join a server straight away vscreen start python3 tools/vanilla_client.py --name Guest --join localhost:25565 +On Linux (x86_64) and on macOS (Apple silicon, from the logged-in screen session), from the files +tools/lab.py prepared on that machine. On macOS vsync is off: with it on, a window nobody can see (a +locked session, or covered) blocks in SDL_GL_SwapWindow and the client stops before it joins. + Sound goes to OpenAL's null backend. The game directory gets an options.txt that skips the first-run screens, keeps the game running unfocused and renders few chunks, so a harness can drive it with vscreen keys. @@ -21,6 +25,9 @@ from pathlib import Path ROOT = Path(__file__).resolve().parents[1] GAME = ROOT / ".local/minecraft/26.3" +MAC = sys.platform == "darwin" +# The natives of this machine's platform, and the shared libraries in them. +NATIVES, LIBRARY_SUFFIX = ("natives-macos-arm64.jar", ".dylib") if MAC else ("natives-linux.jar", ".so") OPTIONS = { "onboardAccessibility": "false", @@ -40,6 +47,8 @@ OPTIONS = { "onlyShowSecureChat": "false", "rawMouseInput": "false", } +if sys.platform == "darwin": + OPTIONS["enableVsync"] = "false" def offline_uuid(name): @@ -49,10 +58,12 @@ def offline_uuid(name): return uuid.UUID(bytes=bytes(digest)) -def linux_library(path): +def host_library(path): name = Path(path).name if "natives-" in name: - return name.endswith("natives-linux.jar") + return name.endswith(NATIVES) + if MAC: + return "netty-transport-native" not in name or "linux" not in name if "netty-transport-native" in name and ("osx" in name or "aarch_64" in name): return False return "java-objc-bridge" not in name @@ -60,18 +71,18 @@ def linux_library(path): def classpath(): prepared = json.loads((GAME / "prepared.json").read_text()) - jars = [ROOT / p for p in prepared["libraries"]["client"] if linux_library(p)] + jars = [ROOT / p for p in prepared["libraries"]["client"] if host_library(p)] return [GAME / "jars/client.jar", *jars] def extract_natives(jars, target): target.mkdir(parents=True, exist_ok=True) for jar in jars: - if not jar.name.endswith("natives-linux.jar"): + if not jar.name.endswith(NATIVES): continue with zipfile.ZipFile(jar) as archive: for name in archive.namelist(): - if name.endswith(".so") and "arm" not in name and "aarch" not in name: + if name.endswith(LIBRARY_SUFFIX) and (MAC or ("arm" not in name and "aarch" not in name)): out = target / Path(name).name if not out.exists(): out.write_bytes(archive.read(name)) @@ -105,7 +116,7 @@ def command(args): extract_natives(jars, natives) assets = args.assets or (args.game_dir / "assets") (assets / "indexes").mkdir(parents=True, exist_ok=True) - cmd = ["java", f"-Xmx{args.heap}", "-XX:StackShadowPages=32", + cmd = ["java", f"-Xmx{args.heap}", *(["-XstartOnFirstThread"] if MAC else []), "-XX:StackShadowPages=32", "--enable-native-access=ALL-UNNAMED", "--add-exports", "java.base/jdk.internal.misc=ALL-UNNAMED", f"-Djava.library.path={natives}", f"-Dorg.lwjgl.system.SharedLibraryExtractPath={natives}", diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 05b84553b..28b591626 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -6,6 +6,10 @@ //! them to its own), and PLAY.txt. It holds none of Minecraft's files: players prepare those //! from their own copy. .github/workflows/release.yml makes the release folders with it. //! +//! `package-server ENGINE OUTDIR`: a server folder (docs/server.md): the server build of the game +//! (`cargo build --release -p horizon-client --no-default-features`, without sound or controllers) +//! as horizon-engine, with horizon-prepare and horizon-server from beside it and the same sources. +//! //! `tokens`: writes `website/src/tokens.css`, the design tokens of `crates/horizon-theme` as CSS //! custom properties (a horizon-theme test fails when the file is out of date). //! @@ -17,7 +21,7 @@ use std::fs; use std::path::{Component, Path, PathBuf}; use std::process::{Command, ExitCode}; -const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR | tokens | icons"; +const USAGE: &str = "usage: cargo run -p xtask -- package BINARY OUTDIR | package-server ENGINE OUTDIR | tokens | icons"; /// What the release folder takes from the repository at HEAD, as `git archive` writes it. const ARCHIVED: [&str; 5] = [ @@ -34,10 +38,16 @@ const ARCHIVED: [&str; 5] = [ /// (docs/server.md). const TOOLS: [&str; 3] = ["horizon-ctl", "horizon-prepare", "horizon-server"]; +/// The programs beside the engine in a server folder. +const SERVER_TOOLS: [&str; 2] = ["horizon-prepare", "horizon-server"]; + fn main() -> ExitCode { let args: Vec<String> = std::env::args().skip(1).collect(); let result = match args.as_slice() { [task, binary, out] if task == "package" => package(Path::new(binary), Path::new(out)), + [task, engine, out] if task == "package-server" => { + package_server(Path::new(engine), Path::new(out)) + } [task] if task == "tokens" => tokens(), [task] if task == "icons" => icons(), _ => Err(USAGE.to_string()), @@ -209,6 +219,21 @@ fn icons() -> Result<(), String> { } fn package(binary: &Path, out: &Path) -> Result<(), String> { + let repo = new_folder(out)?; + copy_into(binary, out)?; + copy_beside(binary, &TOOLS, out)?; + let play = repo.join("packaging/PLAY.txt"); + copy(&play, &out.join("PLAY.txt")) +} + +fn package_server(engine: &Path, out: &Path) -> Result<(), String> { + new_folder(out)?; + copy(engine, &out.join(program_name(engine, "horizon-engine")))?; + copy_beside(engine, &SERVER_TOOLS, out) +} + +/// `OUT`, emptied, with the sources the release folders take (`ARCHIVED`); the repository's path. +fn new_folder(out: &Path) -> Result<PathBuf, String> { let top = git( Path::new(env!("CARGO_MANIFEST_DIR")), &["rev-parse", "--show-toplevel"], @@ -224,15 +249,25 @@ fn package(binary: &Path, out: &Path) -> Result<(), String> { let mut args = vec!["archive", "--format=tar", "HEAD"]; args.extend(ARCHIVED); extract(&git(&repo, &args)?, out)?; - copy_into(binary, out)?; - let exe = binary.extension().is_some_and(|e| e == "exe"); - for tool in TOOLS { - let name = if exe { - format!("{tool}.exe") - } else { - tool.to_string() - }; - let path = binary.parent().unwrap_or(Path::new("")).join(name); + Ok(repo) +} + +/// `name`, with `.exe` when `program` has it. +fn program_name(program: &Path, name: &str) -> String { + if program.extension().is_some_and(|e| e == "exe") { + format!("{name}.exe") + } else { + name.to_string() + } +} + +/// Copies `tools`, built beside `program`, into `out`. +fn copy_beside(program: &Path, tools: &[&str], out: &Path) -> Result<(), String> { + for tool in tools { + let path = program + .parent() + .unwrap_or(Path::new("")) + .join(program_name(program, tool)); if !path.is_file() { return Err(format!( "{} is missing; build it too: cargo build --release -p horizon-client --bins -p horizon-prepare -p horizon-server", @@ -241,8 +276,7 @@ fn package(binary: &Path, out: &Path) -> Result<(), String> { } copy_into(&path, out)?; } - let play = repo.join("packaging/PLAY.txt"); - copy(&play, &out.join("PLAY.txt")) + Ok(()) } /// `cp FILE DIR/`.