diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 000000000..8d8687753 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,17 @@ +# Changes to these files wait for Ludovic's review once branch protection requires code owners' reviews +# (tools/ci/protect_pipeline.sh, docs/security.md). They are what builds, signs and ships releases, the code that +# checks downloads before installing them (backend.rs downloads, installs and updates the launcher itself; links.json +# says where from; the Cargo.toml files pick the crates that do it), and this file. Everything else merges as soon as +# `verify` passes. +/.github/ @ludovic111 +/tools/ci/ @ludovic111 +/tools/release_train.py @ludovic111 +/tools/release_channels.py @ludovic111 +/crates/horizon-release-sign/ @ludovic111 +/crates/horizon-server/src/update.rs @ludovic111 +/crates/horizon-server/Cargo.toml @ludovic111 +/launcher/src/signed.rs @ludovic111 +/launcher/src/backend.rs @ludovic111 +/launcher/links.json @ludovic111 +/launcher/Cargo.toml @ludovic111 +/packaging/ @ludovic111 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index da23874b8..d6577d49e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,23 +1,25 @@ name: checks -# verify: every pull request and every push to main, on GitHub's runners (the repository is public). +# verify: every pull request and every push to main, on GitHub's runners (the repository is public). It is the +# check main requires, so it never has a condition: a skipped job counts as passed, and every run of this workflow +# must report a real verify (a pull request that changes no Rust finishes it in seconds instead). # parity: the vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the -# maintainer's own Minecraft files (Horizon never downloads the game). A fork's pull request runs it only when -# a maintainer adds the run-parity label, once per label. See docs/release-flow.md. +# maintainer's own Minecraft files (Horizon never downloads the game); .github/workflows/parity.yml. A fork's pull +# request runs it only when a maintainer adds the run-parity label (.github/workflows/run-parity.yml), so labels +# never start this workflow. See docs/release-flow.md. on: push: branches: [main] pull_request: - types: [opened, synchronize, reopened, labeled] + types: [opened, synchronize, reopened] workflow_dispatch: permissions: contents: read concurrency: # A new push to a pull request replaces its running checks; main's runs all finish (releases follow them). - group: checks-${{ github.event.pull_request.number || github.sha }}-${{ github.event.action == 'labeled' && 'label' || 'run' }} + group: checks-${{ github.event.pull_request.number || github.sha }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: verify: - if: github.event.action != 'labeled' runs-on: ubuntu-latest timeout-minutes: 30 steps: @@ -62,38 +64,11 @@ jobs: if: steps.rust.outputs.required != 'false' run: cargo +stable test --workspace parity: - if: >- - github.event_name == 'pull_request' && ( - (github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') || - (github.event.action == 'labeled' && github.event.label.name == 'run-parity')) - runs-on: [self-hosted, horizon-game] - timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini - steps: - - uses: actions/checkout@v4 - with: - # The commit the event names: a fork's later pushes need another run-parity label. - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 0 - persist-credentials: false - # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. - clean: false - - uses: dtolnay/rust-toolchain@stable - - name: Tools from the runner - run: bash tools/ci/runner-env.sh - - name: Vanilla data, and resources prepared by this preparer - run: bash tools/ci/vanilla-data.sh - - name: The harnesses this change can affect - env: - PARITY_HOSTS: '' - run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 2400 # world_spawn takes ~1480 s on a busy runner - - name: Logs of the failed harnesses - if: failure() - uses: actions/upload-artifact@v4 - with: - name: parity-logs - path: .local/parity-runner/logs/ - if-no-files-found: ignore - retention-days: 3 + if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository + uses: ./.github/workflows/parity.yml + with: + base: ${{ github.event.pull_request.base.sha }} + head: ${{ github.event.pull_request.head.sha }} # Horizon never downloads the game. These jobs need a self-hosted Linux runner # (label horizon-game) holding the maintainer's own copy: the official launcher's # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in diff --git a/.github/workflows/launcher.yml b/.github/workflows/launcher.yml index c902acf32..e7b55c64b 100644 --- a/.github/workflows/launcher.yml +++ b/.github/workflows/launcher.yml @@ -120,8 +120,9 @@ jobs: with: ref: ${{ needs.decide.outputs.head }} persist-credentials: false - # The Mac mini's runner keeps its target/ between runs. - clean: ${{ runner.environment == 'github-hosted' }} + # Always from a clean checkout, the Mac mini's runner too: its work folder is shared with pull requests' + # parity jobs, and nothing they leave may end up in a launcher release (target/ is rebuilt from scratch). + clean: true - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 if: runner.environment == 'github-hosted' @@ -218,10 +219,49 @@ jobs: path: launcher/out/* retention-days: 3 - release: + sign: needs: [decide, build] runs-on: ubuntu-latest timeout-minutes: 10 + # The only job that holds the release signing key, a secret of the `release` environment, which only main's real + # releases enter (dry runs sign with a throwaway key). It runs no code from the repository but + # tools/ci/sign_release.sh, which calls only the runner's sha256sum and OpenSSL (docs/release-flow.md). + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: tools/ci/sign_release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: horizon-launcher-* + merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig) + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + TAG: ${{ needs.decide.outputs.tag }} + run: bash tools/ci/sign_release.sh "$TAG" dist/horizon-launcher-* + - uses: actions/upload-artifact@v4 + with: + name: signature + path: dist/SHA256SUMS* + if-no-files-found: error + retention-days: 3 + - uses: actions/upload-artifact@v4 + if: needs.decide.outputs.dry_run == 'true' + with: + name: ephemeral.pub + path: dist/ephemeral.pub + retention-days: 3 + + release: + needs: [decide, build, sign] + runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: write steps: @@ -239,6 +279,13 @@ jobs: with: path: dist merge-multiple: true + - name: The signature, checked as launchers check it + env: + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") + cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist # Never marked latest: Horizon's own releases stay the repository's latest. - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' @@ -246,8 +293,9 @@ jobs: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \ - --notes-file notes/body.md --latest=false dist/horizon-launcher-* + --notes-file notes/body.md --latest=false dist/horizon-launcher-* dist/SHA256SUMS "${signature[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/.github/workflows/parity.yml b/.github/workflows/parity.yml new file mode 100644 index 000000000..ef03b6df2 --- /dev/null +++ b/.github/workflows/parity.yml @@ -0,0 +1,48 @@ +name: parity +# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the maintainer's +# own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository +# and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md. +on: + workflow_call: + inputs: + base: + description: The pull request's base commit (the harnesses its changes since then can affect) + type: string + required: true + head: + description: The commit to check out and test + type: string + required: true +permissions: + contents: read +jobs: + parity: + runs-on: [self-hosted, horizon-game] + timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini + steps: + - uses: actions/checkout@v4 + with: + # The commit the event names: a fork's later pushes need another run-parity label. + ref: ${{ inputs.head }} + fetch-depth: 0 + persist-credentials: false + # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. + clean: false + - uses: dtolnay/rust-toolchain@stable + - name: Tools from the runner + run: bash tools/ci/runner-env.sh + - name: Vanilla data, and resources prepared by this preparer + run: bash tools/ci/vanilla-data.sh + - name: The harnesses this change can affect + env: + PARITY_HOSTS: '' + BASE_SHA: ${{ inputs.base }} + run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner + - name: Logs of the failed harnesses + if: failure() + uses: actions/upload-artifact@v4 + with: + name: parity-logs + path: .local/parity-runner/logs/ + if-no-files-found: ignore + retention-days: 3 diff --git a/.github/workflows/promote.yml b/.github/workflows/promote.yml new file mode 100644 index 000000000..b7ef0b38b --- /dev/null +++ b/.github/workflows/promote.yml @@ -0,0 +1,52 @@ +name: promote +# Beta game releases become stable (docs/release-flow.md, "Channels"): every 30 minutes tools/release_channels.py +# promotes the newest beta that has been out 6 hours, passed its release smoke test and isn't covered by an issue +# labelled release-blocker. By hand, from GitHub's app too (Actions > promote > Run workflow): +# gh workflow run promote -f tag=v2026.10.19.03 # that beta now, without the wait +# gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without its smoke test +# gh workflow run promote -f dry_run=true # say what would be promoted +# Holding betas back: label an issue release-blocker. While it is open it holds every beta; closed as completed it +# still holds the betas published before it closed. The issue's text is never read (its author could edit it). +# When the oldest waiting beta is 24 hours old, an issue "Promotion to stable has stalled" says so; it closes itself +# after the next promotion. +on: + schedule: + - cron: '13,43 * * * *' + workflow_dispatch: + inputs: + tag: + description: The beta to promote now (empty = the newest beta that is due) + type: string + default: '' + force: + description: Promote that tag even if a release-blocker covers it or its smoke test didn't run + type: boolean + default: false + dry_run: + description: Say what would be promoted, change nothing + type: boolean + default: false +permissions: + contents: write + issues: write +concurrency: + group: promote + cancel-in-progress: false +jobs: + promote: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@v4 + with: + # The notes of a promoted release cover every pull request since the last stable one. + fetch-depth: 0 + # gh uses GH_TOKEN below; nothing needs git credentials on disk. + persist-credentials: false + - name: Promote + env: + GH_TOKEN: ${{ github.token }} + TAG: ${{ inputs.tag }} + FORCE: ${{ inputs.force && 'yes' || '' }} + DRY_RUN: ${{ (inputs.dry_run || github.ref != 'refs/heads/main') && 'yes' || '' }} + run: python3 tools/release_channels.py promote ${TAG:+--tag "$TAG"} ${FORCE:+--force} ${DRY_RUN:+--dry-run} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index bd916514b..546c6707e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -6,7 +6,8 @@ name: release # RELEASES_PAUSED=1 (repository variable) stops them. # Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and # Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then -# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests. +# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests, as a beta (a pre-release) that promote.yml makes +# stable after 6 hours. # gh workflow run release --ref # dry run: builds and notes, publishes nothing # gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say on: @@ -102,8 +103,11 @@ jobs: with: ref: ${{ needs.decide.outputs.head }} persist-credentials: false - # On the Mac mini's runner, keep target/ (incremental) and .local/ (the prepared resources). - clean: ${{ runner.environment == 'github-hosted' }} + # Always from a clean checkout, the Mac mini's runner too: its work folder is shared with pull requests' + # parity jobs, and nothing they leave (target/, an untracked .cargo/config.toml, a build script's output) + # may end up in a release. target/ is rebuilt from scratch; .local/ is relinked by vanilla-data.sh, which + # keeps its preparations outside the checkout. + clean: true - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 if: runner.environment == 'github-hosted' @@ -168,6 +172,15 @@ jobs: or not report.get("meshed_sections") or not report.get("player"): sys.exit("the smoke run did not draw a world") EOF + # Published with the release: a beta becomes stable only with it (tools/release_channels.py). + cp "$home/smoke.json" "$RUNNER_TEMP/smoke-test.json" + - uses: actions/upload-artifact@v4 + if: runner.environment == 'self-hosted' + with: + name: smoke-test.json + path: ${{ runner.temp }}/smoke-test.json + if-no-files-found: error + retention-days: 3 - name: Package run: | set -euo pipefail @@ -217,10 +230,51 @@ jobs: if-no-files-found: error retention-days: 3 - publish: + sign: needs: [decide, build] runs-on: ubuntu-latest timeout-minutes: 10 + # The only job that holds the release signing key, a secret of the `release` environment, which only main's real + # releases enter (dry runs sign with a throwaway key). It runs no code from the repository but + # tools/ci/sign_release.sh, which calls only the runner's sha256sum and OpenSSL (docs/release-flow.md). + environment: ${{ needs.decide.outputs.dry_run != 'true' && 'release' || '' }} + steps: + - uses: actions/checkout@v4 + with: + sparse-checkout: tools/ci/sign_release.sh + sparse-checkout-cone-mode: false + persist-credentials: false + - uses: actions/download-artifact@v4 + with: + path: dist + pattern: horizon-* + merge-multiple: true + - name: Sign the checksums (SHA256SUMS, SHA256SUMS.sig) + env: + RELEASE_SIGNING_KEY: ${{ secrets.RELEASE_SIGNING_KEY }} + RELEASE_SIGNING_KEY_NEXT: ${{ secrets.RELEASE_SIGNING_KEY_NEXT }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + TAG: ${{ needs.decide.outputs.tag }} + run: | + bash tools/ci/sign_release.sh "$TAG" dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \ + dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz + - uses: actions/upload-artifact@v4 + with: + name: signature + path: dist/SHA256SUMS* + if-no-files-found: error + retention-days: 3 + - uses: actions/upload-artifact@v4 + if: needs.decide.outputs.dry_run == 'true' + with: + name: ephemeral.pub + path: dist/ephemeral.pub + retention-days: 3 + + publish: + needs: [decide, build, sign] + runs-on: ubuntu-latest + timeout-minutes: 15 permissions: contents: write steps: @@ -238,15 +292,26 @@ jobs: with: path: dist merge-multiple: true + - name: The signature, checked as launchers check it + env: + TAG: ${{ needs.decide.outputs.tag }} + EPHEMERAL: ${{ needs.decide.outputs.dry_run == 'true' && 'yes' || '' }} + run: | + key=(); [[ -n "$EPHEMERAL" ]] && key=(--key "$(cat dist/ephemeral.pub)") + cargo run --locked --quiet -p horizon-release-sign -- verify --tag "$TAG" --publishing "${key[@]}" dist - name: Publish ${{ needs.decide.outputs.tag }} if: needs.decide.outputs.dry_run != 'true' env: GH_TOKEN: ${{ github.token }} TAG: ${{ needs.decide.outputs.tag }} run: | + signature=(); [[ -f dist/SHA256SUMS.sig ]] && signature=(dist/SHA256SUMS.sig) + smoke=(); [[ -f dist/smoke-test.json ]] && smoke=(dist/smoke-test.json) + # A beta (pre-release): promote.yml makes it stable and latest after 6 hours (docs/release-flow.md). 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-server-linux-x86_64.tar.gz + --notes-file notes/body.md --prerelease --latest=false dist/horizon-linux-x86_64.tar.gz \ + dist/horizon-windows-x64.zip dist/horizon-macos-arm64.zip dist/horizon-server-linux-x86_64.tar.gz \ + dist/SHA256SUMS "${signature[@]}" "${smoke[@]}" - name: Dry run, the release that would be published if: needs.decide.outputs.dry_run == 'true' run: | diff --git a/.github/workflows/run-parity.yml b/.github/workflows/run-parity.yml new file mode 100644 index 000000000..fd3cce6f8 --- /dev/null +++ b/.github/workflows/run-parity.yml @@ -0,0 +1,20 @@ +name: run-parity +# A fork's pull request runs the parity job (parity.yml) on the Mac mini only when a maintainer who has read the +# change adds the run-parity label: once, on the commit the pull request has then. Remove the label and add it +# again after new pushes. A separate workflow, so that labels never start `checks`: there a label's run reported a +# skipped `verify`, and GitHub counts a skipped required check as passed. +on: + pull_request: + types: [labeled] +permissions: + contents: read +concurrency: + group: run-parity-${{ github.event.pull_request.number }} + cancel-in-progress: true +jobs: + parity: + if: github.event.label.name == 'run-parity' + uses: ./.github/workflows/parity.yml + with: + base: ${{ github.event.pull_request.base.sha }} + head: ${{ github.event.pull_request.head.sha }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 26bfb3759..af44d89f8 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -53,6 +53,11 @@ crates you touched (and the launcher's), generated files, `Cargo.lock`, the Pyth your change can affect. Without the vanilla data on your machine it lists those harnesses instead; CI runs them. `--quick` skips the harnesses. It exits non-zero when something fails. +For the game workspace, Clippy checks all targets of the touched crates and their transitive workspace dependents, +including examples. The dependency scope includes optional, platform, build and development dependencies. +Tests run library, binary, integration and doc tests without building unrelated example executables. Shared Cargo +configuration and toolchain changes select the whole workspace; CI also keeps its workspace-wide checks. + ## Pull requests - **Small.** One change per pull request, under about 500 lines of code where you can; split bigger work into @@ -66,6 +71,7 @@ your change can affect. Without the vanilla data on your machine it lists those `release-now` is for crash fixes that shouldn't wait. pr_ready suggests one. Every merge to main is released automatically ([release flow](docs/release-flow.md)), so main always stays playable. +How agents, checks, releases and signed updates keep this safe: [security](docs/security.md). ## Parity checks on forks diff --git a/Cargo.lock b/Cargo.lock index ea7bc6449..4100e167f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1554,6 +1554,14 @@ dependencies = [ "serde_json", ] +[[package]] +name = "horizon-release-sign" +version = "0.1.0" +dependencies = [ + "base64", + "ring", +] + [[package]] name = "horizon-server" version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml index 409bf4689..bc67ec748 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [workspace] exclude = ["launcher", "crates/horizon-telemetry-server", "third_party/wgpu-hal"] -members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] +members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/voxel-kernels", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-shaderpack", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"] resolver = "2" [workspace.package] diff --git a/README.md b/README.md index a1e6a38f6..6c83d867f 100644 --- a/README.md +++ b/README.md @@ -14,106 +14,64 @@

Website · Download · - What changed · - Screenshots · - Parity status · - Documentation + Documentation · + Release notes · + Project status · + Contributing

# Horizon -A Rust rewrite of Minecraft: Java Edition 26.3 built for one-to-one vanilla parity, checked against the game itself with differential tests. - -Every subsystem matches vanilla in all 281 parity harnesses, on Linux and macOS: 100% of what the harnesses compare (see [Project status](#project-status)). The native client is playable on Linux, macOS (Apple Silicon) and Windows. +Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that reads the same worlds, follows the same rules and generates the same terrain as the Java game, and is checked against it by 281 differential harnesses. You play it through a small launcher, on the files from your own copy of Minecraft. It is free, open source and unofficial. > Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3. -## What changed in v2026.10.13.1 - -The latest release ([notes](https://github.com/ludovic111/horizon/releases/tag/v2026.10.13.1)): - -- **Horizon's own menus:** a new title screen, world list, options and pause menu in the launcher's style, over a live frozen landscape. The vanilla look is still available: Options → Interface → Menu style → Classic. -- **Graphics settings, Simple and Advanced:** presets (Performance, Balanced, Quality, Ultra), or every rendering, quality, display and performance setting, each with a short description and its cost, plus a performance overlay. -- **Much faster rendering:** for example, at render distance 8 over a village, 363 → 2,409 FPS on an RTX 4080. Render distance 32 still stutters in places. -- **Fixed:** no sound on Linux; Linux builds that only ran on the machine they were built on; a missing DLL on Windows (the launcher no longer needs the Visual C++ runtime); memory growing and the frame rate dropping near villages (mobs were duplicated when chunks reloaded); resource preparation failing on Linux with "Missing … java-objc-bridge" ([#41](https://github.com/ludovic111/horizon/issues/41)); the hand and held item at high FOV; missing swing animations. - ## Download -Horizon is downloaded only through **the Horizon launcher**: get it from [playhorizon.dev](https://playhorizon.dev) or from [the launcher's releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true) (the newest `launcher-v*` release, currently [launcher-v0.1.3](https://github.com/ludovic111/horizon/releases/tag/launcher-v0.1.3)), for Linux x86-64, macOS Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its resources from your own copy of Minecraft, starts the client or a dedicated server, and updates itself. +Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/ludovic111/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your own copy of Minecraft, and updates itself. -**You need** Minecraft: Java Edition installed with the official launcher, with 26.3 played once; Python 3.10 or newer and Java 25 (a JDK, e.g. Eclipse Temurin 25) for the one-time resource preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. - -**Host a server:** `horizon-server` is one native program with no Java, one settings file, a command line, a web panel, backups and updates that roll back by themselves. It installs with one command (`curl -fsSL https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.sh | sh` on Linux and macOS, `irm https://raw.githubusercontent.com/ludovic111/horizon/main/packaging/server/install.ps1 | iex` on Windows). The guide is at [playhorizon.dev/server](https://playhorizon.dev/server) ([docs/hosting.md](docs/hosting.md)). - -### The launcher +**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 JDK, for the one-time preparation; and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install). - - + +
The launcher's Play page: v2026.10.14.1 ready to play, its summary, Client and Server, the version picker and Play, the resources and the Minecraft folder as a numbered listThe launcher's Patch notes page, showing the notes of Horizon 2026.10.14.1The launcher's Play page: a version ready to play, its summary, Client and Server, the version picker and PlayThe launcher's Patch notes page
-It lists Horizon's releases and installs the build for your platform, shows each release's patch notes, updates Horizon and itself, and doubles as a command-line tool and an MCP server. See [the launcher's README](launcher/README.md). +## What works today -## Screenshots +The [documentation](https://playhorizon.dev/docs/) covers each of these. -Captured in the Rust client itself, with vanilla assets and no mods or shaders. +- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status). +- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings). +- **Resource packs, shader packs and data packs:** resource packs work, Java shader packs run their full-screen effects (experimental), and data packs load functions, predicates and item modifiers. +- **Playing with others:** invite friends from the pause menu with a code, Open to LAN, and joining offline-mode servers. Horizon cannot sign in to a Microsoft account yet, so it cannot join servers that check accounts. See [Multiplayer](https://playhorizon.dev/docs/multiplayer). +- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods). -### Menus and settings - - - - - - - - - -
Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, and the last world played and the faint wordmark, over a veiled snowy landscape
The Singleplayer page: two worlds with their dates and game modes, and Create world and Play buttonsThe Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
- -The vanilla menus are one setting away: Options → Interface → Menu style → Classic. See [Graphics settings](docs/graphics.md). - -### In game +Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders: + + + + - - - - - - - -
Sunset over a savanna river valley and a plains village
Horizon's title screen over a veiled snowy landscapeThe Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs
A plains village among savanna hills, with farms, villagers and an iron golemSurvival at dusk: a zombie walks up, with the hotbar, health, hunger and experience
A crimson forest in the Nether with a zombified piglinMoonrise over a torch-lit village and river
Tropical fish over a warm-ocean coral reef - Vanilla world generation ported to Rust (terrain, aquifers, carvers, features, villages and the Nether), every block model with smooth lighting and biome tints, the vanilla sky and fog, mobs and the HUD: everything in these frames is drawn by Horizon. -
-## What it does +## Host a server -Horizon reimplements the Minecraft Java client and its game logic in Rust, one subsystem at a time, and compares each piece with the vanilla game. Each `tools/test_*_parity.py` harness drives the same inputs through Horizon and through the vanilla client and server bytecode from your own copy of the game, then checks that the outputs are identical. It is for players and developers interested in game reimplementation, and for anyone who wants to see how far a behaviour-exact native rewrite can go. +The launcher's **Servers** page creates, starts, backs up and updates a Horizon server with buttons, and invites friends over Tailscale (it arrives with the next launcher release). On a VPS, `horizon-server` installs with one command and runs without Java. Guide: [Host a server](https://playhorizon.dev/docs/hosting) ([reference](docs/hosting.md)). -The [native client](docs/native-client.md) opens on a vanilla-style title screen with world creation and selection, and generates worlds with the Rust port of the vanilla generators: noise terrain, aquifers, surface rules, carvers and placed features, all checked against vanilla. It streams and lights chunks on worker threads and renders every vanilla block model with smooth lighting, biome tints, the vanilla sky, sun, moon, stars and clouds. Gameplay includes: +## Modpacks -- validated player physics, health and hunger; -- mining with vanilla tool rules and loot tables; -- placing, crafting, chests and furnaces; -- dropped items, particles and sounds; -- passive and hostile mobs with combat and vanilla AI, including guardians, shulkers, illagers, ravagers, the wither, the ender dragon fight, the breeze, the creaking, the sniffer, the happy ghast, llamas and the copper golem; -- villagers that take jobs, trade, restock, meet at the bell and sleep in beds, on a port of vanilla's brain; -- raids and pillager patrols; -- dispensers, crafters, the loom and the recipe book; -- every command, scoreboards and teams, the player list, subtitles and the HUD overlays; -- boats, minecarts, item frames, paintings and armor stands; -- shields, maps, books, fireworks, beacons, advancements and statistics; -- Anvil saves, joining vanilla servers, and opening a world to LAN. +The launcher's **Modpacks** page imports a Modrinth or CurseForge pack, shows which of its mods Horizon can carry over, and plays the ones it can as their own profile. Today that means content mods made of data and assets; mods with Java code are not ported yet. See [Modpacks](https://playhorizon.dev/docs/modpacks). ## Agent control @@ -149,7 +107,18 @@ cargo run --release -p horizon-client Everything prepared lands in the gitignored `.local/`. It is derived from the game: never commit it or share it. -The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`, `--dedicated`), controls, playing and scripting through `horizon-ctl` and its MCP server, and the architecture are described in [the native client guide](docs/native-client.md). The rest of the documentation is indexed in [docs/README.md](docs/README.md), including [the parity workflow](docs/parity-workflow.md). +The client starts on the title screen. Command-line options (`--world`, `--seed`, `--creative`, `--render-distance`, `--dedicated`), controls, scripting through `horizon-ctl` and the architecture are described in [the native client guide](docs/native-client.md). The rest of the developer documentation is indexed in [docs/README.md](docs/README.md), including [the parity workflow](docs/parity-workflow.md). + +## Contributing + +Issues and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md) for how we work (vanilla first, small pull requests, labels), or [the contributing guide](https://playhorizon.dev/docs/contributing) on the site. Questions and ideas: [Discord](https://discord.gg/HcTeMZxe5E). Before opening a pull request, run the self-check and paste the block it prints: + +```sh +git config core.hooksPath .githooks +python3 tools/pr_ready.py +``` + +It runs rustfmt, clippy with warnings denied, the tests of the crates you touched, the Python tests, the public-tree check, and the vanilla harnesses your change can affect. CI runs the same checks on GitHub's Linux runners; the vanilla harnesses need the game, which Horizon never downloads, so they run on a maintainer's computer holding their own copy. Never commit game files, decompiled source or prepared resources: `tools/check_public_tree.py` rejects them, and tracked Java is allowed only under the project's own `dev/horizonlab` namespace. ## Project status @@ -184,18 +153,7 @@ them too (Rust uses Java's own float maths on each platform). ### Known issues -Online-mode servers (Mojang's session servers) are not supported; skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; the creative hotbar keys (C/X) aren't wired to the hotbar loader; item tooltips lack attribute lines. - -## Contributing - -Issues and pull requests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md) for how we work (vanilla first, small pull requests, labels). Before opening a pull request, run the self-check and paste the block it prints: - -```sh -git config core.hooksPath .githooks -python3 tools/pr_ready.py -``` - -It runs rustfmt, clippy with warnings denied, the tests of the crates you touched, the Python tests, the public-tree check, and the vanilla harnesses your change can affect. CI runs the same checks on GitHub's Linux runners; the vanilla harnesses need the game, which Horizon never downloads, so they run on a self-hosted runner holding the maintainer's own copy. Never commit game files, decompiled source or prepared resources: `tools/check_public_tree.py` rejects them, and tracked Java is allowed only under the project's own `dev/horizonlab` namespace. +Horizon can't sign in to a Microsoft account yet, so it can't join online-mode servers (it joins offline-mode ones); skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; the creative hotbar keys (C/X) aren't wired to the hotbar loader; item tooltips lack attribute lines. ## Licence diff --git a/crates/horizon-client/examples/held_drop_fixture.rs b/crates/horizon-client/examples/held_drop_fixture.rs new file mode 100644 index 000000000..87ca9870c --- /dev/null +++ b/crates/horizon-client/examples/held_drop_fixture.rs @@ -0,0 +1,29 @@ +//! Selected-slot drop state for the vanilla key-handler parity harness. +use horizon_client::command::args::GameMode; +use horizon_client::items::{ItemStack, take_held_drop}; + +fn main() { + for mode in [ + GameMode::Survival, + GameMode::Creative, + GameMode::Adventure, + GameMode::Spectator, + ] { + for all in [false, true] { + for _selected in [0, 8] { + for count in [0, 1, 4, 64] { + let mut slot = Some(ItemStack::new("minecraft:stone", count)); + let mut dropped = 0; + for _ in 0..2 { + if let Some(stack) = + take_held_drop(&mut slot, all, mode == GameMode::Spectator) + { + dropped += stack.count; + } + println!("{} {}", slot.as_ref().map_or(0, |s| s.count), dropped); + } + } + } + } + } +} diff --git a/crates/horizon-client/examples/marker_particles_probe.rs b/crates/horizon-client/examples/marker_particles_probe.rs new file mode 100644 index 000000000..edf624e73 --- /dev/null +++ b/crates/horizon-client/examples/marker_particles_probe.rs @@ -0,0 +1,90 @@ +//! Probe for tools/test_marker_particles_parity.py. +use horizon_client::{ + Result, + animate_tick::{AnimateContext, AnimateTables, animate_tick, marker_particle_target}, + assets::Assets, + biome::Biomes, + blocks::BlockFacts, + chunk::Chunk, + collisions, + command::args::GameMode, + items::ItemStack, + particles::{ParticleEngine, ParticleOptions, ParticleType}, + world::World, +}; +use horizon_core::random::RandomSource; +use serde_json::Value; +use std::{ + collections::HashMap, + fs::File, + io::{BufRead, BufReader, BufWriter, Write}, + path::Path, + sync::Arc, +}; + +fn main() -> Result<()> { + let args: Vec = std::env::args().collect(); + let root = Path::new(".local/horizon-client/26.3"); + let assets = Assets::load(root)?; + let facts = BlockFacts::load(root, assets.registry)?; + let biomes = Biomes::load(root)?; + let collision = collisions::load(root, assets.registry)?; + let tables = AnimateTables::load(root, assets.registry, &biomes)?; + let mut world = World::new(facts.air, 0); + let barrier = assets + .registry + .default_state("minecraft:barrier") + .ok_or("barrier")?; + for cz in -2..2 { + for cx in -2..2 { + world + .chunks + .insert((cx, cz), Arc::new(Chunk::empty(cx, cz))); + for y in 33..96 { + for z in 0..16 { + for x in 0..16 { + world.set(cx * 16 + x, y, cz * 16 + z, barrier)?; + } + } + } + } + } + let mut engine = ParticleEngine::new(root, &HashMap::new()); + let mut out = BufWriter::new(File::create(&args[2])?); + for line in BufReader::new(File::open(&args[1])?).lines() { + let case: Value = serde_json::from_str(&line?)?; + let mode = GameMode::ALL + .into_iter() + .find(|mode| Some(mode.name()) == case["mode"].as_str()) + .ok_or("mode")?; + let stack = ItemStack::new( + &format!("minecraft:{}", case["main"].as_str().ok_or("main")?), + case["count"].as_u64().ok_or("count")? as u32, + ); + let target = marker_particle_target(mode, Some(&stack)); + writeln!(out, "{}", target.unwrap_or("none"))?; + // Exercise the real ambient sampling loop in a dry barrier-filled world. + let options = + ParticleOptions::block(ParticleType::BlockMarker, "item/barrier".into(), 0xFFFFFF); + let options = |_| Some(options.clone()); + let ctx = AnimateContext { + world: &world, + facts: &facts, + collision: &collision, + biomes: &biomes, + registry: assets.registry, + raining_at: &|_| false, + marker: target.map(|name| (name, &options as &dyn Fn(_) -> _)), + }; + engine.seed_randoms(1057, 0, 0); + engine.requested = Some(Vec::new()); + animate_tick(&tables, &mut engine, &ctx, [0, 64, 0]); + for (options, p, v) in engine.requested.take().ok_or("requests")? { + assert_eq!(options.ty, ParticleType::BlockMarker); + assert_eq!(v, [0.0; 3]); + writeln!(out, "marker {} {} {}", p[0], p[1], p[2])?; + } + writeln!(out, "next {}", engine.random().next_int())?; + } + Ok(()) +} diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index df472983e..63a5351a3 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -19,11 +19,17 @@ fn state(menu: &Menu) -> String { .map(|i| canon_stack(menu.slot(i))) .collect(); let data: String = menu.data.iter().map(|d| format!(" {d}")).collect(); + let equipped: Vec = menu + .equipped + .iter() + .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) + .collect(); format!( - "{} | {} |{data} | {}", + "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), - menu.drops.join(";") + menu.drops.join(";"), + equipped.join(";") ) } @@ -82,6 +88,7 @@ fn main() -> horizon_client::Result<()> { speed: 1.0, }); menu.drops.clear(); + menu.equipped.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; diff --git a/crates/horizon-client/examples/mod_port_probe.rs b/crates/horizon-client/examples/mod_port_probe.rs index c78285bbb..13dc7f685 100644 --- a/crates/horizon-client/examples/mod_port_probe.rs +++ b/crates/horizon-client/examples/mod_port_probe.rs @@ -84,8 +84,10 @@ fn main() -> Result<()> { horizon_client::collisions::load(&root, registry).map_err(step("collisions"))?; let loaded = began.elapsed().as_secs_f64() - built; let ours = |id: &str| { - id.split_once(':') - .is_some_and(|(ns, _)| mods.iter().any(|m| m.id == ns)) + id.split_once(':').is_some_and(|(ns, _)| { + mods.iter() + .any(|m| m.content.namespaces.iter().any(|n| n == ns)) + }) }; let tools: Vec = serde_json::from_value(oracle["tools"].clone())?; diff --git a/crates/horizon-client/examples/natural_spawn_fixture.rs b/crates/horizon-client/examples/natural_spawn_fixture.rs index 3fb3d5719..528f8195d 100644 --- a/crates/horizon-client/examples/natural_spawn_fixture.rs +++ b/crates/horizon-client/examples/natural_spawn_fixture.rs @@ -268,10 +268,16 @@ impl NaturalLevel for World<'_> { self.biome_info(x, y, z) .map_or(0.1, |b| b.creature_probability) } - fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec { + fn structures_at( + &self, + x: i32, + y: i32, + z: i32, + wanted: &dyn Fn(&str) -> bool, + ) -> Vec { let (cx, cz) = (x >> 4, z >> 4); let mut out: Vec = Vec::new(); - for start in &self.starts { + for start in self.starts.iter().filter(|s| wanted(&s.id)) { let b = start.bounds.0; // Referenced: the start's box reaches the chunk's columns. if b[3] < cx * 16 || b[0] > cx * 16 + 15 || b[5] < cz * 16 || b[2] > cz * 16 + 15 { diff --git a/crates/horizon-client/src/animate_tick.rs b/crates/horizon-client/src/animate_tick.rs index 059aaf58b..b391c0cbf 100644 --- a/crates/horizon-client/src/animate_tick.rs +++ b/crates/horizon-client/src/animate_tick.rs @@ -6,6 +6,8 @@ use crate::{ biome::Biomes, blocks::{BlockFacts, Fluid}, + command::args::GameMode, + items::ItemStack, particles::{ParticleEngine, ParticleOptions, ParticleType as T}, world::World, }; @@ -254,6 +256,24 @@ pub struct AnimateContext<'a> { pub registry: &'a BlockRegistry, /// `Level.isRainingAt`. pub raining_at: &'a dyn Fn([i32; 3]) -> bool, + /// Creative main-hand marker block and a resolver for each placed state's sprite. + pub marker: Option<(&'a str, &'a dyn Fn(BlockStateId) -> Option)>, +} + +/// `ClientLevel.getMarkerParticleTarget`: only the selected main-hand item counts. +pub fn marker_particle_target( + mode: GameMode, + main_hand: Option<&ItemStack>, +) -> Option<&'static str> { + if mode != GameMode::Creative { + return None; + } + let stack = main_hand.filter(|stack| stack.count > 0)?; + match stack.item.as_ref() { + "minecraft:barrier" => Some("minecraft:barrier"), + "minecraft:light" => Some("minecraft:light"), + _ => None, + } } impl AnimateContext<'_> { fn state(&self, p: [i32; 3]) -> BlockStateId { @@ -358,6 +378,12 @@ fn do_animate_tick( try_spawn_drip(tables, engine, ctx, [x, y - 1, z], drip, top_solid); } } + if let Some((block, options)) = ctx.marker + && ctx.registry.state(state).is_some_and(|s| s.name == block) + && let Some(options) = options(state) + { + engine.add(&options, pos.map(|v| f64::from(v) + 0.5), [0.0; 3]); + } if !facts.full_collision { let biome = ctx .world diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fd57830c9..119376089 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -106,6 +106,7 @@ mod persist; mod perspective; mod pickups; mod piglins; +mod player_equip; mod postprocess; mod potions; mod powder_snow; @@ -1009,11 +1010,16 @@ struct Game<'a> { /// `FogRenderer`'s evolving state. fog: horizon_client::fog::FogState, screen_fx: horizon_client::screen_effects::ScreenEffects, + panorama_rotation: horizon_client::gfx::panorama::Rotation, world: World, streaming: Streaming, lod: Option, lod_source_attempted: bool, lod_observe: horizon_client::fast_hash::FxHashSet<(i32, i32)>, + /// The detail revision, centre and radius `Lod::update` last had covered for. + lod_covered_at: Option<(u64, (i32, i32), i32)>, + /// Unloaded columns `Lod::observe` has yet to summarise. + lod_unloaded: std::collections::VecDeque>, options: Options, player: Option, spawn: Option, @@ -1715,8 +1721,14 @@ impl Game<'_> { Some(stack) } fn particle_sprite(&self, state: BlockStateId) -> Option<(String, u32)> { - let models = self - .pack + Self::block_particle_sprite(&self.pack, self.res.facts(), state) + } + fn block_particle_sprite( + pack: &PackResources, + facts: &BlockFacts, + state: BlockStateId, + ) -> Option<(String, u32)> { + let models = pack .render .model_catalog .collect(state, horizon_core::position::BlockPos::new(0, 0, 0)) @@ -1730,9 +1742,9 @@ impl Game<'_> { let layer = face .map(|face| face.layer) .or_else(|| models.iter().find_map(|(_, model)| model.particle))?; - let name = self.pack.layer_names.get(&layer)?.clone(); + let name = 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 = &facts.get(state).name; if n.contains("leaves") || n.contains("vine") { 0x48B518 } else { @@ -1852,9 +1864,12 @@ impl Game<'_> { if self.eye_position().is_none() { return; } - let Some(thrown) = - horizon_client::items::take_held_drop(&mut self.inventory[self.selected], all) - else { + let spectator = self.spectator(); + let Some(thrown) = horizon_client::items::take_held_drop( + &mut self.inventory[self.selected], + all, + spectator, + ) else { return; }; self.player_drop(thrown); @@ -2847,7 +2862,7 @@ impl Game<'_> { // Block.playerDestroy: the mined statistic, the exhaustion and the drops. self.stats.add("mined", &facts.name, 1); if let Some(p) = self.player.as_mut() { - p.health.food.exhaustion = (p.health.food.exhaustion + 0.005).min(40.0); + p.cause_food_exhaustion(0.005); } let drops = self.block_loot_at(pos, state, held.as_ref()); let silk = held @@ -4166,6 +4181,13 @@ impl Game<'_> { | Screen::CommandBlock ) || self.book.is_some()) } + /// `MouseHandler.grabMouse` / `releaseMouse`. Both put the pointer at + /// the window's centre, so a screen opened from gameplay (inventory, + /// chest, pause, chat, sign, book, death) starts with the cursor in the + /// middle instead of wherever the system last left it. Releasing when + /// already released does nothing, so moving from screen to screen keeps + /// the cursor where it is. Like GLFW's `glfwSetCursorPos`, nothing warps + /// while the window is unfocused (losing focus releases the pointer). fn capture(&mut self, capture: bool) { // A guest's action (`as_guest`) opens and closes screens on the // guest's own client: the window's pointer stays the host's (#687). @@ -4182,14 +4204,43 @@ impl Game<'_> { // The real pointer takes over from an agent's. self.agent_pointer = false; let Some(window) = &self.window else { return }; + let size = self.renderer.as_ref().map_or_else( + || window.inner_size().into(), + |r| [r.config.width, r.config.height], + ); + let centre = + winit::dpi::PhysicalPosition::new(f64::from(size[0]) / 2.0, f64::from(size[1]) / 2.0); + let warp = |window: &Window| { + let _ = window.set_cursor_position(centre); + }; if capture { self.mouse.set_ignore_first_move(); self.captured = window .set_cursor_grab(CursorGrabMode::Locked) .or_else(|_| window.set_cursor_grab(CursorGrabMode::Confined)) .is_ok(); + if self.captured && self.focused { + warp(window); + } } else { - let _ = window.set_cursor_grab(CursorGrabMode::None); + if self.captured { + // Wayland moves a pointer only as the locked pointer's + // position hint, which the compositor applies as the lock + // goes (sway and Hyprland do): set it before ungrabbing. + // X11, Windows and macOS warp, so warp again once free + // (Wayland refuses that one). + if self.focused { + warp(window); + } + let _ = window.set_cursor_grab(CursorGrabMode::None); + if self.focused { + warp(window); + } + let scale = HudBatch::new(size).scale; + self.cursor = (size[0] as f32 / 2.0 / scale, size[1] as f32 / 2.0 / scale); + } else { + let _ = window.set_cursor_grab(CursorGrabMode::None); + } self.captured = false; } window.set_cursor_visible(!self.captured); @@ -5233,6 +5284,9 @@ impl Game<'_> { .collect(); let carried = self.carried.clone(); let creative = self.creative; + // CreativeModeInventoryScreen clicks the menu itself and sends every + // changed slot, which the server sets by player. + let equipment_before = (self.screen == Screen::Creative).then(|| self.player_equipment()); let station_menu = self.station.as_ref().map(|s| { ( s.loom.selected.map_or(-1, |i| i as i32), @@ -5324,6 +5378,7 @@ impl Game<'_> { let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); let crafted = std::mem::take(&mut menu.crafted); + let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { if let Some(g) = game_of[i] { *self.slot_mut(g) = stack; @@ -5366,6 +5421,14 @@ impl Game<'_> { // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. f.input_clicked(self.res.recipes(), before[0].clone()); } + match equipment_before { + Some(before) => self.player_equipment_changed(&before), + None => { + for (slot, stack) in equipped { + self.player_equipped(slot, stack.as_ref()); + } + } + } self.apply_equipment(); true } @@ -6497,7 +6560,7 @@ impl Game<'_> { if let Some(p) = self.player.as_mut() && !self.creative { - p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0); + p.cause_food_exhaustion(0.1); } let player = self.player.as_ref(); let from = player.map(|p| [p.position.x, p.position.y, p.position.z]); @@ -6615,12 +6678,25 @@ impl Game<'_> { self.tick_player_model(); Ok(()) } + /// What the loaded Java shader pack changes in this dimension's vanilla + /// sky (`sunPathRotation`, `clouds`, `sun`, `moon`); `None` without one. + fn java_sky(&self) -> Option<(f32, horizon_shaderpack::properties::SkyDirectives)> { + self.shader_packs.java_sky(match self.dim { + Dim::Overworld => 0, + Dim::Nether => -1, + Dim::End => 1, + }) + } /// SkyRenderer.renderSunMoonAndStars: bodies on a frame rotated Y -90 then X by angle. + /// A Java pack's `sunPathRotation` tilts it about Z in between, and its + /// `sun = false` / `moon = false` leave those out, as Iris does. fn celestial_geometry(&self, sky: &horizon_client::environment::Sky) -> Vec { let mut out = Vec::new(); let atlas = &self.gui.atlas; + let (tilt, keep) = self.java_sky().unwrap_or_default(); let frame = |angle: f32| { glam::Mat4::from_rotation_y((-90.0f32).to_radians()) + * glam::Mat4::from_rotation_z(tilt.to_radians()) * glam::Mat4::from_rotation_x(angle.to_radians()) }; let mut body = |name: &str, angle: f32, size: f32, color: u32| { @@ -6642,12 +6718,14 @@ impl Game<'_> { }); } }; - body( - "environment/celestial/sun", - sky.sun_angle, - 30.0, - 0xFFFF_FFFF, - ); + if keep.sun { + body( + "environment/celestial/sun", + sky.sun_angle, + 30.0, + 0xFFFF_FFFF, + ); + } let phases = [ "full_moon", "waning_gibbous", @@ -6659,12 +6737,14 @@ impl Game<'_> { "waxing_gibbous", ]; let phase = phases[(self.world.day_time / 24000).rem_euclid(8) as usize]; - body( - &format!("environment/celestial/moon/{phase}"), - sky.moon_angle, - 20.0, - 0xFFFF_FFFF, - ); + if keep.moon { + body( + &format!("environment/celestial/moon/{phase}"), + sky.moon_angle, + 20.0, + 0xFFFF_FFFF, + ); + } if sky.star_brightness > 0.0 { let b = (sky.star_brightness.clamp(0.0, 1.0) * 255.0) as u32; let color = b << 24 | b << 16 | b << 8 | b; @@ -8328,6 +8408,7 @@ impl Game<'_> { pack, gui, self.renderer.as_ref(), + None, self.settings.horizon.api, ) } @@ -8878,10 +8959,12 @@ impl Game<'_> { if self.creative_inventory_open() { if Self::creative_trash_hovered(&batch, self.cursor) { if self.has_shift_down() { + let before = self.player_equipment(); self.inventory.fill(None); self.armor.fill(None); self.offhand = None; self.craft_grid[..4].fill(None); + self.player_equipment_changed(&before); self.apply_equipment(); } else { self.carried = None; @@ -9115,7 +9198,7 @@ impl Game<'_> { }; horizon_client::environment::apply_weather(&mut sky, rain, thunder); self.end_flash_sky(&mut sky, alpha); - if self.flash > 0 { + if self.flash > 0 && !self.settings.file.bool("hideLightningFlashes") { // Lightning flash brightens the sky (LevelRenderer skyFlashTime). sky.sky_color = [0.9, 0.9, 1.0]; sky.sky_light_factor = 1.0; @@ -9186,7 +9269,13 @@ impl Game<'_> { (view_yaw, view_pitch) } else if title { // PanoramaRenderer: the title cube spins at 0.1 degrees per tick, pitched 10 degrees. - (-(self.started.elapsed().as_secs_f32() * 2.0) % 360.0, 10.0) + ( + self.panorama_rotation.update( + self.started.elapsed().as_secs_f32(), + self.settings.file.double("panoramaScrollSpeed") as f32, + ), + 10.0, + ) } else { (view_yaw, view_pitch) }; @@ -9229,6 +9318,18 @@ impl Game<'_> { entities.extend(dragon); } } + // A Java pack's `clouds` replaces the cloud option (`renderClouds`: + // "false", "fast", "true"), as Iris overrides `getCloudsType`. + let clouds_mode = { + use horizon_shaderpack::properties::CloudSetting; + match self.java_sky().and_then(|(_, sky)| sky.clouds) { + Some(CloudSetting::Off) => "false", + Some(CloudSetting::Fast) => "fast", + Some(CloudSetting::Fancy) => "true", + None => self.settings.clouds.as_str(), + } + .to_owned() + }; let celestial = if title && !live { Vec::new() } else if self.dim == Dim::Overworld @@ -9315,7 +9416,7 @@ impl Game<'_> { hud: &hud, clouds: ((!title || live) && self.dim == Dim::Overworld - && horizon_client::clouds::visible(&self.settings.clouds, sky.cloud_color[3])) + && horizon_client::clouds::visible(&clouds_mode, sky.cloud_color[3])) .then(|| self.gui.atlas.sprites.get("horizon/white")) .flatten() .map(|white| horizon_client::clouds::Input { @@ -9325,7 +9426,7 @@ impl Game<'_> { time: self.world.game_time, partial_tick: alpha, range: self.settings.cloud_range, - fast: self.settings.clouds == "fast", + fast: clouds_mode == "fast", color: sky.cloud_color, }), entities: &entities, @@ -9593,7 +9694,12 @@ impl Game<'_> { } } KeyCode::KeyF if self.screen == Screen::Playing => { + // handlePlayerAction SWAP_ITEM_WITH_OFFHAND: setItemInHand for + // the off hand, then the main hand. std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]); + let (offhand, main) = (self.offhand.clone(), self.inventory[self.selected].clone()); + self.player_on_equip("offhand", main.as_ref(), offhand.as_ref()); + self.player_on_equip("mainhand", offhand.as_ref(), main.as_ref()); self.using = None; } KeyCode::KeyQ if self.screen == Screen::Playing => { @@ -9675,12 +9781,17 @@ impl Game<'_> { } Ok(()) } + /// LOD Distance as far terrain uses it (`Graphics::lod_distance_on`). + fn lod_distance(&self) -> u32 { + match &self.renderer { + Some(renderer) => self.settings.horizon.lod_distance_on(&renderer.info), + None => self.settings.horizon.lod_distance.min(1024), + } + } /// Only enabled LOD worlds extend the renderer's range, never simulation. fn terrain_distance(&self) -> i32 { if self.lod.is_some() { - self.streaming - .radius - .max(self.settings.horizon.lod_distance.min(1024) as i32) + self.streaming.radius.max(self.lod_distance() as i32) } else { self.streaming.radius } @@ -9689,6 +9800,8 @@ impl Game<'_> { self.lod = None; self.lod_source_attempted = false; self.lod_observe.clear(); + self.lod_covered_at = None; + self.lod_unloaded.clear(); if let Some(renderer) = &mut self.renderer { renderer.clear_lods(); } @@ -9743,17 +9856,30 @@ impl Game<'_> { self.lod_observe .extend(uploads.iter().map(|(key, _)| (key.0, key.2))); for chunk in &unloaded { - horizon_client::spans::time("lod_observe", || lod.observe(chunk, self.res.facts())); self.lod_observe.remove(&(chunk.x, chunk.z)); } - let observe: Vec<_> = self.lod_observe.iter().copied().take(2).collect(); - for key in observe { - self.lod_observe.remove(&key); - if let Some(chunk) = self.world.chunks.get(&key) { - horizon_client::spans::time("lod_observe", || { - lod.observe(chunk, self.res.facts()) - }); - } + // Unloaded columns first (their summaries are all that remains), + // then resident ones: at least one a frame, more within about a + // millisecond. Moving fast unloads dozens in one frame. + self.lod_unloaded.extend(unloaded.iter().cloned()); + let start = std::time::Instant::now(); + let mut observed = 0; + while observed < 1 || start.elapsed() < std::time::Duration::from_millis(1) { + let chunk = if let Some(chunk) = self.lod_unloaded.pop_front() { + chunk + } else if let Some(&key) = self.lod_observe.iter().next() { + self.lod_observe.remove(&key); + match self.world.chunks.get(&key) { + Some(chunk) => chunk.clone(), + None => continue, + } + } else { + break; + }; + horizon_client::spans::time("lod_observe", || { + lod.observe(&chunk, self.res.facts()) + }); + observed += 1; } } let dirty: Vec<_> = unloaded @@ -9838,31 +9964,41 @@ impl Game<'_> { } } if let (Some(lod), Some(player)) = (&mut self.lod, &self.player) { - let covered = renderer - .lod_detail_columns() - .filter(|&(x, z)| { - horizon_client::streaming::in_view_distance( - self.streaming.center, - self.streaming.radius, - x, - z, - ) + let lod_distance = self.settings.horizon.lod_distance_on(&renderer.info); + lod.set_near_loading(self.streaming.busy()); + // The covered columns change only with the complete ones and + // the render area: rebuilt then, not every frame. + let at = ( + renderer.lod_detail_revision(), + self.streaming.center, + self.streaming.radius, + ); + let covered = (self.lod_covered_at != Some(at)).then(|| { + self.lod_covered_at = Some(at); + horizon_client::spans::time("lod_covered_set", || { + renderer + .lod_detail_columns() + .filter(|&(x, z)| { + horizon_client::streaming::in_view_distance(at.1, at.2, x, z) + }) + .collect() }) - .collect(); - for (key, mesh) in horizon_client::spans::time("lod_update", || { + }); + let meshes = horizon_client::spans::time("lod_update", || { lod.update( [player.position.x, player.position.y, player.position.z], self.yaw, self.streaming.radius, - self.settings.horizon.lod_distance, + lod_distance, covered, ) - }) { - horizon_client::spans::time("lod_upload", || renderer.upload_lod(key, &mesh)); - } - for key in lod.removed() { - renderer.remove_lod(key); - } + }); + renderer.queue_lods(meshes, lod.removed(), lod.take_cutout()); + // A finished job can hold hundreds of tiles: spread them + // over frames rather than stall one. + horizon_client::spans::time("lod_upload", || { + renderer.upload_lods(std::time::Duration::from_millis(2)) + }); } } } @@ -10716,6 +10852,7 @@ impl<'a> Game<'a> { options: Options, settings: Settings, audio: Audio, + prepared: Option, ) -> Result { let root = options.resources.clone(); let registry = pack.assets.registry; @@ -10732,15 +10869,9 @@ impl<'a> Game<'a> { .join("saves") .join(".horizon-title"), )); - // These batches share the exported document instead of reparsing it per layer. - let (armor_stand_assets, boat_models, cart_models) = { - let document = horizon_client::mobs::EntityModelDocument::load(&root).ok(); - ( - armor_stands::ArmorStandAssets::load(&root, document.as_ref()), - boats::BoatModels::load(document.as_ref()), - minecarts::CartModels::load(document.as_ref()), - ) - }; + let prepared = prepared + .map(Ok) + .unwrap_or_else(|| GameCpuResources::load(&root))?; let world = World::new(res.facts().air, 0); let creative = options.creative; let inventory = vec![None; 36]; @@ -10759,11 +10890,14 @@ impl<'a> Game<'a> { gui, fog: Default::default(), screen_fx: Default::default(), + panorama_rotation: Default::default(), world, streaming, lod: None, lod_source_attempted: false, lod_observe: Default::default(), + lod_covered_at: None, + lod_unloaded: Default::default(), options, player: None, spawn: None, @@ -10919,18 +11053,18 @@ impl<'a> Game<'a> { level_events: Vec::new(), falling: Vec::new(), paintings: Vec::new(), - painting_variants: paintings::PaintingVariants::load(&root), + painting_variants: prepared.painting_variants, item_frames: Vec::new(), - frame_model: frames::bake_frame(&root, "item_frame"), - glow_frame_model: frames::bake_frame(&root, "glow_item_frame"), - map_frame_model: frames::bake_frame(&root, "item_frame_map"), - glow_map_frame_model: frames::bake_frame(&root, "glow_item_frame_map"), + frame_model: prepared.frame_model, + glow_frame_model: prepared.glow_frame_model, + map_frame_model: prepared.map_frame_model, + glow_map_frame_model: prepared.glow_map_frame_model, armor_stands: Vec::new(), others: Vec::new(), - armor_stand_assets, + armor_stand_assets: prepared.armor_stand_assets, boats: Vec::new(), - boat_models, - crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"), + boat_models: prepared.boat_models, + crystal_model: prepared.crystal_model, carts: Vec::new(), jukebox_sounds: HashMap::new(), bolts: Vec::new(), @@ -10940,7 +11074,7 @@ impl<'a> Game<'a> { crystals: Vec::new(), dragon_fireballs: Vec::new(), breath_clouds: Vec::new(), - dragon_model: horizon_client::mobs::load_model(&root, "minecraft:ender_dragon#main"), + dragon_model: prepared.dragon_model, map_patches: Vec::new(), skin_downloads: horizon_client::skins::Downloader::new( std::env::current_dir() @@ -10948,7 +11082,7 @@ impl<'a> Game<'a> { .join("assets/skins"), ), skin_slots: Vec::new(), - cart_models, + cart_models: prepared.cart_models, riding: None, ender_items: vec![None; 27], ender_open: None, @@ -10962,11 +11096,11 @@ impl<'a> Game<'a> { ominous_spawners: Vec::new(), creaking: Default::default(), spawners: Default::default(), - trident_model: horizon_client::mobs::load_model(&root, "minecraft:trident#main"), - arrow_model: horizon_client::mobs::load_model(&root, "minecraft:arrow#main"), + trident_model: prepared.trident_model, + arrow_model: prepared.arrow_model, tnts: Vec::new(), hoppers: HashMap::new(), - creative_screen: Creative::load(&root)?, + creative_screen: prepared.creative_screen, control: None, frame_stats: Default::default(), perf: Default::default(), @@ -11041,8 +11175,49 @@ impl<'a> Game<'a> { } } +/// CPU-only startup data, owned by one loader generation. No file reads or +/// model baking are needed when the event loop installs this bundle. +struct GameCpuResources { + painting_variants: paintings::PaintingVariants, + frame_model: frames::FrameModel, + glow_frame_model: frames::FrameModel, + map_frame_model: frames::FrameModel, + glow_map_frame_model: frames::FrameModel, + armor_stand_assets: armor_stands::ArmorStandAssets, + boat_models: boats::BoatModels, + cart_models: minecarts::CartModels, + crystal_model: Option, + dragon_model: Option, + arrow_model: Option, + trident_model: Option, + creative_screen: Creative, +} +impl GameCpuResources { + fn load(root: &std::path::Path) -> Result { + let document = horizon_client::mobs::EntityModelDocument::load(root).ok(); + let model = |key| document.as_ref().and_then(|document| document.model(key)); + Ok(Self { + painting_variants: paintings::PaintingVariants::load(root), + frame_model: frames::bake_frame(root, "item_frame"), + glow_frame_model: frames::bake_frame(root, "glow_item_frame"), + map_frame_model: frames::bake_frame(root, "item_frame_map"), + glow_map_frame_model: frames::bake_frame(root, "glow_item_frame_map"), + armor_stand_assets: armor_stands::ArmorStandAssets::load(root, document.as_ref()), + boat_models: boats::BoatModels::load(document.as_ref()), + cart_models: minecarts::CartModels::load(document.as_ref()), + crystal_model: model("minecraft:end_crystal#main"), + dragon_model: model("minecraft:ender_dragon#main"), + arrow_model: model("minecraft:arrow#main"), + trident_model: model("minecraft:trident#main"), + creative_screen: Creative::load(root)?, + }) + } +} + /// The data the background loader produces for `Game::new`. struct Loaded { + game_cpu: Option, + renderer_cpu: Option, root: PathBuf, pack_error: Option, resources: Arc, @@ -11366,6 +11541,17 @@ fn load_resources( started.elapsed().as_millis() ); } + // Finish fallible CPU preparation before starting the tail, so an error + // cannot detach a tail worker that races the next pack-loader generation. + let prepared_at = Instant::now(); + let game_cpu = menu.then(|| GameCpuResources::load(&root)).transpose()?; + let renderer_cpu = menu.then(|| prepare_renderer_textures(&pack)); + if menu { + log::info!( + "Horizon: handoff CPU resources prepared on worker in {} ms", + prepared_at.elapsed().as_millis() + ); + } let rest_loader = if menu { let resources = resources.clone(); let root = root.clone(); @@ -11417,6 +11603,8 @@ fn load_resources( None }; Ok(Loaded { + game_cpu, + renderer_cpu, root, pack_error, resources, @@ -11495,14 +11683,26 @@ fn load_world_rest( }) } -/// The renderer from a pack's block sprites, its shared atlas and its border -/// texture; `previous` shares the device and window surface with an old one. +/// CPU mip chains for the block sprites and world border. +fn prepare_renderer_textures(pack: &PackResources) -> horizon_client::gfx::PreparedTextures { + let assets = &pack.render; + horizon_client::gfx::PreparedTextures::new( + &assets.pixels, + assets.sprite_size, + assets.texture_layers, + &assets.sprite_mips, + (&pack.forcefield.2, pack.forcefield.0), + ) +} + +/// Upload pack textures and create the renderer on the window's device. fn build_renderer( window: Arc, offscreen: bool, pack: &PackResources, gui: &UiResources, previous: Option<&Renderer>, + prepared: Option, api: horizon_client::graphics::GraphicsApi, ) -> Result { let assets = &pack.render; @@ -11519,6 +11719,7 @@ fn build_renderer( (&atlas.pixels, atlas.width, atlas.height), (&pack.forcefield.2, pack.forcefield.0), &gui.panorama, + prepared, previous, api, ))?; @@ -11564,6 +11765,7 @@ fn loading_renderer( (pixels, width, height), (&FORCEFIELD[..], 1), panorama, + None, previous, api, ))?; @@ -11643,9 +11845,17 @@ fn start_game<'a>( vanilla_root: PathBuf, started: Instant, rest_loader: Option, + settings: Option, + prepared: Option, ) -> Result>> { - let mut settings = Settings::load(&std::env::current_dir()?.join("options.txt")); - horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); + let handoff = prepared.is_some(); + let mut settings = match settings { + Some(settings) => settings, + None => { + horizon_client::ui_theme::load_preferences(&std::env::current_dir()?); + Settings::load(&std::env::current_dir()?.join("options.txt")) + } + }; // Scripted and frame-limited runs (the parity harnesses) see vanilla's // screens unless HORIZON_MENU_STYLE asks otherwise. if (options.frames.is_some() || options.control.is_some()) @@ -11656,7 +11866,7 @@ fn start_game<'a>( if let Some(d) = options.distance_override { settings.render_distance = d; } - let mut game = Game::new(res, pack, gui, options, settings, audio)?; + let mut game = Game::new(res, pack, gui, options, settings, audio, prepared)?; game.rest_loader = rest_loader; game.ui.vanilla_root = vanilla_root; if let Some(error) = pack_error { @@ -11734,6 +11944,7 @@ fn start_game<'a>( let (seed, creative) = (game.options.seed, game.options.creative); game.open_world(&folder, None, Some(seed), creative, None)?; } + None if handoff => {} None => { let mut title = Title::new( std::env::current_dir()?.join("saves"), @@ -11795,6 +12006,7 @@ struct Loading { vanilla_root: PathBuf, pack_error: Option, started: Instant, + panorama_rotation: horizon_client::gfx::panorama::Rotation, progress: Progress, receiver: Receiver, loaded: Option>, @@ -11921,7 +12133,11 @@ impl Loading { }; let mut batch = HudBatch::new(size); self.draw_menu(&mut batch); - let frame = loading_frame(&batch); + let mut frame = loading_frame(&batch); + frame.yaw = self.panorama_rotation.update( + self.started.elapsed().as_secs_f32(), + self.settings.file.double("panoramaScrollSpeed") as f32, + ); if let Some(renderer) = &mut self.renderer { match renderer.render(&frame) { Ok(true) if self.gui.is_some() && self.menu.pending.is_none() => { @@ -11940,6 +12156,7 @@ impl Loading { } } fn finish(&mut self, loaded: Loaded) -> Result>> { + let handoff_at = Instant::now(); let mut options = self.options.take().ok_or("loading already finished")?; options.resources = loaded.root.clone(); // StartupMenu owns world selection until it can hand it to Game. @@ -11951,18 +12168,21 @@ impl Loading { if let Some(renderer) = &mut self.renderer { renderer.release_surface(); } + let renderer_at = Instant::now(); let renderer = build_renderer( window.clone(), options.offscreen, &loaded.pack, &gui, self.renderer.as_ref(), + loaded.renderer_cpu, self.settings.horizon.api, )?; log::info!( "Horizon: world renderer ready after {} ms", self.started.elapsed().as_millis() ); + let renderer_ms = renderer_at.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) @@ -11973,6 +12193,7 @@ impl Loading { // 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(loaded.resources)); + let game_at = Instant::now(); let Some(mut game) = start_game( res, loaded.pack, @@ -11983,18 +12204,27 @@ impl Loading { self.vanilla_root.clone(), self.started, loaded.rest_loader, + Some(self.settings.clone()), + loaded.game_cpu, )? else { return Ok(None); }; + let game_ms = game_at.elapsed().as_millis(); game.window = Some(window); game.renderer = Some(renderer); game.world_renderer_ready = true; game.fullscreen = self.fullscreen; + game.panorama_rotation = self.panorama_rotation; self.menu.handoff(&mut game); - game.settings = self.settings.clone(); game.apply_settings(); game.previous = Instant::now(); + log::info!( + "Horizon: startup handoff {} ms (renderer {} ms, start_game {} ms)", + handoff_at.elapsed().as_millis(), + renderer_ms, + game_ms + ); Ok(Some(game)) } } @@ -12099,6 +12329,7 @@ fn run_loading( vanilla_root, pack_error, started, + panorama_rotation: Default::default(), progress, receiver, loaded: None, @@ -12185,6 +12416,8 @@ pub fn run() -> Result<()> { vanilla_root, started, loaded.rest_loader, + None, + None, )?; if let Some(game) = game { run_event_loop(game)?; @@ -12208,6 +12441,52 @@ fn reset_world_progress(adv: &mut advancements::AdvState, stats: &mut stats::Sta *stats = Default::default(); } +#[cfg(test)] +mod startup_cpu_tests { + use super::*; + + #[test] + fn worker_prepares_owned_models_and_inventory_before_handoff() { + let root = std::env::temp_dir().join(format!("horizon-startup-cpu-{}", std::process::id())); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write( + root.join("entity-models.json"), + r#"{ + "minecraft:end_crystal#main": {}, "minecraft:ender_dragon#main": {}, + "minecraft:arrow#main": {}, "minecraft:trident#main": {}, + "minecraft:armor_stand#main": {} + }"#, + ) + .unwrap(); + std::fs::write( + root.join("creative-tabs.json"), + r#"[{ + "id":"minecraft:building_blocks", "items":["minecraft:stone"] + }]"#, + ) + .unwrap(); + let worker_root = root.clone(); + let prepared = std::thread::spawn(move || { + GameCpuResources::load(&worker_root).map_err(|error| error.to_string()) + }) + .join() + .unwrap() + .unwrap(); + std::fs::remove_dir_all(&root).unwrap(); + assert!(prepared.crystal_model.is_some()); + assert!(prepared.dragon_model.is_some()); + assert!(prepared.arrow_model.is_some()); + assert!(prepared.trident_model.is_some()); + assert!(prepared.armor_stand_assets.main.is_some()); + assert_eq!( + prepared.creative_screen.tabs[0].items[0].item.as_ref(), + "minecraft:stone" + ); + // No documents from the old generation remain available to reload. + assert!(GameCpuResources::load(&root).is_err()); + } +} + #[cfg(test)] mod runtime_reset_tests { use super::*; diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 58cd27494..9f174c5ef 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -581,28 +581,31 @@ impl Game<'_> { let Some(info) = self.res.items().get(&stack.item) else { return false; }; - let index = match info.equip_slot.as_deref() { - Some("head") => 0, - Some("chest") => 1, - Some("legs") => 2, - Some("feet") => 3, + let (index, slot) = match info.equip_slot.as_deref() { + Some("head") => (0, "head"), + Some("chest") => (1, "chest"), + Some("legs") => (2, "legs"), + Some("feet") => (3, "feet"), _ => return false, }; if !info.swappable { return false; } - let sound = info.equip_sound.clone(); let current = self.armor[index].clone(); - // PREVENT_ARMOR_CHANGE (Curse of Binding) outside creative, or the same stack. + // PREVENT_ARMOR_CHANGE (Curse of Binding) outside creative, or the same item. if current.as_ref().is_some_and(|c| { - (c.enchantment_level("minecraft:binding_curse") > 0 && !self.creative) || c == stack + (c.enchantment_level("minecraft:binding_curse") > 0 && !self.creative) + || c.same_item_same_components(stack) }) { return true; } - self.armor[index] = Some(ItemStack { + let equipped = ItemStack { count: 1, ..stack.clone() - }); + }; + self.armor[index] = Some(equipped.clone()); + // Player.setItemSlot: onEquipItem plays the equip sound. + self.player_equipped(slot, Some(&equipped)); if !self.creative { let mut held = stack.clone(); held.count -= 1; @@ -620,13 +623,6 @@ impl Game<'_> { } } self.apply_equipment(); - if let Some(sound) = sound { - let at = self - .player - .as_ref() - .map(|p| [p.position.x, p.position.y, p.position.z]); - self.audio.play(&sound, at, 1.0, 1.0); - } self.swing_arm(); true } diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index fde97764d..b5c6e63d9 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -208,16 +208,20 @@ impl Game<'_> { } None => false, }, + // LivingEntity's equipment SlotAccess: setItemSlot, so onEquipItem. Slot::Armor(i) => match self.armor.get_mut(*i) { Some(slot) => { - *slot = stack; + let old = std::mem::replace(slot, stack.clone()); + let name = ["head", "chest", "legs", "feet"][*i]; + self.player_on_equip(name, old.as_ref(), stack.as_ref()); self.apply_equipment(); true } None => false, }, Slot::Offhand => { - self.offhand = stack; + let old = std::mem::replace(&mut self.offhand, stack.clone()); + self.player_on_equip("offhand", old.as_ref(), stack.as_ref()); true } Slot::Ender(i) => match self.ender_items.get_mut(*i) { diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index 212ec0505..06ebf31d6 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -752,6 +752,7 @@ impl Game<'_> { physical_keys.sort(); let lod = json!({ "distance": self.settings.horizon.lod_distance, + "effective_distance": self.lod_distance(), "terrain_distance": self.terrain_distance(), "source": if self.lod.is_none() { "none" } else if self.integrated.is_some() { "integrated" } else { "local" }, "source_attempted": self.lod_source_attempted, diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 0f59e5300..b9aa5004c 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -796,9 +796,15 @@ impl Game<'_> { // LivingEntity.canEquipWithDispenser: alive, the slot usable, the // item's allowed entities, the slot empty and the dispenser rule. let target = self.targets_at(front).into_iter().find(|t| match *t { - Target::Player => slot - .armor_index() - .is_some_and(|i| allows("minecraft:player") && self.armor[i].is_none()), + // Player.canUseSlot: every slot; the armour and the off hand are + // the ones an equippable item can reach. + Target::Player => { + allows("minecraft:player") + && match slot { + Slot::OffHand => self.offhand.is_none(), + _ => slot.armor_index().is_some_and(|i| self.armor[i].is_none()), + } + } Target::Stand(i) => slot.stand_index().is_some_and(|s| { allows("minecraft:armor_stand") && self.armor_stands[i].equipment[s].is_none() }), @@ -818,11 +824,20 @@ impl Game<'_> { // setItemSlot: onEquipItem plays the equip sound and the equip event. let (at, sound) = match target { Target::Player => { - if let Some(i) = slot.armor_index() { - self.armor[i] = Some(one); - } + // Player.setItemSlot: onEquipItem plays the sound and the event. + let name = match slot.armor_index() { + Some(i) => { + self.armor[i] = Some(one.clone()); + ["head", "chest", "legs", "feet"][i] + } + None => { + self.offhand = Some(one.clone()); + "offhand" + } + }; + self.player_equipped(name, Some(&one)); self.apply_equipment(); - (self.player_view().map(|v| v.position), sound) + return true; } Target::Stand(i) => { let stand = &mut self.armor_stands[i]; @@ -849,9 +864,8 @@ impl Game<'_> { self.audio.play(&sound, Some([at.x, at.y, at.z]), 1.0, 1.0); } let who = match target { - Target::Player => Some(horizon_client::mobs::Who::Player), Target::Mob(i) => Some(horizon_client::mobs::Who::Mob(self.mobs[i].id)), - Target::Stand(_) => None, + Target::Player | Target::Stand(_) => None, }; let ctx = self.who_context(who, None); self.post_game_event("minecraft:equip", [at.x, at.y, at.z], ctx); diff --git a/crates/horizon-client/src/game/game_mode.rs b/crates/horizon-client/src/game/game_mode.rs index 902220115..1da06b089 100644 --- a/crates/horizon-client/src/game/game_mode.rs +++ b/crates/horizon-client/src/game/game_mode.rs @@ -53,6 +53,9 @@ impl Game<'_> { } } else if let Some(p) = self.player.as_mut() { p.spectator = false; + if was_spectator { + p.flying_speed = 0.05; + } if !self.creative { p.flying = false; } else if was_spectator { diff --git a/crates/horizon-client/src/game/integrated.rs b/crates/horizon-client/src/game/integrated.rs index bfbc8d66c..ff28ba258 100644 --- a/crates/horizon-client/src/game/integrated.rs +++ b/crates/horizon-client/src/game/integrated.rs @@ -660,6 +660,6 @@ fn serve( }), }; let audio = Audio::silent(&options.resources); - let mut server = Game::new(res, pack, gui, options, settings, audio)?; + let mut server = Game::new(res, pack, gui, options, settings, audio, None)?; server.run_integrated(launch, flags, tasks, ready) } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6c0fa4abf..b00c74b8b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -746,9 +746,15 @@ impl Game<'_> { let g = &mut host.hub.guests[gi]; let slot = g.selected; std::mem::swap(&mut g.inventory[slot], &mut g.offhand); + let (offhand, main) = (g.offhand.clone(), g.inventory[slot].clone()); if let Some(play) = host.play.get_mut(&conn) { play.using = None; } + // setItemInHand: the off hand, then the main hand. + self.as_guest(host, conn, |g| { + g.player_on_equip("offhand", main.as_ref(), offhand.as_ref()); + g.player_on_equip("mainhand", offhand.as_ref(), main.as_ref()); + }); } _ => {} }, @@ -844,7 +850,21 @@ impl Game<'_> { return; } let item = self.item_from_network(host, &p.item); - host.hub.guests[gi].set_menu_slot(p.slot as usize, item); + let slot = p.slot as usize; + let g = &mut host.hub.guests[gi]; + let old = g.menu_slot(slot); + g.set_menu_slot(slot, item.clone()); + // InventoryMenu's ArmorSlot and off-hand slot: setByPlayer. + let equipment = match slot { + 5..=8 => Some(["head", "chest", "legs", "feet"][slot - 5]), + 45 => Some("offhand"), + _ => None, + }; + if let Some(equipment) = equipment { + self.as_guest(host, conn, |g| { + g.player_on_equip(equipment, old.as_ref(), item.as_ref()); + }); + } } S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} @@ -1572,9 +1592,7 @@ impl Game<'_> { if w.player.ground.on_ground && !on_ground && moved[1] > 0.0 { let sprinting = w.player.sprinting; w.player - .health - .food - .add_exhaustion(if sprinting { 0.2 } else { 0.05 }); + .cause_food_exhaustion(if sprinting { 0.2 } else { 0.05 }); } let landed = (|| -> horizon_client::Result<()> { w.set_on_ground_with_movement(on_ground, false, movement)?; diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index de26e84aa..6101ce99e 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -105,9 +105,18 @@ impl Game<'_> { load_player(menu, &host.hub.guests[gi]); let result = op(menu, &env); let dropped = std::mem::take(&mut menu.dropped); + let equipped = std::mem::take(&mut menu.equipped); menu.drops.clear(); menu.crafted.clear(); store_player(menu, &mut host.hub.guests[gi]); + if !equipped.is_empty() { + let conn = host.hub.guests[gi].conn; + self.as_guest(host, conn, |g| { + for (slot, stack) in equipped { + g.player_equipped(slot, stack.as_ref()); + } + }); + } self.drop_guest_items(host, gi, dropped); result } diff --git a/crates/horizon-client/src/game/lan_pvp.rs b/crates/horizon-client/src/game/lan_pvp.rs index dba2ed8e6..01537cee6 100644 --- a/crates/horizon-client/src/game/lan_pvp.rs +++ b/crates/horizon-client/src/game/lan_pvp.rs @@ -81,7 +81,7 @@ impl Game<'_> { if let Some(p) = self.player.as_mut() && !self.creative { - p.health.food.exhaustion = (p.health.food.exhaustion + 0.1).min(40.0); + p.cause_food_exhaustion(0.1); } self.swing_arm(); Some(Strike { diff --git a/crates/horizon-client/src/game/mods.rs b/crates/horizon-client/src/game/mods.rs index b6abf38ef..01787ec02 100644 --- a/crates/horizon-client/src/game/mods.rs +++ b/crates/horizon-client/src/game/mods.rs @@ -75,7 +75,18 @@ pub(super) fn content_root( { continue; } - match Content::read(path, m) { + let content = Content::read(path, m).and_then(|content| { + // The first of two mods owning one namespace stays on. + let own = (m.id.as_str(), content.namespaces.as_slice()); + match mods + .iter() + .find_map(|c| horizon_mods::content::clash((&c.id, &c.content.namespaces), own)) + { + Some(e) => Err(e), + None => Ok(content), + } + }); + match content { Ok(content) => mods.push(ContentMod { id: m.id.clone(), content, diff --git a/crates/horizon-client/src/game/natural_spawning.rs b/crates/horizon-client/src/game/natural_spawning.rs index 9bf7023af..0fab09bde 100644 --- a/crates/horizon-client/src/game/natural_spawning.rs +++ b/crates/horizon-client/src/game/natural_spawning.rs @@ -170,9 +170,15 @@ impl NaturalLevel for GameLevel<'_, '_> { fn creature_probability(&self, x: i32, y: i32, z: i32) -> f32 { self.biome(x, y, z).map_or(0.1, |b| b.creature_probability) } - fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec { + fn structures_at( + &self, + x: i32, + y: i32, + z: i32, + wanted: &dyn Fn(&str) -> bool, + ) -> Vec { self.game - .structures_reaching([x, y, z]) + .structures_reaching_where([x, y, z], wanted) .into_iter() .map(|(id, in_piece)| StructureAt { id, diff --git a/crates/horizon-client/src/game/player_equip.rs b/crates/horizon-client/src/game/player_equip.rs new file mode 100644 index 000000000..a13c6400a --- /dev/null +++ b/crates/horizon-client/src/game/player_equip.rs @@ -0,0 +1,94 @@ +//! `LivingEntity.onEquipItem` for players: the equip sound and the equip +//! game event when an armour or off-hand slot takes a different item, from +//! every path that calls it (use, the inventory menu, the creative screen, +//! the swap-hands key, dispensers), for the host and for LAN guests. +use super::Game; +use horizon_client::items::ItemStack; + +/// The equipment slots `onEquipItem` can act on, as `EquipmentSlot` names: +/// the armour (`Player.doesEmitEquipEvent`: these emit the game event) and +/// the off hand. +const ARMOR: [&str; 4] = ["head", "chest", "legs", "feet"]; +const OFFHAND: &str = "offhand"; + +/// `ItemStack.isSameItemSameComponents` over optional stacks. +fn same(a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.same_item_same_components(b), + _ => false, + } +} + +impl Game<'_> { + /// The armour (head first) and the off hand, in `EquipmentSlot` order of + /// the inventory menu's slots. + pub(super) fn player_equipment(&self) -> [Option; 5] { + let [head, chest, legs, feet] = self.armor.clone(); + [head, chest, legs, feet, self.offhand.clone()] + } + + /// `onEquipItem` for every slot that changed since `before`: what the + /// server does for the creative screen, which sends each changed slot + /// (`handleSetCreativeModeSlot` sets it by player). + pub(super) fn player_equipment_changed(&mut self, before: &[Option; 5]) { + let after = self.player_equipment(); + for (i, slot) in ARMOR.into_iter().chain([OFFHAND]).enumerate() { + self.player_on_equip(slot, before[i].as_ref(), after[i].as_ref()); + } + } + + /// `LivingEntity.onEquipItem(slot, old, new)` for the player in place + /// (the host, or a guest inside `as_guest`). + pub(super) fn player_on_equip( + &mut self, + slot: &str, + old: Option<&ItemStack>, + new: Option<&ItemStack>, + ) { + if !same(old, new) { + self.player_equipped(slot, new); + } + } + + /// The body of `onEquipItem` once the item changed: the item's + /// `Equippable.equipSound` when it is equipped in its own slot, and the + /// `equip` / `unequip` game event for armour. Nothing on a client (the + /// server plays it) or for a spectator. The player's `firstTick` never + /// sees an equip here: loading a save sets the slots directly. + pub(super) fn player_equipped(&mut self, slot: &str, new: Option<&ItemStack>) { + if self.remote.is_some() || self.spectator() { + return; + } + let Some(at) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let at = [at.x, at.y, at.z]; + let equippable = new + .and_then(|s| self.res.items().get(&s.item)) + .and_then(|info| { + let own = info.equip_slot.as_deref()?; + Some((own == slot, info.equip_sound.clone())) + }); + if let Some((true, sound)) = &equippable { + let sound = sound + .as_deref() + .unwrap_or("minecraft:item.armor.equip_generic"); + // Player.getSoundSource: PLAYERS. + let players = horizon_client::settings::SOUND_SOURCES + .iter() + .position(|s| *s == "player") + .unwrap_or(0); + self.audio.play_on(players, sound, Some(at), 1.0, 1.0); + } + if ARMOR.contains(&slot) { + let event = if equippable.is_some() { + "minecraft:equip" + } else { + "minecraft:unequip" + }; + let ctx = self.player_context(None); + self.post_game_event(event, at, ctx); + } + } +} diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index 51cb1fc0a..52ab5060a 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -280,7 +280,7 @@ impl Game<'_> { } } EffectAction::Exhaust(amount) => { - p.health.food.exhaustion = (p.health.food.exhaustion + amount).min(40.0); + p.cause_food_exhaustion(amount); } EffectAction::Eat(nutrition, saturation) => { let food = &mut p.health.food; diff --git a/crates/horizon-client/src/game/render_tick.rs b/crates/horizon-client/src/game/render_tick.rs index ba07755b9..cdc7a68c6 100644 --- a/crates/horizon-client/src/game/render_tick.rs +++ b/crates/horizon-client/src/game/render_tick.rs @@ -3,7 +3,7 @@ use super::{Dim, Game}; use horizon_client::fog::{FogData, FogInputs, FogType, fog_type, update_rain_fog}; use horizon_client::{ - animate_tick::{AnimateContext, animate_tick, campfire_particles}, + animate_tick::{AnimateContext, animate_tick, campfire_particles, marker_particle_target}, biome::Biomes, blocks::{BlockFacts, Fluid}, chunk::{HEIGHT, MIN_Y}, @@ -121,6 +121,11 @@ impl Game<'_> { }; let at = [camera.x, camera.y, camera.z]; let day = self.world.day_time; + let has_sky_light = self.dim == Dim::Overworld; + // CommonUniforms.getEyeBrightness: the camera entity's eye block. + let eye = self.eye_position().unwrap_or(at).map(|v| v.floor() as i32); + let light = self.world.light(eye[0], eye[1], eye[2]); + let eye_light = [light & 15, if has_sky_light { light >> 4 } else { 0 }]; horizon_client::gfx::ShaderInputs { rain, thunder, @@ -135,10 +140,11 @@ impl Game<'_> { Dim::Nether => -1, Dim::End => 1, }, - has_sky_light: self.dim == Dim::Overworld, + has_sky_light, moon_phase: day.div_euclid(24_000).rem_euclid(8) as u8, day_fraction: (day.rem_euclid(24_000) as f32 + partial_tick) / 24_000.0, partial_tick, + eye_light, } } /// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water. @@ -284,6 +290,15 @@ impl Game<'_> { } else { (0.0, 0.0) }; + let marker = marker_particle_target(self.mode, self.stack_in(self.selected)); + let marker_options = |state| { + let (sprite, tint) = Self::block_particle_sprite(&self.pack, self.res.facts(), state)?; + Some(ParticleOptions::block( + ParticleType::BlockMarker, + sprite, + tint, + )) + }; let world = &self.world; let facts = self.res.facts(); let biomes = self.res.biomes(); @@ -300,6 +315,7 @@ impl Game<'_> { biomes, registry: self.pack.assets.registry, raining_at: &raining_at, + marker: marker.map(|name| (name, &marker_options as &dyn Fn(_) -> _)), }; if let Some(e) = eye { let block = [ diff --git a/crates/horizon-client/src/game/sculk.rs b/crates/horizon-client/src/game/sculk.rs index 84078c9cf..a5a24725b 100644 --- a/crates/horizon-client/src/game/sculk.rs +++ b/crates/horizon-client/src/game/sculk.rs @@ -700,26 +700,39 @@ impl Game<'_> { pub(super) fn tick_sculk_blocks(&mut self) -> Result<()> { self.sculk_prepare(); self.sculk_sync_index(); - let keys: Vec<(i32, i32, i32)> = self.sculk.index.iter().copied().collect(); - for key in keys { - let ticking = self.chunk_ticks(key.0 >> 4, key.2 >> 4); - if !ticking { - continue; - } - self.tick_sculk_block(key)?; + // `ServerLevel.shouldTickBlocksAt` in a block-ticking chunk, from + // every player's tickets (`update_chunk_tickets`), once the chunk is + // lit: asked once per chunk, as the sensors share few chunks. Nothing + // a sculk tick does loads, unloads or lights a chunk or moves a ticket. + let levels = self.tickets.levels(); + let chunks = &self.world.chunks; + let mut ticking = FxHashMap::<(i32, i32), bool>::default(); + let mut ticks = |cx: i32, cz: i32| { + *ticking.entry((cx, cz)).or_insert_with(|| { + levels.block_ticking(cx, cz) && chunks.get(&(cx, cz)).is_some_and(|c| c.lit) + }) + }; + // The ticking ones in the index's order, with whether the chunks + // around them tick too. + let due: Vec<((i32, i32, i32), bool)> = self + .sculk + .index + .iter() + .filter_map(|&key| { + let (cx, cz) = (key.0 >> 4, key.2 >> 4); + ticks(cx, cz).then(|| { + let adjacent = (-1..=1).all(|dx| (-1..=1).all(|dz| ticks(cx + dx, cz + dz))); + (key, adjacent) + }) + }) + .collect(); + for (key, adjacent) in due { + self.tick_sculk_block(key, adjacent)?; } Ok(()) } - /// `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 { - 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<()> { + fn tick_sculk_block(&mut self, key: (i32, i32, i32), adjacent: bool) -> Result<()> { let time = self.world.game_time; - let adjacent = (-1..=1) - .all(|dx| (-1..=1).all(|dz| self.chunk_ticks((key.0 >> 4) + dx, (key.2 >> 4) + dz))); let Some(entity) = self.sculk_entity(key) else { self.sculk.index.remove(&key); return Ok(()); @@ -1144,11 +1157,11 @@ impl Game<'_> { /// `LightmapRenderStateExtractor`: (brightness taken off the gamma /// option, the pulsing light scale). pub(super) fn darkness_lighting(&self, partial: f32) -> (f32, f32) { - // options.darknessEffectScale is at its default of 100%. - let modifier = self.darkness_blend(partial); + let scale = self.settings.file.double("darknessEffectScale") as f32; + let modifier = self.darkness_blend(partial) * scale; let pulse = ((self.ticks as f32 - partial) * std::f32::consts::PI * 0.025).cos() * 0.45 * modifier; - (modifier, pulse.max(0.0)) + (modifier, pulse.max(0.0) * scale) } /// `LightmapRenderStateExtractor`: the night vision effect's intensity diff --git a/crates/horizon-client/src/game/shader_packs.rs b/crates/horizon-client/src/game/shader_packs.rs index da4e8f594..6b9ee33dc 100644 --- a/crates/horizon-client/src/game/shader_packs.rs +++ b/crates/horizon-client/src/game/shader_packs.rs @@ -6,6 +6,7 @@ use super::Game; use horizon_client::shader_pack::{self, ShaderPack, Stamp}; use horizon_client::text::Text; +use horizon_shaderpack::properties::SkyDirectives; use std::{ path::PathBuf, time::{Duration, Instant}, @@ -26,6 +27,14 @@ impl ShaderPacks { pub(super) fn id(&self) -> Option<&str> { self.pack.as_ref().map(|p| p.id.as_str()) } + /// What a loaded Java pack changes in the vanilla sky of `dimension` + /// (0 overworld, -1 the Nether, 1 the End): its `sunPathRotation`, and + /// whether it keeps the clouds, sun and moon (Iris's sky mixins). + pub(super) fn java_sky(&self, dimension: i8) -> Option<(f32, SkyDirectives)> { + let java = self.pack.as_ref()?.java.as_ref()?; + let folder = &java.folders[java.folder_for(dimension)?]; + Some((folder.directives.sun_path_rotation, java.sky)) + } } /// `shaderpacks/` beside `options.txt`. diff --git a/crates/horizon-client/src/game/startup_menu.rs b/crates/horizon-client/src/game/startup_menu.rs index 9531b0f38..c5b19763c 100644 --- a/crates/horizon-client/src/game/startup_menu.rs +++ b/crates/horizon-client/src/game/startup_menu.rs @@ -688,6 +688,7 @@ mod tests { vanilla_root: PathBuf::new(), pack_error: None, started: Instant::now(), + panorama_rotation: Default::default(), progress: Progress::new(), receiver, loaded: None, diff --git a/crates/horizon-client/src/game/structures.rs b/crates/horizon-client/src/game/structures.rs index e941f2fd9..95a65e4ae 100644 --- a/crates/horizon-client/src/game/structures.rs +++ b/crates/horizon-client/src/game/structures.rs @@ -7,6 +7,15 @@ impl Game<'_> { /// Structures reaching `pos`: (id, inside a piece). `getStructureAt` /// tests the start's whole box, `getStructureWithPieceAt` a piece's. pub(super) fn structures_reaching(&self, pos: [i32; 3]) -> Vec<(String, bool)> { + self.structures_reaching_where(pos, &|_| true) + } + /// The same, for the structures whose id `wanted` takes: the others' + /// starts aren't looked up. + pub(super) fn structures_reaching_where( + &self, + pos: [i32; 3], + wanted: &dyn Fn(&str) -> bool, + ) -> Vec<(String, bool)> { let Some(chunk) = self.world.chunks.get(&(pos[0] >> 4, pos[2] >> 4)) else { return Vec::new(); }; @@ -18,6 +27,9 @@ impl Game<'_> { }; let mut out: Vec<(String, bool)> = Vec::new(); for (id, (sx, sz)) in &chunk.structure_refs { + if !wanted(id) { + continue; + } for start in locator.starts_at(*sx, *sz) { if *start.name != **id || !start.bounding_box.is_inside(pos) { continue; diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index 31a1c9e72..e8d2aaab2 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -72,6 +72,8 @@ pub mod translucency; pub(crate) mod upload; mod world_post; +/// A column whose every section has its mesh (`Renderer::lod_detail_columns`). +const COMPLETE_COLUMN: u32 = (1 << (crate::chunk::HEIGHT / 16)) - 1; /// A section's instance: its camera-relative origin and, in `w`, the step of /// its fixed-point UVs (`terrain.wgsl`'s `terrain_uv`). fn section_instance(origin: [f32; 3]) -> [f32; 4] { @@ -238,6 +240,9 @@ pub struct ShaderInputs { /// The time of day as a fraction (0 sunrise, 0.25 noon) and the partial tick. pub day_fraction: f32, pub partial_tick: f32, + /// The block and sky light (0..15) of the block holding the camera + /// entity's eyes; no sky light without a sky. + pub eye_light: [u8; 2], } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -370,7 +375,17 @@ pub struct Renderer { depth: wgpu::TextureView, sections: resident::Resident, lods: HashMap, + /// The chunk columns the resident tiles leave out (`Lod::take_cutout`): + /// their sections are drawn even past the render distance, so terrain + /// leaving it never opens a hole before the tiles fill it in. + lod_cutout: crate::fast_hash::FxHashSet<(i32, i32)>, + /// Removed sections of `lod_cutout` columns, released once tiles cover them. + lod_retiring: crate::fast_hash::FxHashSet, + /// Finished tile meshes `upload_lods` has yet to upload. + lod_pending: Option, detail_columns: HashMap<(i32, i32), u32>, + /// Bumped whenever a column becomes or stops being complete. + detail_revision: u64, arena: arena::Arena, sorted_indices: arena::Arena, translucent_sorter: translucency::Sorter, @@ -509,6 +524,46 @@ fn terrain_group( ], }) } +/// CPU texture uploads prepared by the resource worker. Consumed by renderer +/// construction so the temporary mip chains are released after GPU upload. +pub struct PreparedTextures { + sprites: Vec<(Vec, u32)>, + forcefield: (Vec, u32), +} +impl PreparedTextures { + pub fn new( + pixels: &[u8], + size: u32, + layers: u32, + settings: &[crate::mipmap::Settings], + forcefield: (&[u8], u32), + ) -> Self { + Self::with_split(pixels, size, layers, settings, forcefield, sprite_split()) + } + + fn with_split( + pixels: &[u8], + size: u32, + layers: u32, + settings: &[crate::mipmap::Settings], + forcefield: (&[u8], u32), + split: u32, + ) -> Self { + let layer_bytes = (size * size * 4) as usize; + Self { + sprites: (0..layers.div_ceil(split).max(1)) + .map(|array| { + let first = array * split; + let count = layers.saturating_sub(first).clamp(1, split); + let start = (first as usize * layer_bytes).min(pixels.len()); + mip_chain(&pixels[start..], size, settings, first, count) + }) + .collect(), + forcefield: mip_chain(forcefield.0, forcefield.1, &[], 0, 1), + } + } +} + fn mip_chain( pixels: &[u8], size: u32, @@ -792,6 +847,7 @@ impl Renderer { hud_atlas: (&[u8], u32, u32), forcefield: (&[u8], u32), panorama_faces: &panorama::Faces, + prepared: Option, previous: Option<&Self>, api: GraphicsApi, ) -> Result { @@ -1165,20 +1221,17 @@ impl Renderer { usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false, }); - let layer_bytes = (sprite_size * sprite_size * 4) as usize; + let prepared = prepared.unwrap_or_else(|| { + PreparedTextures::new(sprite_pixels, sprite_size, layers, sprite_mips, forcefield) + }); let mut mip_levels = 1; - let sprite_textures: Vec = (0..sprite_arrays) - .map(|array| { - let first = array * split; + let sprite_textures: Vec = prepared + .sprites + .into_iter() + .enumerate() + .map(|(array, (mips, levels))| { + let first = array as u32 * split; let count = layers.saturating_sub(first).clamp(1, split); - let start = (first as usize * layer_bytes).min(sprite_pixels.len()); - let (mips, levels) = mip_chain( - &sprite_pixels[start..], - sprite_size, - sprite_mips, - first, - count, - ); mip_levels = levels; device.create_texture_with_data( &queue, @@ -1639,9 +1692,8 @@ impl Renderer { }); // WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture // (repeat, linear minification with mipmaps, nearest magnification). - let (forcefield_pixels, forcefield_size) = forcefield; - let (forcefield_mips, forcefield_levels) = - mip_chain(forcefield_pixels, forcefield_size, &[], 0, 1); + let forcefield_size = forcefield.1; + let (forcefield_mips, forcefield_levels) = prepared.forcefield; let forcefield_texture = device.create_texture_with_data( &queue, &wgpu::TextureDescriptor { @@ -2038,7 +2090,11 @@ impl Renderer { depth, sections: resident::Resident::default(), lods: HashMap::new(), + lod_cutout: Default::default(), + lod_retiring: Default::default(), + lod_pending: None, detail_columns: HashMap::new(), + detail_revision: 0, arena, sorted_indices, translucent_sorter: translucency::Sorter::default(), @@ -2252,13 +2308,15 @@ impl Renderer { if changed { self.block_entity_revision = next_block_entity_revision(); } + if !self.lod_retiring.is_empty() { + self.lod_retiring.remove(&key); + } self.release_section(key); let section = self.upload_mesh(mesh); - if section.is_some() || (mesh.solid.is_empty() && mesh.translucent.is_empty()) { - *self.detail_columns.entry((key.0, key.2)).or_default() |= 1 << key.1; - } else if let Some(mask) = self.detail_columns.get_mut(&(key.0, key.2)) { - *mask &= !(1 << key.1); - } + self.set_detail( + key, + section.is_some() || (mesh.solid.is_empty() && mesh.translucent.is_empty()), + ); if let Some(section) = section { self.sections.insert(key, section); } @@ -2412,7 +2470,11 @@ impl Renderer { self.block_entity_revision = next_block_entity_revision(); self.sections.clear(); self.lods.clear(); + self.lod_cutout.clear(); + self.lod_retiring.clear(); + self.lod_pending = None; self.detail_columns.clear(); + self.detail_revision += 1; self.arena.clear(); if let Some(flat) = &mut self.flat { flat.clear(); @@ -2422,23 +2484,44 @@ impl Renderer { self.occlusion.clear(); } pub fn lod_detail_columns(&self) -> impl Iterator + '_ { - let complete = (1u32 << (crate::chunk::HEIGHT / 16)) - 1; self.detail_columns .iter() - .filter_map(move |(&column, &mask)| (mask == complete).then_some(column)) + .filter_map(move |(&column, &mask)| (mask == COMPLETE_COLUMN).then_some(column)) + } + /// Changes whenever `lod_detail_columns` does. + pub fn lod_detail_revision(&self) -> u64 { + self.detail_revision + } + /// Whether the section at `key` has its mesh, for `lod_detail_columns`. + fn set_detail(&mut self, key: SectionKey, meshed: bool) { + let column = (key.0, key.2); + let mask = self.detail_columns.get(&column).copied().unwrap_or(0); + let next = if meshed { + mask | 1 << key.1 + } else { + mask & !(1 << key.1) + }; + if (mask == COMPLETE_COLUMN) != (next == COMPLETE_COLUMN) { + self.detail_revision += 1; + } + if next == 0 { + self.detail_columns.remove(&column); + } else { + self.detail_columns.insert(column, next); + } } pub fn remove(&mut self, key: SectionKey) { - if let Some(mask) = self.detail_columns.get_mut(&(key.0, key.2)) { - *mask &= !(1 << key.1); - if *mask == 0 { - self.detail_columns.remove(&(key.0, key.2)); - } - } + self.set_detail(key, false); if self.block_entities.remove(&key).is_some() { self.block_entity_revision = next_block_entity_revision(); } self.occlusion.remove(key); - self.release_section(key); + if !self.lod_cutout.is_empty() && self.lod_cutout.contains(&(key.0, key.2)) { + // Distant tiles still leave its column out: drawn until they don't. + self.lod_retiring.insert(key); + } else { + self.release_section(key); + } } /// Run `pack`'s stages over the world from now on (`None`: no pack, the /// vanilla frame). On error the previous pack stays. @@ -2826,6 +2909,7 @@ impl Renderer { }); } let reachable = &self.occlusion; + let cutout = &self.lod_cutout; let mut visible = std::mem::take(&mut self.visible); visible.clear(); crate::spans::time("visibility", || { @@ -2834,6 +2918,7 @@ impl Renderer { (frame.detail_distance / 16.0) as i32, &view, |k| !culling || reachable.contains(k), + |x, z| !cutout.is_empty() && cutout.contains(&(x, z)), &mut visible, ) }); @@ -3552,6 +3637,11 @@ impl Renderer { size, &self.world_post, pack_uniform, + java_stages::JavaFrame { + eye_light: frame.shader.eye_light, + sun_angle: frame.sky.sun_angle, + moon_angle: frame.sky.moon_angle, + }, ), }; self.world_post @@ -4487,6 +4577,50 @@ mod sprite_upload_tests { } } + #[test] + fn prepared_texture_uploads_preserve_layer_order_and_settings() { + let size = 4; + let layers = 5; + let pixels: Vec = (0..size * size * layers) + .flat_map(|i| [i as u8, (i * 3) as u8, 99, if i % 3 == 0 { 0 } else { 255 }]) + .collect(); + let settings: Vec<_> = (0..layers) + .map(|i| crate::mipmap::Settings { + strategy: if i % 2 == 0 { + crate::mipmap::Strategy::Mean + } else { + crate::mipmap::Strategy::StrictCutout + }, + ..Default::default() + }) + .collect(); + let border = [20, 30, 40, 128].repeat(16); + let expected = mip_chain(&pixels, size, &settings, 0, layers); + // A partial final array and an exact boundary exercise the global + // layer offset used to select each sprite's mipmap settings. + for split in [1, 2, 5, 8] { + let prepared = PreparedTextures::with_split( + &pixels, + size, + layers, + &settings, + (&border, size), + split, + ); + assert_eq!(prepared.sprites.len(), layers.div_ceil(split) as usize); + let actual: Vec<_> = prepared + .sprites + .iter() + .flat_map(|(bytes, levels)| { + assert_eq!(*levels, expected.1); + bytes.iter().copied() + }) + .collect(); + assert_eq!(actual, expected.0); + assert_eq!(prepared.forcefield, mip_chain(&border, size, &[], 0, 1)); + } + } + #[test] fn mip_chain_allocates_exactly_its_size() { for size in [16, 64] { diff --git a/crates/horizon-client/src/gfx/java_stages.rs b/crates/horizon-client/src/gfx/java_stages.rs index d3e393e07..e9f8ddbb1 100644 --- a/crates/horizon-client/src/gfx/java_stages.rs +++ b/crates/horizon-client/src/gfx/java_stages.rs @@ -11,8 +11,21 @@ use super::pack_stages::FrameUniform; use crate::java_pack::{JavaFolder, JavaPasses}; use glam::{Mat3, Mat4, Vec3, Vec4}; use horizon_shaderpack::pipeline::TargetSettings; -use horizon_shaderpack::pipeline::{Program, target_index}; -use std::collections::{BTreeMap, BTreeSet}; +use horizon_shaderpack::pipeline::{Directives, Program, target_index}; +use horizon_shaderpack::uniforms::{CustomUniforms, SmoothFloat, UniformState}; +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +/// What Iris's uniforms read from the game that the frame uniform doesn't +/// carry. +#[derive(Clone, Copy, Debug, Default)] +pub struct JavaFrame { + /// The block and sky light at the camera's eye block, 0..15 + /// (`CommonUniforms.getEyeBrightness`). + pub eye_light: [u8; 2], + /// `visual/sun_angle` and `visual/moon_angle`, degrees (0: overhead). + pub sun_angle: f32, + pub moon_angle: f32, +} /// Iris's `noisetex` size (`noiseTextureResolution`'s default). const NOISE_SIZE: u32 = 256; @@ -203,6 +216,7 @@ struct Folder { flipped_at_end: BTreeSet, passes: Vec, final_pass: Option, + directives: Directives, } pub struct JavaStages { @@ -216,6 +230,10 @@ pub struct JavaStages { last: Option, frames: u32, previous: Option<(Mat4, Mat4, Vec3)>, + uniforms: CustomUniforms, + uniform_state: UniformState, + /// `eyeBrightnessSmooth`, block then sky. + eye_smooth: [SmoothFloat; 2], } impl JavaStages { @@ -256,6 +274,7 @@ impl JavaStages { flipped_at_end: plan.flipped_at_end.clone(), passes, final_pass, + directives: plan.directives, }) }) .collect::, _>>()?; @@ -273,6 +292,9 @@ impl JavaStages { last: None, frames: 0, previous: None, + uniforms: pack.uniforms.clone(), + uniform_state: UniformState::default(), + eye_smooth: [SmoothFloat::default(); 2], }) } @@ -289,6 +311,7 @@ impl JavaStages { size: [u32; 2], post: &super::world_post::Post, frame: FrameUniform, + world: JavaFrame, ) -> &wgpu::BindGroup { let dimension = (frame.dimension[0] as i32).clamp(-1, 1); let folder = self.folder_for[(dimension + 1) as usize].unwrap_or(0); @@ -302,7 +325,8 @@ impl JavaStages { let now = std::time::Instant::now(); let frame_time = self.last.map_or(0.0, |t| (now - t).as_secs_f32()); self.last = Some(now); - let inputs = Inputs::new( + let directives = self.folders[folder].directives; + let mut inputs = Inputs::new( &frame, size, self.started.elapsed().as_secs_f32(), @@ -310,6 +334,16 @@ impl JavaStages { self.frames, self.previous, ); + inputs.set_world(&world, directives.sun_path_rotation); + let half_life = directives.eye_brightness_half_life; + for (i, smooth) in self.eye_smooth.iter_mut().enumerate() { + inputs.eye_smooth[i] = smooth.update(inputs.eye[i], half_life, half_life, frame_time); + } + self.uniforms + .update(&mut self.uniform_state, frame_time, &|name| { + inputs.builtin(name) + }); + inputs.custom = self.uniform_state.values().clone(); self.previous = Some((inputs.view, inputs.projection, inputs.camera)); self.frames = self.frames.wrapping_add(1); let bound = self.bound.as_ref().expect("bound above"); @@ -1405,6 +1439,32 @@ struct Inputs { frame_time: f32, frames: u32, frame: FrameUniform, + /// `eyeBrightness` and `eyeBrightnessSmooth`: block, sky light × 16. + eye: [f32; 2], + eye_smooth: [f32; 2], + /// `CelestialUniforms`, in view space. + sun_position: Vec3, + moon_position: Vec3, + up_position: Vec3, + /// `sunAngle` and `shadowAngle`, 0..1. + sun_angle: f32, + shadow_angle: f32, + is_day: bool, + /// The pack's custom uniforms this frame. + custom: HashMap>, +} + +/// `CelestialUniforms.getSunAngle`: the body's angle plus 90, in 0..360 +/// (0 at sunrise for the sun). +fn celestial_angle(degrees: f32) -> f32 { + let c = degrees + 90.0; + if c < 0.0 { + c + 360.0 + } else if c > 360.0 { + c - 360.0 + } else { + c + } } impl Inputs { @@ -1427,7 +1487,7 @@ impl Inputs { ); let projection = to_gl * Mat4::from_cols_array_2d(&frame.projection); let camera = Vec4::from(frame.camera_position).truncate(); - Self { + let mut out = Self { view, projection, camera, @@ -1437,20 +1497,64 @@ impl Inputs { frame_time, frames, frame: *frame, - } + eye: [0.0; 2], + eye_smooth: [0.0; 2], + sun_position: Vec3::ZERO, + moon_position: Vec3::ZERO, + up_position: Vec3::ZERO, + sun_angle: 0.0, + shadow_angle: 0.0, + is_day: true, + custom: HashMap::new(), + }; + out.set_world(&JavaFrame::default(), 0.0); + out } - /// The value of Iris uniform `name`, as its scalars in order; `None` for - /// one Horizon doesn't provide (it stays zero). + /// The light at the eye and the sun and moon, tilted by the pack's + /// `sunPathRotation` as Iris tilts them. + fn set_world(&mut self, world: &JavaFrame, sun_path_rotation: f32) { + self.eye = world.eye_light.map(|l| f32::from(l) * 16.0); + self.eye_smooth = self.eye; + // CelestialUniforms.getCelestialPosition: the sky's Y -90, the + // tilt, the body's angle, then (0, 100, 0) as a point. + let sky = self.view * Mat4::from_rotation_y((-90f32).to_radians()); + let body = |angle: f32| { + let m = sky + * Mat4::from_rotation_z(sun_path_rotation.to_radians()) + * Mat4::from_rotation_x(angle.to_radians()); + m.transform_point3(Vec3::new(0.0, 100.0, 0.0)) + }; + self.sun_position = body(world.sun_angle); + self.moon_position = body(world.moon_angle); + self.up_position = sky.transform_vector3(Vec3::new(0.0, 100.0, 0.0)); + let sun = celestial_angle(world.sun_angle); + self.is_day = sun < 180.0; + self.sun_angle = sun / 360.0; + self.shadow_angle = if self.is_day { + sun + } else { + celestial_angle(world.moon_angle) + } / 360.0; + } + + /// The value of uniform `name`, as its scalars in order: Iris's own, + /// else the pack's custom uniform; `None` for one Horizon doesn't + /// provide (it stays zero). fn value(&self, name: &str) -> Option> { + self.builtin(name) + .or_else(|| self.custom.get(name).cloned()) + } + + /// The value of Iris uniform `name`; `None` for one Horizon doesn't + /// provide. + fn builtin(&self, name: &str) -> Option> { if let Some(flag) = name.strip_prefix("iris_bool_") { return self.value(flag); } let f = &self.frame; let mat = |m: Mat4| m.to_cols_array().to_vec(); let vec3 = |v: Vec3| v.to_array().to_vec(); - let in_view = |v: Vec3| (self.view * v.extend(0.0)).truncate() * 100.0; - let sun = Vec4::from(f.sun).truncate(); let day = f.time[2].rem_euclid(1.0); // The full-screen passes' own matrices: 0..1 onto the screen. let screen = Mat4::orthographic_rh_gl(0.0, 1.0, 0.0, 1.0, -1.0, 1.0); @@ -1476,12 +1580,16 @@ impl Inputs { "frameCounter" => vec![(self.frames % 720_720) as f32], "worldTime" => vec![(day * 24000.0).floor()], "worldDay" => vec![0.0], - "sunAngle" => vec![day], - "shadowAngle" => vec![if day < 0.5 { day } else { day - 0.5 }], - "sunPosition" => vec3(in_view(sun)), - "moonPosition" => vec3(in_view(-sun)), - "shadowLightPosition" => vec3(in_view(if sun.y >= 0.0 { sun } else { -sun })), - "upPosition" => vec3(in_view(Vec3::Y)), + "sunAngle" => vec![self.sun_angle], + "shadowAngle" => vec![self.shadow_angle], + "sunPosition" => vec3(self.sun_position), + "moonPosition" => vec3(self.moon_position), + "shadowLightPosition" => vec3(if self.is_day { + self.sun_position + } else { + self.moon_position + }), + "upPosition" => vec3(self.up_position), "moonPhase" => vec![f.moon[3]], "rainStrength" | "wetness" => vec![f.weather[0]], "thunderStrength" => vec![f.weather[1]], @@ -1491,9 +1599,9 @@ impl Inputs { "nightVision" => vec![f.camera_state[1]], "darknessFactor" => vec![f.camera_state[2]], "screenBrightness" => vec![1.0], - // Sky light at full with a sky, no block light: Horizon doesn't - // give the light at the eye yet. - "eyeBrightness" | "eyeBrightnessSmooth" => vec![0.0, 240.0 * f.dimension[1]], + "eyeBrightness" => self.eye.to_vec(), + // An ivec2: the smoothed value truncated. + "eyeBrightnessSmooth" => self.eye_smooth.map(f32::trunc).to_vec(), "hasSkylight" => vec![f.dimension[1]], "iris_ModelViewMatrix" | "iris_ModelViewMatrixInverse" => mat(Mat4::IDENTITY), "iris_ProjectionMatrix" | "iris_ModelViewProjectionMatrix" => mat(screen), @@ -1559,6 +1667,60 @@ mod tests { ); } + #[test] + fn celestial_and_eye_uniforms_follow_iris() { + let frame = FrameUniform { + view: Mat4::IDENTITY.to_cols_array_2d(), + ..Default::default() + }; + let close = |a: Option>, b: [f32; 3]| { + let a = a.unwrap(); + assert!( + a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-3), + "{a:?} != {b:?}" + ); + }; + let mut inputs = Inputs::new(&frame, [300, 200], 0.0, 0.0, 0, None); + // Sunrise: the sun in the east, at angle 0; the moon in the west. + let world = |sun_angle: f32| JavaFrame { + eye_light: [3, 15], + sun_angle, + moon_angle: sun_angle + 180.0, + }; + inputs.set_world(&world(-90.0), 0.0); + close(inputs.value("sunPosition"), [100.0, 0.0, 0.0]); + close(inputs.value("moonPosition"), [-100.0, 0.0, 0.0]); + close(inputs.value("upPosition"), [0.0, 100.0, 0.0]); + assert_eq!(inputs.value("sunAngle"), Some(vec![0.0])); + assert_eq!(inputs.value("eyeBrightness"), Some(vec![48.0, 240.0])); + // Complementary Unbound's sunPathRotation of -40 at noon: the sun + // where its GetSunVector puts it, (0, cos 40, sin 40). + let tilt = (-40f32).to_radians(); + inputs.set_world(&world(0.0), -40.0); + close( + inputs.value("sunPosition"), + [0.0, 100.0 * tilt.cos(), -100.0 * tilt.sin()], + ); + assert_eq!(inputs.value("sunAngle"), Some(vec![0.25])); + close(inputs.value("shadowLightPosition"), { + let s = inputs.sun_position; + [s.x, s.y, s.z] + }); + // Night: the moon casts the shadows. + inputs.set_world(&world(150.0), 0.0); + assert!(!inputs.is_day); + assert_eq!( + inputs.value("shadowLightPosition"), + inputs.value("moonPosition") + ); + assert!((inputs.value("shadowAngle").unwrap()[0] - 60.0 / 360.0).abs() < 1e-6); + // Custom uniforms come after Iris's own. + inputs.custom.insert("eyeBrightnessM".into(), vec![0.5]); + inputs.custom.insert("sunAngle".into(), vec![9.0]); + assert_eq!(inputs.value("eyeBrightnessM"), Some(vec![0.5])); + assert_ne!(inputs.value("sunAngle"), Some(vec![9.0])); + } + #[test] fn gl_projection_from_reversed_depth() { // A point at the near plane is GL's -1, at the far plane 1. diff --git a/crates/horizon-client/src/gfx/lod.rs b/crates/horizon-client/src/gfx/lod.rs index 6699a62a3..734110b5c 100644 --- a/crates/horizon-client/src/gfx/lod.rs +++ b/crates/horizon-client/src/gfx/lod.rs @@ -1,8 +1,46 @@ //! Far meshes share the terrain arena and passes, with their actual bounds //! rather than the 16³ boxes used by the near-section residency walk. use super::{Frustum, Renderer, SectionGpu}; -use crate::{lod::TileKey, mesher::SectionMesh}; +use crate::{ + fast_hash::{FxHashMap, FxHashSet}, + lod::TileKey, + mesher::SectionMesh, +}; use glam::{DVec3, Vec3}; +use std::time::{Duration, Instant}; + +/// Finished tile meshes not uploaded yet, the tiles they replace (removed +/// once every mesh is in) and the columns they leave out. +#[derive(Default)] +pub(super) struct Pending { + meshes: FxHashMap, + removed: FxHashSet, + cutout: Option>, +} + +impl Pending { + /// Takes in the next job, with the same result as applying both in + /// turn: newer meshes replace waiting ones, tiles meshed again are not + /// removed, and tiles removed now drop their waiting meshes. + fn add( + &mut self, + meshes: Vec<(TileKey, SectionMesh)>, + removed: Vec, + cutout: Option>, + ) { + for (key, mesh) in meshes { + self.removed.remove(&key); + self.meshes.insert(key, mesh); + } + for key in removed { + self.meshes.remove(&key); + self.removed.insert(key); + } + if cutout.is_some() { + self.cutout = cutout; + } + } +} pub(super) struct Tile { pub mesh: SectionGpu, @@ -101,9 +139,67 @@ impl Renderer { } pub fn clear_lods(&mut self) { + self.lod_pending = None; for (_, tile) in std::mem::take(&mut self.lods) { self.release_mesh(tile.mesh); } + self.set_lod_cutout(Default::default()); + } + + /// Queues a finished mesh job (`Lod::update`, `Lod::removed`, + /// `Lod::take_cutout`) for `upload_lods`, joining one still uploading + /// (`Pending::add`). + pub fn queue_lods( + &mut self, + meshes: Vec<(TileKey, SectionMesh)>, + removed: Vec, + cutout: Option>, + ) { + if meshes.is_empty() && removed.is_empty() && cutout.is_none() { + return; + } + self.lod_pending + .get_or_insert_default() + .add(meshes, removed, cutout); + } + + /// Uploads queued tile meshes for about `budget` (at least one), then, + /// once all are in, retires the tiles they replace. + pub fn upload_lods(&mut self, budget: Duration) { + let start = Instant::now(); + while let Some(pending) = &mut self.lod_pending { + let Some(&key) = pending.meshes.keys().next() else { + let pending = self.lod_pending.take().expect("pending tiles"); + for key in pending.removed { + self.remove_lod(key); + } + if let Some(cutout) = pending.cutout { + self.set_lod_cutout(cutout); + } + return; + }; + let mesh = pending.meshes.remove(&key).expect("pending tile"); + self.upload_lod(key, &mesh); + if start.elapsed() >= budget { + return; + } + } + } + + /// The chunk columns the resident tiles now leave out (`Lod::take_cutout`). + /// Removed sections they no longer leave out are released. + pub fn set_lod_cutout(&mut self, cutout: crate::fast_hash::FxHashSet<(i32, i32)>) { + self.lod_cutout = cutout; + let released: Vec<_> = self + .lod_retiring + .iter() + .copied() + .filter(|key| !self.lod_cutout.contains(&(key.0, key.2))) + .collect(); + for key in released { + self.lod_retiring.remove(&key); + self.release_section(key); + } } } @@ -112,6 +208,29 @@ mod tests { use super::*; use crate::mesher::TerrainVertex; + #[test] + fn joined_jobs_apply_as_if_in_turn() { + let key = |x| TileKey { x, z: 0, level: 0 }; + let mut pending = Pending::default(); + // The first job meshes 1 and 2 and retires 3 and 4. + pending.add( + vec![ + (key(1), SectionMesh::default()), + (key(2), SectionMesh::default()), + ], + vec![key(3), key(4)], + Some([(0, 0)].into_iter().collect()), + ); + // The second meshes 3 again and retires 2. + pending.add(vec![(key(3), SectionMesh::default())], vec![key(2)], None); + let mut meshes: Vec<_> = pending.meshes.keys().map(|k| k.x).collect(); + meshes.sort_unstable(); + let mut removed: Vec<_> = pending.removed.iter().map(|k| k.x).collect(); + removed.sort_unstable(); + assert_eq!((meshes, removed), (vec![1, 3], vec![2, 4])); + assert!(pending.cutout.is_some_and(|c| c.contains(&(0, 0)))); + } + #[test] fn large_tile_bounds_include_water_and_do_not_cull_by_origin() { let vertex = |pos| TerrainVertex::tiled(pos, [0.0; 2], 0, 0, 0); diff --git a/crates/horizon-client/src/gfx/panorama.rs b/crates/horizon-client/src/gfx/panorama.rs index d53cd4501..1c17e0bff 100644 --- a/crates/horizon-client/src/gfx/panorama.rs +++ b/crates/horizon-client/src/gfx/panorama.rs @@ -230,6 +230,21 @@ impl Panorama { } } +/// `PanoramaRenderer`: accumulate rotation so changing speed does not jump +/// back to a different point on the cube. `now` is monotonic seconds. +#[derive(Clone, Copy, Debug, Default)] +pub struct Rotation { + last: f32, + yaw: f32, +} +impl Rotation { + pub fn update(&mut self, now: f32, speed: f32) -> f32 { + self.yaw = (self.yaw - (now - self.last).max(0.0) * 2.0 * speed) % 360.0; + self.last = now; + self.yaw + } +} + #[cfg(test)] mod tests { use super::*; @@ -282,6 +297,15 @@ mod tests { } } + #[test] + fn rotation_speed_changes_preserve_position() { + let mut rotation = Rotation::default(); + assert_eq!(rotation.update(5.0, 1.0), -10.0); + assert_eq!(rotation.update(10.0, 0.0), -10.0); + assert_eq!(rotation.update(12.0, 0.5), -12.0); + assert_eq!(rotation.update(13.0, 1.0), -14.0); + } + #[test] fn original_resolution_texels_and_vanilla_cube_orientation_are_preserved() { let f = Fixture::new(1024); diff --git a/crates/horizon-client/src/gfx/resident.rs b/crates/horizon-client/src/gfx/resident.rs index b7455b765..49407e77a 100644 --- a/crates/horizon-client/src/gfx/resident.rs +++ b/crates/horizon-client/src/gfx/resident.rs @@ -163,11 +163,17 @@ fn camera_column(camera: DVec3) -> (i32, i32) { /// Whether the section at `key` is drawn: its column within the render /// distance of the camera's (`SectionOcclusionGraph.isInViewDistance`), and /// partly inside the frustum. `None` when it is not, else its squared centre -/// distance and origin. +/// distance and origin. `Resident::visible` walks columns instead. +#[cfg(test)] fn in_view(key: SectionKey, camera: DVec3, radius: i32, frustum: &Frustum) -> Option<(f64, Vec3)> { if !in_view_distance(camera_column(camera), radius, key.0, key.2) { return None; } + in_frustum(key, camera, frustum) +} + +/// `in_view` without the distance test. +fn in_frustum(key: SectionKey, camera: DVec3, frustum: &Frustum) -> Option<(f64, Vec3)> { let origin = origin(key, camera); let min = origin.as_vec3(); if !frustum.intersects(min, min + Vec3::splat(16.0)) { @@ -178,7 +184,10 @@ fn in_view(key: SectionKey, camera: DVec3, radius: i32, frustum: &Frustum) -> Op impl Resident { /// Appends the sections `in_view` and `reachable` to `out`, nearest - /// first (ties by key, so the order never depends on storage). + /// first (ties by key, so the order never depends on storage), and the + /// sections in the frustum of columns past the render distance that + /// `beyond` keeps (distant terrain still leaves them out; the occlusion + /// graph never reaches them). /// /// Columns are tested first, with the same distance test (it depends /// only on x and z) and a box spanning their sections: every section box @@ -191,11 +200,13 @@ impl Resident { radius: i32, frustum: &Frustum, reachable: impl Fn(SectionKey) -> bool, + beyond: impl Fn(i32, i32) -> bool, out: &mut Vec, ) { let from = camera_column(camera); for column in &self.columns { - if !in_view_distance(from, radius, column.x, column.z) { + let near = in_view_distance(from, radius, column.x, column.z); + if !near && !beyond(column.x, column.z) { continue; } let min = origin((column.x, column.low, column.z), camera).as_vec3(); @@ -205,10 +216,10 @@ impl Resident { } for &(y, slot) in &column.sections { let key = (column.x, y, column.z); - if !reachable(key) { + if near && !reachable(key) { continue; } - if let Some((d, o)) = in_view(key, camera, radius, frustum) { + if let Some((d, o)) = in_frustum(key, camera, frustum) { out.push(Visible { distance: d.to_bits(), key, @@ -255,13 +266,22 @@ mod tests { planes: super::super::frustum(projection * view), }; let mut fast = Vec::new(); - r.visible(camera, radius, &frustum, reachable, &mut fast); + // Columns past the distance kept for distant terrain. + let beyond = |x: i32, z: i32| (x + z).rem_euclid(3) == 0; + r.visible(camera, radius, &frustum, reachable, beyond, &mut fast); let mut slow: Vec<(SectionKey, f64, [f32; 3])> = r .items .iter() - .filter(|(k, _)| reachable(*k)) - .filter_map(|(k, _)| { - in_view(*k, camera, radius, &frustum).map(|(d, o)| (*k, d, o.to_array())) + .filter_map(|&(k, _)| { + let near = in_view_distance(camera_column(camera), radius, k.0, k.2); + if near { + in_view(k, camera, radius, &frustum).filter(|_| reachable(k)) + } else if beyond(k.0, k.2) { + in_frustum(k, camera, &frustum) + } else { + None + } + .map(|(d, o)| (k, d, o.to_array())) }) .collect(); slow.sort_unstable_by(|a, b| a.1.total_cmp(&b.1).then(a.0.cmp(&b.0))); @@ -370,7 +390,7 @@ mod tests { old = old.min(t.elapsed()); let t = Instant::now(); list.clear(); - r.visible(camera, 32, &frustum, |_| true, &mut list); + r.visible(camera, 32, &frustum, |_| true, |_, _| false, &mut list); for v in &list { sum += i64::from(r.get(v.slot)[1] + r.get(v.slot)[0]); } diff --git a/crates/horizon-client/src/graphics.rs b/crates/horizon-client/src/graphics.rs index e3ce8fe6e..bea0ffaa9 100644 --- a/crates/horizon-client/src/graphics.rs +++ b/crates/horizon-client/src/graphics.rs @@ -156,6 +156,26 @@ pub enum Overlay { Graph, } +/// The farthest LOD Distance, in chunks, on integrated GPUs other than +/// Apple's: they share the CPU's memory bandwidth, and past it far terrain +/// costs them more frame time than it is worth. +pub const INTEGRATED_LOD_DISTANCE: u32 = 128; +/// Whether `INTEGRATED_LOD_DISTANCE` applies to this adapter. Apple's GPUs +/// are integrated too, with memory and bandwidth enough for every distance. +pub fn lod_capped(info: &wgpu::AdapterInfo) -> bool { + info.device_type == wgpu::DeviceType::IntegratedGpu && !info.name.starts_with("Apple") +} +impl Graphics { + /// `lod_distance` as far terrain uses it on this adapter. + pub fn lod_distance_on(&self, info: &wgpu::AdapterInfo) -> u32 { + let distance = self.lod_distance.min(1024); + if lod_capped(info) { + distance.min(INTEGRATED_LOD_DISTANCE) + } else { + distance + } + } +} #[derive(Clone, Debug, PartialEq)] pub struct Graphics { pub preset: Preset, @@ -418,6 +438,46 @@ mod tests { ); } + #[test] + fn integrated_gpus_other_than_apple_cap_the_lod_distance() { + let adapter = |name: &str, device_type| wgpu::AdapterInfo { + name: name.into(), + vendor: 0, + device: 0, + device_type, + device_pci_bus_id: String::new(), + driver: String::new(), + driver_info: String::new(), + backend: wgpu::Backend::Vulkan, + subgroup_min_size: 0, + subgroup_max_size: 0, + transient_saves_memory: None, + limit_bucket: None, + }; + let hd620 = adapter( + "Intel(R) HD Graphics 620 (KBL GT2)", + wgpu::DeviceType::IntegratedGpu, + ); + let m4 = adapter("Apple M4 Pro", wgpu::DeviceType::IntegratedGpu); + let discrete = adapter("NVIDIA GeForce RTX 4070", wgpu::DeviceType::DiscreteGpu); + for (distance, capped) in [(0, 0), (64, 64), (128, 128), (256, 128), (1024, 128)] { + let g = Graphics { + lod_distance: distance, + ..Graphics::default() + }; + assert_eq!(g.lod_distance_on(&hd620), capped); + assert_eq!(g.lod_distance_on(&m4), distance); + assert_eq!(g.lod_distance_on(&discrete), distance); + } + assert!( + crate::graphics_ui::rows(crate::graphics_ui::Level::Simple) + .iter() + .any(|row| matches!(row, crate::graphics_ui::Row::Setting(s) + if s.text.contains(&format!("{INTEGRATED_LOD_DISTANCE} chunks")))), + "the LOD Distance description names the cap" + ); + } + #[test] fn lod_distance_is_opt_in_and_bounded() { assert_eq!(Graphics::default().lod_distance, 0); diff --git a/crates/horizon-client/src/graphics_ui.rs b/crates/horizon-client/src/graphics_ui.rs index 1b9b1cec6..ea126c785 100644 --- a/crates/horizon-client/src/graphics_ui.rs +++ b/crates/horizon-client/src/graphics_ui.rs @@ -83,7 +83,7 @@ pub fn rows(level: Level) -> Vec { let lod = h( H::LodDistance, Medium, - "Coarse distant surface in local worlds; no extra simulation.", + "Coarse distant terrain in local worlds. Integrated GPUs stop at 128 chunks.", ); let fov = v( Opt::Fov, diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs index 7c80a87ac..3f26cf467 100644 --- a/crates/horizon-client/src/hud_overlays.rs +++ b/crates/horizon-client/src/hud_overlays.rs @@ -606,19 +606,22 @@ pub fn sidebar( .then_with(|| compare_ignore_case(&a.owner, &b.owner)) }); entries.truncate(15); + // Font draws each literal through StringDecomposer.iterateFormatted: + // legacy `§` codes style what follows and are not drawn. let rows: Vec<(Text, Text, i32)> = entries .iter() .map(|e| { let name = match board.players_team(&e.owner) { Some(team) => team.formatted_name(e.owner_name()), None => e.owner_name(), - }; - let score = e.format_value(&format); + } + .resolve_legacy(); + let score = e.format_value(&format).resolve_legacy(); let score_width = width(font, &score); (name, score, score_width) }) .collect(); - let title = objective.display_text(); + let title = objective.display_text().resolve_legacy(); let title_width = width(font, &title); let spacer = font.width(": ") as i32; let mut biggest = title_width; diff --git a/crates/horizon-client/src/hunger.rs b/crates/horizon-client/src/hunger.rs index fa1b62a5e..2f97ea293 100644 --- a/crates/horizon-client/src/hunger.rs +++ b/crates/horizon-client/src/hunger.rs @@ -14,6 +14,14 @@ use horizon_world::{ }; impl PlayerMotion { + /// Player.causeFoodExhaustion: creative and spectator abilities suppress + /// exhaustion from movement, attacks and effects. + pub fn cause_food_exhaustion(&mut self, amount: f32) { + if !self.invulnerable && !self.spectator { + self.health.food.add_exhaustion(amount); + } + } + /// ServerPlayer.tickRegeneration, dispatched from Player.aiStep before /// inventory and living movement. The separately invoked food tick follows /// movement in ServerPlayer.doTick. @@ -51,6 +59,7 @@ impl PlayerMotion { let mut world = TickWorld { resources, rules, + invulnerable: self.invulnerable || self.spectator, attributes: &mut self.attributes, data: &mut h.data, ids: h.ids, @@ -67,6 +76,7 @@ impl PlayerMotion { struct TickWorld<'a> { resources: &'a HealthResources, rules: HealthRules, + invulnerable: bool, attributes: &'a mut Attributes, data: &'a mut SyncedFloats, ids: PlayerFloatIds, @@ -118,6 +128,11 @@ impl FoodWorld for TickWorld<'_> { .expect("validated health field")) } fn hurt_starvation(&mut self, _: (), food: &mut FoodData, amount: f32) -> Result<()> { + // FoodData still ticks after a mode switch with an empty food bar, but + // Player.hurtServer rejects starvation for invulnerable abilities. + if self.invulnerable { + return Ok(()); + } let id = self .resources .damage diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 7f2782c72..edf094d39 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -1705,7 +1705,15 @@ mod tests { } } -pub fn take_held_drop(slot: &mut Option, all: bool) -> Option { +/// Minecraft.handleKeybinds: spectators cannot drop from the selected slot. +pub fn take_held_drop( + slot: &mut Option, + all: bool, + spectator: bool, +) -> Option { + if spectator { + return None; + } let stack = slot.as_mut()?; if stack.count == 0 { return None; @@ -1727,10 +1735,23 @@ mod held_drop_tests { #[test] fn one_all_and_empty_drop() { let mut slot = Some(ItemStack::new("minecraft:stone", 4)); - assert_eq!(take_held_drop(&mut slot, false).unwrap().count, 1); + assert_eq!(take_held_drop(&mut slot, false, false).unwrap().count, 1); assert_eq!(slot.as_ref().unwrap().count, 3); - assert_eq!(take_held_drop(&mut slot, true).unwrap().count, 3); + assert_eq!(take_held_drop(&mut slot, true, false).unwrap().count, 3); assert!(slot.is_none()); - assert!(take_held_drop(&mut slot, false).is_none()); + assert!(take_held_drop(&mut slot, false, false).is_none()); + } + #[test] + fn spectator_keeps_selected_stack_for_single_and_whole_stack_drops() { + for all in [false, true] { + let mut slot = Some(ItemStack::new("minecraft:stone", 4)); + assert!(take_held_drop(&mut slot, all, true).is_none()); + assert_eq!(slot.as_ref().unwrap().count, 4); + // Leaving spectator allows dropping the same selected stack again. + assert_eq!( + take_held_drop(&mut slot, all, false).unwrap().count, + if all { 4 } else { 1 } + ); + } } } diff --git a/crates/horizon-client/src/java_pack.rs b/crates/horizon-client/src/java_pack.rs index f051cf2b6..fb170d152 100644 --- a/crates/horizon-client/src/java_pack.rs +++ b/crates/horizon-client/src/java_pack.rs @@ -6,8 +6,10 @@ //! `shadow`) don't run yet: the world is drawn by Horizon. use horizon_shaderpack::{ JavaPack, - pipeline::{Program, TargetSettings}, + pipeline::{Directives, Program, TargetSettings}, preprocess::Environment, + properties::SkyDirectives, + uniforms::CustomUniforms, }; use std::{ collections::{BTreeMap, BTreeSet}, @@ -28,11 +30,17 @@ pub struct JavaFolder { pub final_pass: Option, /// The targets whose alternate side holds the frame's last write. pub flipped_at_end: BTreeSet, + /// `sunPathRotation` and `eyeBrightnessHalflife`. + pub directives: Directives, } /// A loaded Java pack. pub struct JavaPasses { pub folders: Vec, + /// `uniform.*` / `variable.*` from `shaders.properties`. + pub uniforms: CustomUniforms, + /// What the pack keeps of the vanilla sky (`clouds`, `sun`, `moon`). + pub sky: SkyDirectives, } impl JavaPasses { @@ -122,12 +130,21 @@ pub fn load( flipped_after_prepare: plan.flipped_after_prepare, final_pass, flipped_at_end: plan.flipped_at_end, + directives: plan.directives, }); } if folders.is_empty() { return Err("no deferred, composite or final programs".into()); } - Ok(JavaPasses { folders }) + let uniforms = properties.custom_uniforms(); + for problem in &uniforms.problems { + log::warn!("Horizon: shader pack custom uniform {problem}"); + } + Ok(JavaPasses { + folders, + uniforms, + sky: properties.sky(), + }) } #[cfg(test)] diff --git a/crates/horizon-client/src/lod.rs b/crates/horizon-client/src/lod.rs index c2e69a291..0e1ed89ca 100644 --- a/crates/horizon-client/src/lod.rs +++ b/crates/horizon-client/src/lod.rs @@ -22,6 +22,12 @@ use std::{ const CELLS: usize = 16; const MAX_SAVED: usize = 1024; const SAMPLE_JOBS: usize = 4; +/// While the near terrain loads on a machine with four threads or fewer, far +/// terrain starts one sample job at most this often and no detail: it would +/// otherwise take the cores the near chunks and the frame need. +const HELD_SAMPLE_STEP: std::time::Duration = std::time::Duration::from_millis(500); +/// The coarsest tile level: `Plan` roots cover at most 1024 chunks around. +const MAX_LEVEL: u8 = 10; /// Top solid face and optional fluid face, in absolute block coordinates. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Surface { @@ -142,7 +148,9 @@ impl Column { self.spans.push(span); } } - fn from_chunk(chunk: &Chunk, facts: &BlockFacts, x: i32, z: i32) -> Self { + /// `kinds`: `state_kinds`, per block state. + fn from_chunk(chunk: &Chunk, kinds: &[u8], x: i32, z: i32) -> Self { + let kind = |state: BlockStateId| kinds.get(state.0 as usize).copied().unwrap_or(0); let face_light = |y: i32| { let mut sky = 0; let mut block = 0; @@ -177,13 +185,8 @@ impl Column { for offset in (0..16).step_by(step) { let y = min + offset; let state = BlockStateId(chunk.get(x, y, z)); - let f = facts.get(state); - if facts.is_air(state) - || !(f.solid_render - || f.full_collision - || f.name.ends_with("_leaves") - || matches!(&*f.name, "minecraft:water" | "minecraft:lava")) - { + let kind = kind(state); + if kind & KEPT == 0 { continue; } let light = face_light(y); @@ -192,17 +195,13 @@ impl Column { max: (y + step as i32) as i16, state, biome: chunk.biome(x, y, z), - light: u16::from(light & 0xf0) - | (u16::from((light & 15).max(f.emission)) << 12), + light: u16::from(light & 0xf0) | (u16::from((light & 15).max(kind >> 4)) << 12), }); } } let mut water = None; for span in column.spans.iter().rev() { - if matches!( - &*facts.get(span.state).name, - "minecraft:water" | "minecraft:lava" - ) { + if kind(span.state) & FLUID != 0 { water.get_or_insert((i32::from(span.max), span.state)); } else { column.surface = Some(Surface { @@ -219,7 +218,9 @@ impl Column { { column.surface = Some(Surface { height: MIN_Y, - state: facts.air, + state: BlockStateId( + kinds.iter().position(|&kind| kind & AIR != 0).unwrap_or(0) as u32 + ), water: Some((height, state)), biome: chunk.biome(x, height - 1, z), }); @@ -227,6 +228,28 @@ impl Column { column } } +/// `state_kinds` bits: kept in columns, a fluid, the air state; the light +/// emission is in the high nibble. +const KEPT: u8 = 1; +const FLUID: u8 = 2; +const AIR: u8 = 4; +/// What `Column::from_chunk` needs of each block state, read from the facts +/// once: matching their names for every block made observing a chunk slow. +fn state_kinds(facts: &BlockFacts) -> Vec { + (0..facts.states.len()) + .map(|i| { + let state = BlockStateId(i as u32); + let f = facts.get(state); + let fluid = matches!(&*f.name, "minecraft:water" | "minecraft:lava"); + let kept = !facts.is_air(state) + && (f.solid_render || f.full_collision || f.name.ends_with("_leaves") || fluid); + (u8::from(kept) * KEPT) + | (u8::from(fluid) * FLUID) + | (u8::from(state == facts.air) * AIR) + | (f.emission.min(15) << 4) + }) + .collect() +} #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TileKey { pub x: i32, @@ -240,6 +263,13 @@ impl TileKey { pub fn origin(self) -> [i32; 3] { [self.x * self.size(), 0, self.z * self.size()] } + fn parent(self) -> Self { + Self { + x: self.x.div_euclid(2), + z: self.z.div_euclid(2), + level: self.level + 1, + } + } fn children(self) -> [Self; 4] { std::array::from_fn(|i| Self { x: self.x * 2 + (i & 1) as i32, @@ -335,7 +365,7 @@ impl Plan { fn select( &self, key: TileKey, - ready: &FxHashMap>, + ready: &FxHashMap, out: &mut Vec, ) -> bool { if !self.nodes.contains(&key) { @@ -365,9 +395,26 @@ impl Plan { } } } +/// A mesh job whose inputs are being gathered, a few each frame +/// (`INPUT_BUDGET`): gathering hundreds at once stalled the frame. +struct Gathering { + active: FxHashSet, + /// The active tiles' samples when the job began: a replan may drop them + /// from `ready` before the job is sent. + samples: FxHashMap>>, + keys: Vec, + finer: FxHashMap>, + inputs: Vec, + covered: FxHashSet<(i32, i32)>, + bounds: Option<[i32; 4]>, +} +/// How long one frame may spend gathering mesh inputs (at least one). +const INPUT_BUDGET: std::time::Duration = std::time::Duration::from_millis(2); struct MeshInput { key: TileKey, - columns: Vec, + /// The tile's samples, with `visited` replacing some of them (`columns`). + samples: Arc>, + visited: Vec<(usize, Column)>, neighbors: [Vec; 4], finer: Vec, } @@ -375,6 +422,17 @@ struct ReducedColumns { columns: Arc<[Column; 256]>, levels: [Vec; 4], } +impl MeshInput { + /// Built on the worker: cloning every tile's samples on the render + /// thread stalled it for tens of milliseconds after a move. + fn columns(&self) -> Vec { + let mut columns = (*self.samples).clone(); + for (index, column) in &self.visited { + columns[*index] = column.clone(); + } + columns + } +} impl ReducedColumns { fn new(columns: Arc<[Column; 256]>) -> Self { let levels = std::array::from_fn(|level| { @@ -422,6 +480,7 @@ enum Done { Mesh { active: FxHashSet, meshes: Vec<(TileKey, SectionMesh)>, + covered: FxHashSet<(i32, i32)>, }, } struct Shared { @@ -438,6 +497,12 @@ pub struct Lod { #[cfg(test)] context: Arc, meshing: bool, + /// The next mesh job, while its inputs are gathered (`meshing` is set). + gathering: Option, + /// Something `select` reads changed since it last ran. + reselect: bool, + /// The plan or the covered columns changed: covered leaves need stand-ins. + replanned: bool, invalidated: FxHashSet<(i32, i32)>, area: Option<([i32; 2], i32, u32, i32)>, plan: Plan, @@ -446,12 +511,24 @@ pub struct Lod { detail_masks: FxHashMap, detail_request_pending: bool, detail_request_at: std::time::Instant, - ready: FxHashMap>, + /// Four threads or fewer: far work waits for the near terrain (`hold`). + small: bool, + /// The near terrain is loading (`set_near_loading`). + near_loading: bool, + /// When `request_samples` last started a job while held. + held_sample_at: std::time::Instant, + /// `state_kinds`, from the first observed chunk's facts. + kinds: Option>, + /// Each tile's samples, shared with mesh jobs in flight. + ready: FxHashMap>>, active: FxHashSet, dirty: FxHashSet, removed: Vec, covered: FxHashSet<(i32, i32)>, covered_bounds: Option<[i32; 4]>, + /// The covered columns the active meshes leave out, when a mesh job + /// has finished since the last `take_cutout`. + cutout: Option>, saved: FxHashMap<(i32, i32), Arc<[Column; 256]>>, reduced: FxHashMap<(i32, i32), ReducedColumns>, saved_order: VecDeque<(i32, i32)>, @@ -579,7 +656,7 @@ impl Lod { } let mesh = mesher.mesh( input.key, - &input.columns, + &input.columns(), &covered, bounds, &mesh_context, @@ -588,7 +665,11 @@ impl Lod { ); meshes.push((input.key, mesh)); } - Done::Mesh { active, meshes } + Done::Mesh { + active, + meshes, + covered, + } } }; if tx.send(done).is_err() { @@ -609,6 +690,9 @@ impl Lod { #[cfg(test)] context, meshing: false, + gathering: None, + reselect: true, + replanned: true, invalidated: FxHashSet::default(), area: None, plan: Plan::default(), @@ -617,12 +701,17 @@ impl Lod { detail_masks: FxHashMap::default(), detail_request_pending: false, detail_request_at: std::time::Instant::now(), + small: thread::available_parallelism().map_or(1, |n| n.get()) <= 4, + near_loading: false, + held_sample_at: std::time::Instant::now(), + kinds: None, ready: FxHashMap::default(), active: FxHashSet::default(), dirty: FxHashSet::default(), removed: Vec::new(), covered: FxHashSet::default(), covered_bounds: None, + cutout: None, saved: FxHashMap::default(), reduced: FxHashMap::default(), saved_order: VecDeque::new(), @@ -653,25 +742,45 @@ impl Lod { pub fn removed(&mut self) -> Vec { std::mem::take(&mut self.removed) } + /// The full-detail columns the active meshes leave out, once per finished + /// mesh job. Until a column leaves this set, nothing distant stands in for + /// it: its full-detail terrain must still be drawn, in or past the render + /// distance, or a hole opens there. + pub fn take_cutout(&mut self) -> Option> { + self.cutout.take() + } pub fn invalidate_chunk(&mut self, x: i32, z: i32) { if self.meshing { self.invalidated.insert((x, z)); } - for &key in &self.active { - let [ox, _, oz] = key.origin(); - if x * 16 <= ox + key.size() - && (x + 1) * 16 >= ox - && z * 16 <= oz + key.size() - && (z + 1) * 16 >= oz - { - self.dirty.insert(key); + // The tiles touching the chunk: a few per level, not every active one. + for level in 0..=MAX_LEVEL { + let size = 16 << level; + for kz in (z * 16).div_euclid(size) - 1..=((z + 1) * 16).div_euclid(size) { + for kx in (x * 16).div_euclid(size) - 1..=((x + 1) * 16).div_euclid(size) { + let key = TileKey { + x: kx, + z: kz, + level, + }; + let [ox, _, oz] = key.origin(); + if x * 16 <= ox + size + && (x + 1) * 16 >= ox + && z * 16 <= oz + size + && (z + 1) * 16 >= oz + && self.active.contains(&key) + { + self.dirty.insert(key); + } + } } } } /// Capture actual block columns, including canopy gaps and material layers. pub fn observe(&mut self, chunk: &Chunk, facts: &BlockFacts) { + let kinds = self.kinds.get_or_insert_with(|| state_kinds(facts)); let values = Arc::new(std::array::from_fn(|i| { - Column::from_chunk(chunk, facts, (i & 15) as i32, (i >> 4) as i32) + Column::from_chunk(chunk, kinds, (i & 15) as i32, (i >> 4) as i32) })); let key = (chunk.x, chunk.z); if self.saved.get(&key) == Some(&values) { @@ -704,7 +813,8 @@ impl Lod { level: 0, }; if self.plan.nodes.contains(&fine) || self.ready.contains_key(&fine) { - self.ready.insert(fine, columns.to_vec()); + self.ready.insert(fine, Arc::new(columns.to_vec())); + self.reselect = true; self.detail_masks.insert(fine, [u64::MAX; 4]); } } @@ -732,6 +842,7 @@ impl Lod { if x0 == x1 || z0 == z1 { continue; } + let samples = Arc::make_mut(samples); let mask = self.detail_masks.entry(key).or_default(); for z in z0..z1 { for x in x0..x1 { @@ -759,7 +870,8 @@ impl Lod { } } } - self.ready.insert(key, samples); + self.ready.insert(key, Arc::new(samples)); + self.reselect = true; } } fn finish_detail(&mut self, key: (i32, i32), columns: ReducedColumns) { @@ -776,8 +888,17 @@ impl Lod { } self.invalidate_chunk(key.0, key.1); } + /// Whether the near terrain is still loading: on small machines far + /// terrain then holds back (`HELD_SAMPLE_STEP`). + pub fn set_near_loading(&mut self, loading: bool) { + self.near_loading = loading; + } + fn held(&self) -> bool { + self.small && self.near_loading + } fn request_detail(&mut self, camera: [i32; 2]) { - if self.detail_request_pending + if self.held() + || self.detail_request_pending || self.detail_request_at.elapsed() < std::time::Duration::from_millis(250) { return; @@ -843,7 +964,7 @@ impl Lod { yaw: f32, detail: i32, distance: u32, - covered: FxHashSet<(i32, i32)>, + covered: Option>, ) -> Vec<(TileKey, SectionMesh)> { let elevation = (((camera[1] - f64::from(MIN_Y + crate::chunk::HEIGHT)).clamp(0., 16384.)) as i32 / 32) @@ -865,13 +986,32 @@ impl Lod { elevation, ); if self.area != Some(area) { - self.area = Some(area); - self.plan = Plan::with_previous(camera, detail, distance, &self.plan, elevation); - self.ready.retain(|key, _| self.plan.nodes.contains(key)); - self.detail_masks - .retain(|key, _| self.plan.nodes.contains(key)); + crate::spans::time("lod_plan", || { + self.area = Some(area); + self.plan = Plan::with_previous(camera, detail, distance, &self.plan, elevation); + self.ready.retain(|key, _| self.plan.nodes.contains(key)); + self.detail_masks + .retain(|key, _| self.plan.nodes.contains(key)); + self.replanned = true; + self.reselect = true; + }); } let mut meshes = Vec::new(); + crate::spans::time("lod_results", || self.receive(&mut meshes)); + crate::spans::time("lod_covered", || self.cover(covered)); + if !self.meshing { + crate::spans::time("lod_select", || self.select()); + } + if self.gathering.is_some() { + crate::spans::time("lod_input", || self.gather(INPUT_BUDGET)); + } + crate::spans::time("lod_request", || self.request_detail(focus)); + crate::spans::time("lod_wanted", || { + self.request_samples(camera, focus, yaw, detail, elevation) + }); + meshes + } + fn receive(&mut self, meshes: &mut Vec<(TileKey, SectionMesh)>) { while let Ok(done) = self.results.try_recv() { match done { Done::Detail(key, columns) => { @@ -882,12 +1022,15 @@ impl Lod { Done::Mesh { active, meshes: completed, + covered, } => { + self.cutout = Some(covered); // Retire parents only when the entire replacement is ready. self.removed .extend(self.active.difference(&active).copied()); self.active = active; self.meshing = false; + self.reselect = true; for (x, z) in std::mem::take(&mut self.invalidated) { self.invalidate_chunk(x, z); } @@ -895,7 +1038,12 @@ impl Lod { } } } - if self.covered != covered { + } + /// Takes the new full-detail columns, when they changed (`None`: not). + fn cover(&mut self, covered: Option>) { + if let Some(covered) = covered + && self.covered != covered + { let changes: Vec<_> = self .covered .symmetric_difference(&covered) @@ -916,17 +1064,28 @@ impl Lod { }) }); self.covered = covered; + self.replanned = true; + self.reselect = true; } // Complete resident columns need no duplicate noise work. Their real // summaries are retained when the full-detail chunks leave the view. - for &key in &self.plan.nodes { - if key.level == 0 && self.covered.contains(&(key.x, key.z)) { - self.ready - .entry(key) - .or_insert_with(|| vec![Column::default(); CELLS * CELLS]); + if std::mem::take(&mut self.replanned) { + for &key in &self.plan.nodes { + if key.level == 0 && self.covered.contains(&(key.x, key.z)) { + self.ready + .entry(key) + .or_insert_with(|| Arc::new(vec![Column::default(); CELLS * CELLS])); + } } } - if !self.meshing { + } + /// Chooses the tiles to draw and meshes those that changed, when the + /// plan, the samples, the covered columns or the active tiles changed. + fn select(&mut self) { + if !std::mem::take(&mut self.reselect) && self.dirty.is_empty() { + return; + } + { let mut selected = Vec::new(); for &key in &self.plan.roots { self.plan.select(key, &self.ready, &mut selected); @@ -952,27 +1111,77 @@ impl Lod { self.dirty.extend(next.difference(&self.active).copied()); self.dirty.retain(|key| next.contains(key)); if !self.dirty.is_empty() || next != self.active { - let inputs = self - .dirty + let finer = Self::finer(&next, &self.dirty); + let samples = next .iter() - .map(|&key| crate::spans::time("lod_input", || self.mesh_input(key, &next))) + .filter_map(|key| Some((*key, self.ready.get(key)?.clone()))) .collect(); - self.dirty.clear(); + let keys: Vec<_> = self.dirty.drain().collect(); self.meshing = true; - self.shared.jobs.lock().unwrap().push_front(Job::Mesh { + self.gathering = Some(Gathering { active: next, - inputs, + samples, + inputs: Vec::with_capacity(keys.len()), + keys, + finer, covered: self.covered.clone(), bounds: self.covered_bounds, }); - self.shared.wake.notify_all(); } } - self.request_detail(focus); + } + /// Gathers mesh inputs for about `budget`, then sends the job once all + /// are in. + fn gather(&mut self, budget: std::time::Duration) { + let Some(mut gathering) = self.gathering.take() else { + return; + }; + let start = std::time::Instant::now(); + while let Some(key) = gathering.keys.pop() { + let finer = gathering.finer.remove(&key).unwrap_or_default(); + gathering.inputs.push(self.mesh_input( + key, + &gathering.active, + &gathering.samples, + finer, + )); + if start.elapsed() >= budget { + break; + } + } + if !gathering.keys.is_empty() { + self.gathering = Some(gathering); + return; + } + self.shared.jobs.lock().unwrap().push_front(Job::Mesh { + active: gathering.active, + inputs: gathering.inputs, + covered: gathering.covered, + bounds: gathering.bounds, + }); + self.shared.wake.notify_all(); + } + fn request_samples( + &mut self, + camera: [i32; 2], + focus: [i32; 2], + yaw: f32, + detail: i32, + elevation: i32, + ) { // Every sample slot busy: no tile can be requested this frame. - let free = SAMPLE_JOBS.saturating_sub(self.pending.len()); + let free = if self.held() { + usize::from( + self.pending.is_empty() && self.held_sample_at.elapsed() >= HELD_SAMPLE_STEP, + ) + } else { + SAMPLE_JOBS.saturating_sub(self.pending.len()) + }; if free == 0 { - return meshes; + return; + } + if self.held() { + self.held_sample_at = std::time::Instant::now(); } // Load desired nearby leaves directly, alongside broad fallback coverage. // Waiting for every ancestor/sibling made full detail take minutes to appear. @@ -1053,7 +1262,6 @@ impl Lod { drop(jobs); self.shared.wake.notify_all(); } - meshes } fn visited_column(&self, wx: i32, wz: i32, width: i32) -> Option<&Column> { let key = (wx.div_euclid(16), wz.div_euclid(16)); @@ -1073,8 +1281,14 @@ impl Lod { None } } - fn neighbor(&self, wx: i32, wz: i32, active: &FxHashSet) -> Option<(Column, i32)> { - for level in 0..=10 { + fn neighbor( + &self, + wx: i32, + wz: i32, + active: &FxHashSet, + samples: &FxHashMap>>, + ) -> Option<(Column, i32)> { + for level in 0..=MAX_LEVEL { let size = 16 << level; let key = TileKey { x: wx.div_euclid(size), @@ -1092,19 +1306,27 @@ impl Lod { if let Some(column) = self.visited_column(sx, sz, stride) { return Some((column.clone(), stride)); } - return Some((self.ready[&key][(z * 16 + x) as usize].clone(), stride)); + return samples + .get(&key) + .map(|columns| (columns[(z * 16 + x) as usize].clone(), stride)); } None } - fn mesh_input(&self, key: TileKey, active: &FxHashSet) -> MeshInput { + fn mesh_input( + &self, + key: TileKey, + active: &FxHashSet, + samples: &FxHashMap>>, + finer: Vec, + ) -> MeshInput { let stride = key.size() / CELLS as i32; let [ox, _, oz] = key.origin(); - let mut columns = self.ready[&key].clone(); + let mut visited = Vec::new(); for z in 0..CELLS { for x in 0..CELLS { let (wx, wz) = (ox + x as i32 * stride, oz + z as i32 * stride); if let Some(column) = self.visited_column(wx, wz, stride) { - columns[z * CELLS + x] = column.clone(); + visited.push((z * CELLS + x, column.clone())); } } } @@ -1119,7 +1341,7 @@ impl Lod { _ => (ox + offset, oz + key.size()), }; let (column, neighbor_stride) = self - .neighbor(wx, wz, active) + .neighbor(wx, wz, active, samples) .unwrap_or_else(|| (Column::default(), stride)); let coordinate = if direction < 2 { wz } else { wx }; let width = (neighbor_stride - coordinate.rem_euclid(neighbor_stride)) @@ -1135,28 +1357,38 @@ impl Lod { }); MeshInput { key, - columns, + samples: samples[&key].clone(), + visited, neighbors, - finer: active - .iter() - .copied() - .filter(|other| { - let [x, _, z] = other.origin(); - other.level < key.level - && x >= ox - && z >= oz - && x + other.size() <= ox + key.size() - && z + other.size() <= oz + key.size() - }) - .collect(), + finer, } } + /// The active tiles inside each of `keys` (finer, so each a descendant). + fn finer( + active: &FxHashSet, + keys: &FxHashSet, + ) -> FxHashMap> { + let mut finer: FxHashMap> = FxHashMap::default(); + for &tile in active { + let mut parent = tile; + while parent.level < MAX_LEVEL { + parent = parent.parent(); + if keys.contains(&parent) { + finer.entry(parent).or_default().push(tile); + } + } + } + finer + } #[cfg(test)] fn mesh(&self, key: TileKey) -> SectionMesh { - let input = self.mesh_input(key, &self.active); + let finer = Self::finer(&self.active, &[key].into_iter().collect()) + .remove(&key) + .unwrap_or_default(); + let input = self.mesh_input(key, &self.active, &self.ready, finer); mesh::Mesher::default().mesh( key, - &input.columns, + &input.columns(), &self.covered, self.covered_bounds, &self.context, @@ -1184,6 +1416,7 @@ mod tests { for distance in [64, 256, 1024] { let plan = Plan::new(camera, 12, distance); assert!(plan.nodes.len() < 12000, "{} nodes", plan.nodes.len()); + assert!(plan.roots.iter().all(|key| key.level <= MAX_LEVEL)); for key in &plan.nodes { if !plan.split.contains(key) && key.distance(camera) < 12 * 16 { assert_eq!(key.level, 0); @@ -1241,7 +1474,7 @@ mod tests { plan.nodes.insert(parent); plan.split.insert(parent); plan.nodes.extend(parent.children()); - let mut ready = FxHashMap::default(); + let mut ready: FxHashMap> = FxHashMap::default(); ready.insert(parent, vec![]); ready.insert(parent.children()[0], vec![]); let mut selected = Vec::new(); @@ -1382,7 +1615,7 @@ mod tests { }; lod.ready.insert( key, - vec![ + Arc::new(vec![ Column::from_surface(Some(Surface { height: 70, state: stone, @@ -1390,7 +1623,7 @@ mod tests { biome: biomes.id("minecraft:plains"), })); CELLS * CELLS - ], + ]), ); // A chunk covers only one quarter of this parent's 32² cell. Both // opaque terrain and water must leave precisely that 16² footprint. @@ -1494,7 +1727,8 @@ mod tests { z: -1, level: 0, }; - lod.ready.insert(fine, vec![Column::default(); 256]); + lod.ready + .insert(fine, Arc::new(vec![Column::default(); 256])); lod.finish_detail( (-1, -1), ReducedColumns::new(Arc::new(std::array::from_fn(|_| Column::default()))), @@ -1553,10 +1787,12 @@ mod tests { lod.area = Some(([-16, -16], 2, 64, 0)); lod.plan.roots = vec![key]; lod.plan.nodes.insert(key); + // As a replan does (`update` only selects after a change). + lod.reselect = true; let await_meshes = |lod: &mut Lod| { let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); loop { - let meshes = lod.update(camera, 0.0, 2, 64, lod.covered.clone()); + let meshes = lod.update(camera, 0.0, 2, 64, None); if !meshes.is_empty() { return meshes; } @@ -1573,10 +1809,8 @@ mod tests { lod.plan.nodes.insert(child); lod.ready.insert(child, lod.ready[&key].clone()); } - assert!( - lod.update(camera, 0.0, 2, 64, lod.covered.clone()) - .is_empty() - ); + lod.reselect = true; + assert!(lod.update(camera, 0.0, 2, 64, None).is_empty()); assert!( lod.active.contains(&key), "parent retired before child meshes" @@ -1599,11 +1833,14 @@ mod tests { lod.plan = Plan::default(); lod.plan.roots.push(covered_fine); lod.plan.nodes.insert(covered_fine); - lod.ready.insert(covered_fine, vec![Column::default(); 256]); + lod.ready + .insert(covered_fine, Arc::new(vec![Column::default(); 256])); lod.covered.insert((-1, -2)); + lod.reselect = true; + lod.replanned = true; let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); loop { - lod.update(camera, 0., 2, 64, lod.covered.clone()); + lod.update(camera, 0., 2, 64, None); if !lod.meshing && lod.active.is_empty() { break; } @@ -1630,7 +1867,8 @@ mod tests { }; lod.plan.roots = vec![parent]; lod.ready.clear(); - lod.ready.insert(parent, vec![Column::default(); 256]); + lod.ready + .insert(parent, Arc::new(vec![Column::default(); 256])); lod.active = [parent].into_iter().collect(); lod.pending = (0..SAMPLE_JOBS - 1) .map(|i| TileKey { @@ -1642,7 +1880,7 @@ mod tests { lod.sample_nearby = true; lod.detail_request_pending = true; lod.meshing = true; - lod.update(camera, 0.0, 2, 64, FxHashSet::default()); + lod.update(camera, 0.0, 2, 64, Some(FxHashSet::default())); let Some(Job::Sample(nearby)) = lod.shared.jobs.lock().unwrap().pop_front() else { panic!("nearby detail was not scheduled"); }; @@ -1652,14 +1890,14 @@ mod tests { "detail should load ahead of the view" ); lod.finish_sample(nearby, vec![Column::default(); 256]); - lod.update(camera, 0.0, 2, 64, FxHashSet::default()); + lod.update(camera, 0.0, 2, 64, Some(FxHashSet::default())); let Some(Job::Sample(fallback)) = lod.shared.jobs.lock().unwrap().pop_front() else { panic!("fallback refinement was starved"); }; assert!(fallback.level > 0); lod.pending.remove(&fallback); lod.sample_nearby = true; - lod.update(camera, 90.0, 2, 64, FxHashSet::default()); + lod.update(camera, 90.0, 2, 64, Some(FxHashSet::default())); let Some(Job::Sample(turned)) = lod.shared.jobs.lock().unwrap().pop_front() else { panic!("turned view was not scheduled"); }; @@ -1685,7 +1923,8 @@ mod tests { lod.plan.nodes.insert(parent); lod.plan.split.insert(parent); lod.plan.nodes.extend(parent.children()); - lod.ready.insert(parent, vec![Column::default(); 256]); + lod.ready + .insert(parent, Arc::new(vec![Column::default(); 256])); } lod.active = [near, far].into_iter().collect(); lod.shared.jobs.lock().unwrap().clear(); @@ -1697,7 +1936,7 @@ mod tests { }) .collect(); lod.sample_nearby = false; - lod.update(camera, 0., 2, 64, FxHashSet::default()); + lod.update(camera, 0., 2, 64, Some(FxHashSet::default())); let Some(Job::Sample(broad)) = lod.shared.jobs.lock().unwrap().pop_front() else { panic!("projected-error refinement missing") }; diff --git a/crates/horizon-client/src/lod/mesh.rs b/crates/horizon-client/src/lod/mesh.rs index a991a4a8e..73287af50 100644 --- a/crates/horizon-client/src/lod/mesh.rs +++ b/crates/horizon-client/src/lod/mesh.rs @@ -302,8 +302,34 @@ fn mesh_columns_with_edges( count += neighbors[side].len(); start }); - let prepared: Vec>> = columns + let stride = key.size() / CELLS as i32; + let [ox, _, oz] = key.origin(); + // A cell meets full-detail or finer terrain: it is meshed in smaller steps. + let cell_step = |x: usize, z: usize| { + let (wx, wz) = (ox + x as i32 * stride, oz + z as i32 * stride); + let overlaps = covered_bounds.is_some_and(|[x0, z0, x1, z1]| { + wx < x1 && wx + stride > x0 && wz < z1 && wz + stride > z0 + }); + let mut step = if overlaps { stride.min(16) } else { stride }; + for other in finer { + let [x, _, z] = other.origin(); + if wx < x + other.size() && x < wx + stride && wz < z + other.size() && z < wz + stride + { + step = step.min(other.size()); + } + } + step + }; + let filled = fill_buried_gaps( + columns, + neighbors, + stride, + |x, z| cell_step(x, z) == stride, + |span| material(span, Direction::Up).fluid != 0, + ); + let prepared: Vec>> = filled .iter() + .map(|column| &**column) .chain(neighbors.iter().flatten().map(|edge| &edge.column)) .map(|column| { let materials: Vec<_> = column @@ -342,8 +368,6 @@ fn mesh_columns_with_edges( }) .collect(); let mut faces = Faces::new(); - let stride = key.size() / CELLS as i32; - let [ox, _, oz] = key.origin(); let finer_keys: FxHashSet<_> = finer.iter().copied().collect(); let mut finer_levels: Vec<_> = finer.iter().map(|key| key.level).collect(); finer_levels.sort_unstable(); @@ -362,21 +386,9 @@ fn mesh_columns_with_edges( for z in 0..CELLS { for x in 0..CELLS { let (wx, wz) = (ox + x as i32 * stride, oz + z as i32 * stride); - let overlaps = covered_bounds.is_some_and(|[x0, z0, x1, z1]| { - wx < x1 && wx + stride > x0 && wz < z1 && wz + stride > z0 - }); - let mut step = if overlaps { stride.min(16) } else { stride }; - for other in finer { - let [x, _, z] = other.origin(); - if wx < x + other.size() - && x < wx + stride - && wz < z + other.size() - && z < wz + stride - { - step = step.min(other.size()); - } - } + let step = cell_step(x, z); let column = &prepared[z * CELLS + x]; + let own_sky = column.last().map_or(0, |top| top.span.light & 0xff); for dz in (0..stride).step_by(step as usize) { for dx in (0..stride).step_by(step as usize) { if is_covered(wx + dx, wz + dz) { @@ -462,10 +474,21 @@ fn mesh_columns_with_edges( // Near meshes may have culled against the real neighbor. // Keep a finite seal where their full-detail area begins. if is_covered(nw[0], nw[1]) { - add_side(&mut faces, direction, plane, u0, u1, segment, &[], side); + add_side( + &mut faces, + direction, + plane, + u0, + u1, + segment, + &[], + side, + own_sky, + ); } else if !edge { add_side( &mut faces, direction, plane, u0, u1, segment, column, side, + own_sky, ); } else if (0..CELLS as i32).contains(&nx) && (0..CELLS as i32).contains(&nz) @@ -479,6 +502,7 @@ fn mesh_columns_with_edges( segment, &prepared[nz as usize * CELLS + nx as usize], side, + own_sky, ); } else { let edge_side = match direction { @@ -498,6 +522,7 @@ fn mesh_columns_with_edges( segment, &[], side, + own_sky, ); } // A coarse face can meet several finer columns. @@ -515,6 +540,7 @@ fn mesh_columns_with_edges( segment, &prepared[edge_offsets[edge_side] + i], side, + own_sky, ); } } @@ -621,6 +647,107 @@ mod refinement_tests { } } +/// The tile's columns with the gaps no neighbour's open air reaches filled +/// with the material below them, or the fluid above them (kelp and seagrass +/// leave gaps in water): a cave seen from nowhere adds no faces. A +/// gap is open when a neighbouring column's top lies below the gap's top, so +/// that column's open air looks into it. Unknown neighbours, and cells that +/// `whole` rejects (they meet full-detail or finer terrain), count as open; +/// those cells keep their gaps. +fn fill_buried_gaps<'a>( + columns: &'a [Column], + neighbors: &[Vec; 4], + stride: i32, + whole: impl Fn(usize, usize) -> bool, + mut fluid: impl FnMut(&Span) -> bool, +) -> Vec> { + use std::borrow::Cow; + let top = |column: &Column| { + column + .spans + .iter() + .rev() + .find(|span| span.min < span.max) + .map_or(i16::MIN, |span| span.max) + }; + let tops: Vec<_> = (0..CELLS * CELLS) + .map(|i| { + if whole(i % CELLS, i / CELLS) { + top(&columns[i]) + } else { + i16::MIN + } + }) + .collect(); + let edge = |side: usize, cell: usize| { + let (start, end) = (cell as i32 * stride, (cell as i32 + 1) * stride); + neighbors[side] + .iter() + .filter(|edge| edge.start < end && start < edge.end) + .map(|edge| top(&edge.column)) + .min() + .unwrap_or(i16::MIN) + }; + columns + .iter() + .enumerate() + .map(|(i, column)| { + let (x, z) = (i % CELLS, i / CELLS); + if column.spans.len() < 2 || !whole(x, z) { + return Cow::Borrowed(column); + } + let open = [ + if x > 0 { tops[i - 1] } else { edge(0, z) }, + if x + 1 < CELLS { + tops[i + 1] + } else { + edge(1, z) + }, + if z > 0 { tops[i - CELLS] } else { edge(2, x) }, + if z + 1 < CELLS { + tops[i + CELLS] + } else { + edge(3, x) + }, + ] + .into_iter() + .min() + .unwrap_or(i16::MIN); + let buried = |below: &Span, above: &Span| below.max < above.min && above.min <= open; + if !column + .spans + .windows(2) + .any(|pair| buried(&pair[0], &pair[1])) + { + return Cow::Borrowed(column); + } + let mut filled = Column { + surface: column.surface, + spans: Vec::with_capacity(column.spans.len()), + }; + for &span in &column.spans { + let mut span = span; + if let Some(below) = filled.spans.last_mut() + && buried(below, &span) + { + if fluid(&span) { + span.min = below.max; + } else { + below.max = span.min; + } + } + filled.push(span); + } + Cow::Owned(filled) + }) + .collect() +} + +/// Adds the parts of `segment`'s side not hidden by `neighbor`, the column +/// it faces. Parts above the neighbour's top face open air: reduced columns +/// and the seals at full-detail edges expose sides that were buried (their +/// recorded light is a cave's or none), so those take at least the sky light +/// over the top of the neighbour (or of this column, with no neighbour). fn add_side( faces: &mut Faces, direction: Direction, @@ -630,7 +757,23 @@ fn add_side( segment: &Segment<'_>, neighbor: &[Segment<'_>], side: Material, + own_sky: u16, ) { + let (open, sky) = neighbor.last().map_or((f32::NEG_INFINITY, own_sky), |top| { + (f32::from(top.span.max), top.span.light & 0xff) + }); + let mut add = |v0: f32, v1: f32| { + let mut lit = side; + for paint in lit.faces.iter_mut().flatten() { + paint.light = (paint.light & 0xff00) | (paint.light & 0xff).max(sky); + } + let split = open.clamp(v0, v1); + for (v0, v1, material) in [(v0, split, side), (split, v1, lit)] { + if v0 < v1 { + add_face(faces, direction, plane, Rect { u0, v0, u1, v1 }, material); + } + } + }; let mut floor = segment.min; for next in neighbor { if next.max <= floor @@ -640,18 +783,7 @@ fn add_side( continue; } if floor < next.min { - add_face( - faces, - direction, - plane, - Rect { - u0, - v0: floor, - u1, - v1: next.min.min(segment.max), - }, - side, - ); + add(floor, next.min.min(segment.max)); } floor = floor.max(next.max); if floor >= segment.max { @@ -659,18 +791,7 @@ fn add_side( } } if floor < segment.max { - add_face( - faces, - direction, - plane, - Rect { - u0, - v0: floor, - u1, - v1: segment.max, - }, - side, - ); + add(floor, segment.max); } } @@ -960,6 +1081,88 @@ mod tests { ); } #[test] + fn exposed_buried_sides_take_the_sky_light_over_their_neighbor() { + let mut columns = columns(); + let dark = |min, max| Span { + light: 0, + ..span(min, max, 1) + }; + // A reduced column whose lower blocks were buried (no light), next to + // a lower column, and to one with a cave below its top. + columns[0].spans = vec![dark(0, 9), span(9, 10, 1)]; + columns[1].spans = vec![span(0, 4, 1)]; + columns[CELLS].spans = vec![span(0, 2, 1), span(6, 12, 1)]; + let mesh = mesh(&columns); + let quads = mesh.solid.as_chunks::<4>().0; + let bounds = |q: &[TerrainVertex; 4]| { + let ys = q.iter().map(|v| v.pos[1]); + ( + ys.clone().fold(f32::INFINITY, f32::min), + ys.fold(0.0, f32::max), + ) + }; + // Over the lower neighbour: open air, lit like its top. + let open: Vec<_> = quads + .iter() + .filter(|q| q.iter().all(|v| v.pos[0] == 1.0 && v.pos[2] <= 1.0) && normal(q).x > 0.0) + .collect(); + assert_eq!(open.len(), 1); + assert_eq!(bounds(open[0]), (4.0, 10.0)); + assert!(open[0].iter().all(|v| v.light == 240)); + // Into the cave: its recorded light. + let cave: Vec<_> = quads + .iter() + .filter(|q| q.iter().all(|v| v.pos[2] == 1.0 && v.pos[0] <= 1.0) && normal(q).z > 0.0) + .collect(); + assert_eq!(cave.len(), 1); + assert_eq!(bounds(cave[0]), (2.0, 6.0)); + assert!(cave[0].iter().all(|v| v.light == 0)); + } + #[test] + fn caves_no_neighbor_sees_into_add_no_faces() { + let mut columns = columns(); + for column in &mut columns { + column.spans = vec![span(0, 20, 1)]; + } + let cave = 5 * CELLS + 5; + columns[cave].spans = vec![span(0, 8, 1), span(12, 20, 1)]; + let at = |mesh: &SectionMesh, y: f32| { + mesh.solid + .as_chunks::<4>() + .0 + .iter() + .filter(|q| q.iter().all(|v| v.pos[1] == y)) + .count() + }; + // Closed on every side: filled, no floor or ceiling. + let closed = mesh(&columns); + assert_eq!((at(&closed, 8.0), at(&closed, 12.0)), (0, 0)); + assert!( + closed + .solid + .iter() + .all(|v| v.pos[1] == 0.0 || v.pos[1] == 20.0) + ); + // A lower neighbour's open air looks in: the cave stays. + columns[cave + 1].spans = vec![span(0, 10, 1)]; + let open = mesh(&columns); + assert_eq!((at(&open, 8.0), at(&open, 12.0)), (1, 1)); + // Kelp leaves a gap in water: water fills it, without inner faces. + for column in &mut columns { + column.spans = vec![span(0, 5, 1), span(5, 10, 2)]; + } + columns[cave].spans = vec![span(0, 5, 1), span(5, 7, 2), span(8, 10, 2)]; + let water = mesh(&columns); + assert!( + water + .translucent + .iter() + .all(|v| v.pos[1] != 7.0 && v.pos[1] != 8.0) + ); + let uniform = mesh(&vec![columns[0].clone(); CELLS * CELLS]); + assert_eq!(water.translucent.len(), uniform.translucent.len()); + } + #[test] fn greedy_faces_preserve_material_and_light_boundaries() { let mut columns = columns(); columns[0].spans = vec![span(0, 1, 1)]; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 64286b1fe..f5d8c8480 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -177,6 +177,9 @@ pub struct Menu { pub sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, + /// `LivingEntity.onEquipItem` calls that change the item: the + /// `EquipmentSlot` name and the new stack, in order, for the caller. + pub equipped: Vec<(&'static str, Option)>, /// The merchant a merchant menu trades with. pub merchant: Option>, } @@ -398,6 +401,7 @@ impl Menu { loom_patterns: Vec::new(), sounds: Vec::new(), crafted: Vec::new(), + equipped: Vec::new(), merchant: None, } } @@ -699,6 +703,47 @@ impl Menu { self.slot_changed(env, s); } + /// `Slot.setByPlayer(stack)`: the slot's item is the previous one. + fn set_by_player(&mut self, env: &Env, s: usize, stack: Option) { + let previous = self.slot(s).cloned(); + self.set_by_player_from(env, s, stack, previous.as_ref()); + } + + /// `Slot.setByPlayer(stack, previous)`: `ArmorSlot` and the inventory + /// menu's off-hand slot first call the owner's `onEquipItem`, which acts + /// only when the item changes (`isSameItemSameComponents`). + fn set_by_player_from( + &mut self, + env: &Env, + s: usize, + mut stack: Option, + previous: Option<&ItemStack>, + ) { + tidy(&mut stack); + if let Some(slot) = self.equipment_slot(s) { + let same = match (previous.filter(|p| p.count > 0), stack.as_ref()) { + (None, None) => true, + (Some(a), Some(b)) => a.same_item_same_components(b), + _ => false, + }; + if !same { + self.equipped.push((slot, stack.clone())); + } + } + self.put(env, s, stack); + } + + /// The `EquipmentSlot` of an `ArmorSlot` or of `InventoryMenu`'s off-hand + /// slot (the only menu slot over inventory slot 40). + fn equipment_slot(&self, s: usize) -> Option<&'static str> { + let slot = self.slots[s]; + match slot.role { + Role::Armor(eq) => Some(["feet", "legs", "chest", "head"][eq]), + _ if slot.container == PLAYER && slot.index == OFFHAND => Some("offhand"), + _ => None, + } + } + /// `Slot.remove`: the container's `removeItem`. fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option { let slot = self.slots[s]; @@ -832,7 +877,7 @@ impl Menu { } let result = self.remove(env, s, amount.min(max_amount))?; if self.slot(s).is_none() { - self.put(env, s, None); + self.set_by_player_from(env, s, None, Some(&result)); } Some(result) } @@ -872,12 +917,12 @@ impl Menu { match self.slot(s).cloned() { None => { let part = split(stack, transferable); - self.put(env, s, Some(part)); + self.set_by_player(env, s, Some(part)); } Some(mut current) if current.same_item_same_components(stack) => { stack.count -= transferable; current.count += transferable; - self.put(env, s, Some(current)); + self.set_by_player(env, s, Some(current)); } Some(_) => {} } @@ -1033,7 +1078,7 @@ impl Menu { if !self.has_item(dest) && self.may_place(env, dest, stack) { let max = self.slot_max(env, dest, stack); let part = split(stack, stack.count.min(max)); - self.put(env, dest, Some(part)); + self.set_by_player(env, dest, Some(part)); changed = true; break; } @@ -1312,7 +1357,8 @@ impl Menu { let slot = self.slots[index]; if stack.count == 0 { self.containers[slot.container][slot.index] = None; - self.put(env, index, None); + // InventoryMenu: setByPlayer(EMPTY, clicked). + self.set_by_player_from(env, index, None, Some(&clicked)); } else { self.containers[slot.container][slot.index] = Some(stack.clone()); self.slot_changed(env, index); @@ -1418,7 +1464,7 @@ impl Menu { remaining -= i64::from(new_count) - i64::from(have); let mut placed = source.clone(); placed.count = new_count; - self.put(env, s, Some(placed)); + self.set_by_player(env, s, Some(placed)); } } source.count = remaining.max(0) as u32; @@ -1578,7 +1624,7 @@ impl Menu { tidy(&mut self.carried); } else if carried.count <= self.slot_max(env, s, &carried) { self.carried = Some(clicked); - self.put(env, s, Some(carried)); + self.set_by_player(env, s, Some(carried)); } else { self.carried = Some(carried); } @@ -1612,7 +1658,7 @@ impl Menu { (None, Some(taken)) => { if self.may_pickup(env, target) { self.containers[PLAYER][inv_slot] = Some(taken.clone()); - self.put(env, target, None); + self.set_by_player(env, target, None); self.on_take(env, target); } } @@ -1622,10 +1668,10 @@ impl Menu { if source.count > max { let part = split(&mut source, max); self.containers[PLAYER][inv_slot] = Some(source); - self.put(env, target, Some(part)); + self.set_by_player(env, target, Some(part)); } else { self.containers[PLAYER][inv_slot] = None; - self.put(env, target, Some(source)); + self.set_by_player(env, target, Some(source)); } } } @@ -1635,14 +1681,14 @@ impl Menu { if source.count > max { let part = split(&mut source, max); self.containers[PLAYER][inv_slot] = Some(source); - self.put(env, target, Some(part)); + self.set_by_player(env, target, Some(part)); self.on_take(env, target); if !self.inventory_add(env, &mut taken) { self.drop_stack(&taken); } } else { self.containers[PLAYER][inv_slot] = Some(taken); - self.put(env, target, Some(source)); + self.set_by_player(env, target, Some(source)); self.on_take(env, target); } } @@ -1988,6 +2034,47 @@ pub(crate) mod tests { test(&env, &mut menu); } + /// `onEquipItem` runs from the armour and off-hand slots' `setByPlayer` + /// when the item changes: never from `Inventory.setItem` (a swap's source). + #[test] + fn armour_and_off_hand_slots_report_what_is_equipped() { + with_menu(Kind::Inventory, |env, menu| { + menu.creative = false; + let name = |e: &[(&str, Option)]| { + e.iter() + .map(|(slot, s)| format!("{slot}:{}", s.as_ref().map_or("-", |s| &*s.item))) + .collect::>() + }; + // A shift-click puts the helmet on (InventoryMenu.quickMoveStack). + menu.set_slot(env, 9, stack("iron_helmet", 1)); + menu.click(env, 9, 0, Input::QuickMove).unwrap(); + assert_eq!(name(&menu.equipped), ["head:minecraft:iron_helmet"]); + // Taking it off; the same helmet back on is a change both ways. + menu.equipped.clear(); + menu.click(env, 5, 0, Input::Pickup).unwrap(); + menu.click(env, 5, 0, Input::Pickup).unwrap(); + assert_eq!( + name(&menu.equipped), + ["head:-", "head:minecraft:iron_helmet"] + ); + // F over a hotbar slot: the shield reaches the off hand by + // Inventory.setItem, so nothing; a number key onto the off-hand + // slot sets it by player. + menu.equipped.clear(); + menu.set_slot(env, 36, stack("shield", 1)); + menu.click(env, 36, 40, Input::Swap).unwrap(); + assert_eq!(menu.slot(45).map(|s| &*s.item), Some("minecraft:shield")); + assert!(menu.equipped.is_empty()); + menu.click(env, 45, 1, Input::Swap).unwrap(); + assert_eq!(name(&menu.equipped), ["offhand:-"]); + // Other menus have no equipment slots. + let mut chest = Menu::new(Kind::Chest(1)); + chest.set_slot(env, 0, stack("iron_helmet", 1)); + chest.click(env, 0, 0, Input::QuickMove).unwrap(); + assert!(chest.equipped.is_empty()); + }); + } + #[test] fn a_quick_craft_drag_previews_each_slot_and_the_rest_in_hand() { with_menu(Kind::Inventory, |env, menu| { diff --git a/crates/horizon-client/src/mobs/spawn_selection.rs b/crates/horizon-client/src/mobs/spawn_selection.rs index fa1ec736a..c87c3d97a 100644 --- a/crates/horizon-client/src/mobs/spawn_selection.rs +++ b/crates/horizon-client/src/mobs/spawn_selection.rs @@ -15,6 +15,7 @@ use super::Species; use super::spawn_rules::{self, Reason, SpawnLevel}; use crate::biome::SpawnEntry; +use crate::fast_hash::FxHashMap; use horizon_core::{ geometry::{Aabb, Vec3}, random::RandomSource, @@ -365,9 +366,15 @@ pub trait NaturalLevel: SpawnLevel { fn spawn_cost(&self, entity: &str, x: i32, y: i32, z: i32) -> Option; /// The `creature_world_gen_spawn_probability` attribute at a position. fn creature_probability(&self, x: i32, y: i32, z: i32) -> f32; - /// Every structure whose references reach the position's chunk, in the - /// chunk's reference order. - fn structures_at(&self, x: i32, y: i32, z: i32) -> Vec; + /// Every structure whose references reach the position's chunk and + /// whose id `wanted` takes, in the chunk's reference order. + fn structures_at( + &self, + x: i32, + y: i32, + z: i32, + wanted: &dyn Fn(&str) -> bool, + ) -> Vec; fn structure_spawns(&self) -> &StructureSpawns; /// `getNearestPlayer(x, y, z, -1, false)`: the squared distance to the /// nearest player that is not a spectator. @@ -624,7 +631,9 @@ pub struct Override { /// Every structure's `spawn_overrides`, by structure id then category. #[derive(Clone, Debug, Default)] pub struct StructureSpawns { - pub overrides: HashMap>, + /// Fx-hashed: natural spawning asks for every structure reaching every + /// position it tries. + pub overrides: FxHashMap>, } impl StructureSpawns { /// The overrides of the resource root first asked for, loaded once. @@ -633,7 +642,7 @@ impl StructureSpawns { SHARED.get_or_init(|| Self::load(root)) } pub fn load(root: &Path) -> Self { - let mut overrides = HashMap::new(); + let mut overrides = FxHashMap::default(); let dir = root.join("data/minecraft/worldgen/structure"); for entry in fs::read_dir(dir).into_iter().flatten().flatten() { let path = entry.path(); @@ -646,7 +655,7 @@ impl StructureSpawns { else { continue; }; - let map: HashMap = v["spawn_overrides"] + let map: FxHashMap = v["spawn_overrides"] .as_object() .into_iter() .flatten() @@ -709,7 +718,14 @@ pub fn mobs_at( y: i32, z: i32, ) -> Vec { - let structures = l.structures_at(x, y, z); + // Only a fortress or a structure overriding this category's spawns can + // change the list, so only theirs are looked up (the references reaching + // most chunks are mineshafts, which override nothing). + let overrides = l.structure_spawns(); + let monster = category == Category::Monster; + let structures = l.structures_at(x, y, z, &|id| { + (monster && id == "minecraft:fortress") || overrides.get(id, category.name()).is_some() + }); if category == Category::Monster && name_at(l, x, y - 1, z) == "minecraft:nether_bricks" && structures @@ -719,7 +735,7 @@ pub fn mobs_at( return fortress_enemies(); } for s in &structures { - if let Some(o) = l.structure_spawns().get(&s.id, category.name()) + if let Some(o) = overrides.get(&s.id, category.name()) && (if o.piece { s.in_piece } else { s.in_bounds }) { return o.spawns.clone(); @@ -801,8 +817,8 @@ pub struct SpawnState { counts: [i32; 8], charges: Vec<([i32; 3], f64)>, players: Vec, - players_near: HashMap<(i32, i32), Vec>, - player_counts: HashMap, + players_near: FxHashMap<(i32, i32), Vec>, + player_counts: FxHashMap, last_checked: Option<([i32; 3], String, f64)>, } impl SpawnState { @@ -821,8 +837,8 @@ impl SpawnState { counts: [0; 8], charges: Vec::new(), players, - players_near: HashMap::new(), - player_counts: HashMap::new(), + players_near: FxHashMap::default(), + player_counts: FxHashMap::default(), last_checked: None, }; for e in entities { diff --git a/crates/horizon-client/src/mod_content.rs b/crates/horizon-client/src/mod_content.rs index c396c3333..f1ecfa8d2 100644 --- a/crates/horizon-client/src/mod_content.rs +++ b/crates/horizon-client/src/mod_content.rs @@ -641,8 +641,8 @@ const NBT_TABLES: [&str; 6] = [ "worldgen/blocks/cached-support.nbt", "worldgen/blocks/cached-collision.nbt", ]; -/// In a root built here: the content mods' ids, the namespaces loaders -/// read besides `minecraft`. +/// In a root built here: the namespaces the content mods own (their ids and +/// listed namespaces), which loaders read besides `minecraft`. const MARKER: &str = "horizon-mod-content.json"; /// Block states a world can hold. Chunk sections widen their global palette /// past vanilla's 16 bits to fit the registry (crate::chunk::set_block_states); @@ -947,6 +947,18 @@ impl Known { /// Builds the content root for `mods` over `base` in `out`. pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { + // Two mods owning one namespace would mix their files. + for (i, a) in mods.iter().enumerate() { + for b in &mods[..i] { + let (b, a) = ( + (b.id.as_str(), b.content.namespaces.as_slice()), + (a.id.as_str(), a.content.namespaces.as_slice()), + ); + if let Some(e) = horizon_mods::content::clash(b, a) { + return Err(e.into()); + } + } + } // The overlay links to the base: a relative base would leave them dangling. let base = &std::path::absolute(base)?; let plan = Plan::new(base, mods)?; @@ -1110,9 +1122,12 @@ pub fn build(base: &Path, mods: &[ContentMod], out: &Path) -> Result<()> { overlay.write(&own, &fs::read(&vanilla)?)?; } } - let mut ids: Vec<&str> = mods.iter().map(|m| m.id.as_str()).collect(); - ids.sort(); - overlay.write(MARKER, &serde_json::to_vec(&ids)?)?; + let mut namespaces: Vec<&str> = mods + .iter() + .flat_map(|m| m.content.namespaces.iter().map(String::as_str)) + .collect(); + namespaces.sort(); + overlay.write(MARKER, &serde_json::to_vec(&namespaces)?)?; Ok(()) } diff --git a/crates/horizon-client/src/mod_content_tests.rs b/crates/horizon-client/src/mod_content_tests.rs index c80b45c3e..ba95c36de 100644 --- a/crates/horizon-client/src/mod_content_tests.rs +++ b/crates/horizon-client/src/mod_content_tests.rs @@ -661,3 +661,100 @@ fn content_root_carries_a_structure_mod() { assert!(at[0].abs() < 1024 && at[2].abs() < 1024, "{at:?}"); let _ = fs::remove_dir_all(&scratch); } + +/// A content mod folder from `(path, text)` pairs, read as the game reads it. +fn folder_mod(dir: &Path, files: &[(&str, &str)]) -> ContentMod { + for (name, text) in files { + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + let package = horizon_mods::Package::read(dir).unwrap(); + ContentMod { + id: package.manifest.id.clone(), + content: Content::read(dir, &package.manifest).unwrap(), + } +} + +fn manifest(id: &str, namespaces: &str) -> String { + format!( + "id = \"{id}\"\nname = \"{id}\"\nversion = \"1.0\"\napi = \"0.2\"\ncapabilities = [\"registries\"]\nnamespaces = [{namespaces}]\n" + ) +} + +/// A mod whose files sit under namespaces besides its id (Towns and Towers' +/// `kaisyn`): they join the root, and loaders read those namespaces. +#[test] +fn listed_namespaces_join_the_root() { + let Some(base) = prepared() else { + return; + }; + let scratch = std::env::temp_dir().join(format!("horizon-mod-ns-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let toml = manifest("towers", "\"kaisyn\""); + let m = folder_mod( + &scratch.join("towers"), + &[ + ("horizon-mod.toml", &toml), + ( + "data/kaisyn/worldgen/processor_list/mossy.json", + r#"{"processors": []}"#, + ), + ( + "data/kaisyn/tags/worldgen/biome/has_tower.json", + r#"{"values": ["minecraft:plains"]}"#, + ), + ( + "assets/kaisyn/lang/en_us.json", + r#"{"block.kaisyn.x": "X"}"#, + ), + ], + ); + let root = scratch.join("root"); + build(&base, &[m], &root).unwrap(); + assert_eq!(namespaces(&root), ["kaisyn", "towers"]); + assert!(tag_namespaces(&root).contains(&"kaisyn".to_owned())); + let lists: BTreeMap = + serde_json::from_slice(&fs::read(root.join("worldgen/processor_lists.json")).unwrap()) + .unwrap(); + assert!(lists.contains_key("kaisyn:mossy")); + let tags: BTreeMap = + serde_json::from_slice(&fs::read(root.join("worldgen/biome_tags.json")).unwrap()).unwrap(); + assert!(tags.contains_key("kaisyn:has_tower")); + let _ = fs::remove_dir_all(&scratch); +} + +/// Two mods owning one namespace (one's listed namespace is the other's id, +/// or both list it) are refused together, naming both. +#[test] +fn mods_sharing_a_namespace_are_refused() { + let scratch = std::env::temp_dir().join(format!("horizon-mod-clash-{}", std::process::id())); + let _ = fs::remove_dir_all(&scratch); + let towers = folder_mod( + &scratch.join("towers"), + &[("horizon-mod.toml", &manifest("towers", "\"kaisyn\""))], + ); + let kaisyn = folder_mod( + &scratch.join("kaisyn"), + &[("horizon-mod.toml", &manifest("kaisyn", ""))], + ); + let other = folder_mod( + &scratch.join("other"), + &[("horizon-mod.toml", &manifest("other", "\"kaisyn\""))], + ); + // The check runs before the base is read. + let base = scratch.join("no-base"); + let out = scratch.join("root"); + let e = build(&base, &[towers, kaisyn], &out).unwrap_err(); + assert_eq!( + e.to_string(), + "mods towers and kaisyn both use the namespace kaisyn; turn one of them off" + ); + let towers = folder_mod( + &scratch.join("towers"), + &[("horizon-mod.toml", &manifest("towers", "\"kaisyn\""))], + ); + let e = build(&base, &[towers, other], &out).unwrap_err(); + assert!(e.to_string().starts_with("mods towers and other"), "{e}"); + let _ = fs::remove_dir_all(&scratch); +} diff --git a/crates/horizon-client/src/motion.rs b/crates/horizon-client/src/motion.rs index 6fca66c1d..f8052a747 100644 --- a/crates/horizon-client/src/motion.rs +++ b/crates/horizon-client/src/motion.rs @@ -1269,9 +1269,7 @@ impl MotionWorld<'_, '_, '_> { amount: 1, })); self.player - .health - .food - .add_exhaustion(if self.player.sprinting { 0.2 } else { 0.05 }); + .cause_food_exhaustion(if self.player.sprinting { 0.2 } else { 0.05 }); Ok(()) } /// LivingEntity.travelFallFlying with updateFallFlyingMovement. @@ -1423,7 +1421,7 @@ impl MovementStatisticsWorld for MotionWorld<'_, '_, '_> { Ok(()) } fn exhaust(&mut self, amount: f32) -> Result<()> { - self.player.health.food.add_exhaustion(amount); + self.player.cause_food_exhaustion(amount); Ok(()) } } @@ -2227,6 +2225,73 @@ mod tests { assert!(ladder.last().unwrap().1.y > 0.0); } + #[test] + fn creative_and_spectator_preserve_hunger_when_switching_from_survival() { + let root = std::env::var_os("HORIZON_TEST_RESOURCES") + .map(std::path::PathBuf::from) + .unwrap_or_else(|| { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../.local/horizon-client/26.3") + }); + if !root.join("movement-properties.nbt").exists() { + eprintln!("skipped hunger regression: prepared resources unavailable"); + return; + } + let assets = Assets::load(&root).unwrap(); + let resources = MotionResources::load(&root, &assets).unwrap(); + // Both abilities are set by creative/spectator mode changes for the + // resident player and for LAN/dedicated guests. + for spectator in [false, true] { + for food in [0, 1, 20] { + let mut player = PlayerMotion::new(&resources, Vec3::ZERO).unwrap(); + player.health.food.food = food; + player.health.food.saturation = 0.0; + player.health.food.exhaustion = 0.0; + player.health.food.timer = 79; + player.invulnerable = true; + player.spectator = spectator; + for _ in 0..160 { + player.cause_food_exhaustion(0.2); + player + .food_tick(&resources.health, Default::default()) + .unwrap(); + } + assert_eq!(player.health.food.food, food); + assert_eq!(player.health.food.saturation, 0.0); + assert_eq!(player.health.food.exhaustion, 0.0); + assert_eq!(player.health.health(), 20.0); + assert!(!player.health.dead_or_dying()); + assert!(player.events.is_empty()); + + // Pending exhaustion from survival is still processed, but an + // empty food bar cannot hurt the now-invulnerable player. + player.health.food.exhaustion = 5.0; + player.health.food.timer = 79; + player + .food_tick(&resources.health, Default::default()) + .unwrap(); + assert_eq!(player.health.food.food, (food - 1).max(0)); + assert_eq!(player.health.food.exhaustion, 1.0); + assert_eq!(player.health.health(), 20.0); + assert!(player.events.is_empty()); + + // Returning to survival resumes exhaustion and starvation. + player.health.food.food = food; + player.health.food.exhaustion = 0.0; + player.invulnerable = false; + player.spectator = false; + player.cause_food_exhaustion(0.2); + assert_eq!(player.health.food.exhaustion, 0.2); + player.health.food.exhaustion = 5.0; + player.health.food.timer = 79; + player + .food_tick(&resources.health, Default::default()) + .unwrap(); + assert_eq!(player.health.food.food, (food - 1).max(0)); + assert_eq!(player.health.health(), if food <= 1 { 19.0 } else { 20.0 }); + } + } + } + #[test] fn player_fire_damage_queues_hurt_sound_only_for_fresh_hits() { let root = std::env::var_os("HORIZON_TEST_RESOURCES") diff --git a/crates/horizon-client/src/options_horizon.rs b/crates/horizon-client/src/options_horizon.rs index b0a64c7e5..dd065d120 100644 --- a/crates/horizon-client/src/options_horizon.rs +++ b/crates/horizon-client/src/options_horizon.rs @@ -126,17 +126,19 @@ pub const SECTIONS: &[Section] = &[ name: "Accessibility", blurb: "Contrast, motion, text backgrounds and notifications.", rows: |_| { - [ - Opt::HighContrast, - Opt::MenuBlur, - Opt::TextBackgroundOpacity, - Opt::NotificationDisplayTime, - Opt::ShowSubtitles, - Opt::ViewBobbing, - Opt::ChatLineSpacing, - ] - .map(HRow::Opt) - .to_vec() + let mut rows = vec![HRow::Page( + "Controls", + "Key binds, mouse and controller", + Page::Controls, + )]; + rows.extend( + options_ui::ACCESSIBILITY_OPTIONS + .iter() + .copied() + .filter(|opt| opt.available()) + .map(HRow::Opt), + ); + rows }, }, Section { @@ -225,6 +227,8 @@ pub(crate) fn searchable_section(section: usize) -> bool { /// Whether an option is an on/off switch, and its value. fn switch_value(opt: Opt, s: &Settings) -> Option { Some(match opt { + Opt::HideLightningFlashes => s.file.bool("hideLightningFlashes"), + Opt::HideSplashTexts => s.file.bool("hideSplashTexts"), Opt::InvertY => s.invert_y, Opt::DiscreteScroll => s.discrete_scroll, Opt::ViewBobbing => s.view_bobbing, @@ -392,7 +396,18 @@ impl OptionsUi { HRow::Opt(opt) => { let (caption, value) = caption_value(opt, s); let cy = y + ROW_H / 2.0; - if let Some(on) = switch_value(opt, s) { + if !opt.available() { + ui.row(x, y, &caption, "", 0.0); + let label = "Unavailable"; + let bw = ui.button_width(label, false).max(96.0); + ui.button( + ROW + i as u64, + [control_x - bw, y + 12.0, bw, CONTROL], + label, + Button::Secondary, + false, + ); + } else if let Some(on) = switch_value(opt, s) { ui.row(x, y, &caption, "", 0.0); ui.switch(ROW + i as u64, control_x, cy, on); } else if let Kind::Slider(v) = opt.kind(s) { @@ -768,7 +783,7 @@ impl OptionsUi { Some(Target::Row(i)) => { let section = self.section.min(SECTIONS.len() - 1); match self.horizon_rows(s, section).get(i) { - Some(HRow::Opt(opt)) => { + Some(HRow::Opt(opt)) if opt.available() => { opt.cycle(s, right, framebuffer); if *opt == Opt::Preset { apply_preset(s); @@ -857,6 +872,31 @@ mod tests { (point.0 * gui_per_dp, point.1 * gui_per_dp) } + #[test] + fn accessibility_section_only_shows_available_options() { + let s = Settings::default(); + let section = SECTIONS.iter().find(|s| s.name == "Accessibility").unwrap(); + let rows = (section.rows)(&s); + let options: Vec<_> = rows + .iter() + .filter_map(|row| match row { + HRow::Opt(opt) => Some(*opt), + _ => None, + }) + .collect(); + let expected: Vec<_> = options_ui::ACCESSIBILITY_OPTIONS + .iter() + .copied() + .filter(|opt| opt.available()) + .collect(); + assert_eq!(options, expected); + assert!(options.iter().all(|opt| opt.available())); + assert!( + rows.iter() + .any(|r| matches!(r, HRow::Page(_, _, Page::Controls))) + ); + } + #[test] fn horizon_scrollbar_track_drag_is_bounded_and_stops_on_release() { let atlas = atlas(); diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 8e1875f48..4440d0a82 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -68,6 +68,22 @@ pub enum Opt { HighContrast, ShowSubtitles, NotificationDisplayTime, + Narrator, + TextBackground, + ChatDelay, + DistortionEffects, + FovEffects, + DarknessPulsing, + DamageTilt, + GlintSpeed, + GlintStrength, + HideLightningFlashes, + MonochromeLogo, + PanoramaSpeed, + HideSplashTexts, + NarratorHotkey, + RotateWithMinecarts, + HighContrastBlockOutlines, ForceUnicode, JapaneseGlyphs, /// Horizon's controller settings (`horizon-controller.txt`). @@ -114,7 +130,72 @@ pub(crate) enum Kind { Slider(f32), Cycle, } +/// Options shared by the Classic page and Horizon's Accessibility section. +/// `AccessibilityOptionsScreen.options`, with the Controls link inserted separately. +pub(crate) const ACCESSIBILITY_OPTIONS: &[Opt] = &[ + Opt::Narrator, + Opt::ShowSubtitles, + Opt::HighContrast, + Opt::MenuBlur, + Opt::TextBackgroundOpacity, + Opt::TextBackground, + Opt::ChatOpacity, + Opt::ChatLineSpacing, + Opt::ChatDelay, + Opt::NotificationDisplayTime, + Opt::ViewBobbing, + Opt::DistortionEffects, + Opt::FovEffects, + Opt::DarknessPulsing, + Opt::DamageTilt, + Opt::GlintSpeed, + Opt::GlintStrength, + Opt::HideLightningFlashes, + Opt::MonochromeLogo, + Opt::PanoramaSpeed, + Opt::HideSplashTexts, + Opt::NarratorHotkey, + Opt::RotateWithMinecarts, + Opt::HighContrastBlockOutlines, +]; impl Opt { + /// Keep controls visible while their underlying systems are still missing. + pub(crate) fn available(self) -> bool { + !matches!( + self, + Opt::Narrator + | Opt::NarratorHotkey + | Opt::ChatDelay + | Opt::DistortionEffects + | Opt::GlintSpeed + | Opt::GlintStrength + | Opt::MonochromeLogo + | Opt::RotateWithMinecarts + | Opt::HighContrastBlockOutlines + ) + } + fn file_key(self) -> Option<&'static str> { + Some(match self { + Opt::Narrator => "narrator", + Opt::TextBackground => "backgroundForChatOnly", + Opt::ChatDelay => "chatDelay", + Opt::DistortionEffects => "screenEffectScale", + Opt::FovEffects => "fovEffectScale", + Opt::DarknessPulsing => "darknessEffectScale", + Opt::DamageTilt => "damageTiltStrength", + Opt::GlintSpeed => "glintSpeed", + Opt::GlintStrength => "glintStrength", + Opt::HideLightningFlashes => "hideLightningFlashes", + Opt::MonochromeLogo => "darkMojangStudiosBackground", + Opt::PanoramaSpeed => "panoramaScrollSpeed", + Opt::HideSplashTexts => "hideSplashTexts", + Opt::NarratorHotkey => "narratorHotkey", + Opt::RotateWithMinecarts => "rotateWithMinecart", + Opt::HighContrastBlockOutlines => "highContrastBlockOutline", + _ => return None, + }) + } + pub(crate) fn caption(self) -> &'static str { match self { Opt::Fov => "options.fov", @@ -168,6 +249,22 @@ impl Opt { Opt::HighContrast => "options.accessibility.high_contrast", Opt::ShowSubtitles => "options.showSubtitles", Opt::NotificationDisplayTime => "options.notifications.display_time", + Opt::Narrator => "options.narrator", + Opt::TextBackground => "options.accessibility.text_background", + Opt::ChatDelay => "Chat Delay", + Opt::DistortionEffects => "options.screenEffectScale", + Opt::FovEffects => "options.fovEffectScale", + Opt::DarknessPulsing => "options.darknessEffectScale", + Opt::DamageTilt => "options.damageTiltStrength", + Opt::GlintSpeed => "options.glintSpeed", + Opt::GlintStrength => "options.glintStrength", + Opt::HideLightningFlashes => "options.hideLightningFlashes", + Opt::MonochromeLogo => "options.darkMojangStudiosBackgroundColor", + Opt::PanoramaSpeed => "options.accessibility.panorama_speed", + Opt::HideSplashTexts => "options.hideSplashTexts", + Opt::NarratorHotkey => "options.accessibility.narrator_hotkey", + Opt::RotateWithMinecarts => "options.rotateWithMinecart", + Opt::HighContrastBlockOutlines => "options.accessibility.high_contrast_block_outline", Opt::ForceUnicode => "options.forceUnicodeFont", Opt::JapaneseGlyphs => "options.japaneseGlyphVariants", // Horizon's own options: English captions (no vanilla keys). @@ -189,6 +286,14 @@ impl Opt { pub(crate) fn kind(self, s: &Settings) -> Kind { let unit = |v: f32, lo: f32, hi: f32| Kind::Slider(((v - lo) / (hi - lo)).clamp(0.0, 1.0)); match self { + Opt::FovEffects | Opt::DarknessPulsing => { + Kind::Slider(s.file.double(self.file_key().unwrap()).sqrt() as f32) + } + Opt::DistortionEffects + | Opt::DamageTilt + | Opt::GlintSpeed + | Opt::GlintStrength + | Opt::PanoramaSpeed => Kind::Slider(s.file.double(self.file_key().unwrap()) as f32), Opt::Fov => unit(s.fov, 30.0, 110.0), Opt::RenderDistance => unit(s.render_distance as f32, 2.0, 64.0), Opt::SimulationDistance => unit(s.simulation_distance as f32, 5.0, 32.0), @@ -253,6 +358,21 @@ impl Opt { pub fn label(self, s: &Settings) -> Text { let c = self.caption(); match self { + Opt::ChatDelay => tr("options.chat.delay_none"), + Opt::FovEffects + | Opt::DarknessPulsing + | Opt::DistortionEffects + | Opt::DamageTilt + | Opt::GlintSpeed + | Opt::GlintStrength => { + let value = s.file.double(self.file_key().unwrap()) as f32; + if value == 0.0 { + generic(c, tr("options.off")) + } else { + percent(c, value) + } + } + Opt::PanoramaSpeed => percent(c, s.file.double("panoramaScrollSpeed") as f32), Opt::Fov => match s.fov as i32 { 70 => generic(c, tr("options.fov.min")), 110 => generic(c, tr("options.fov.max")), @@ -386,6 +506,19 @@ impl Opt { } fn value_text(self, s: &Settings) -> Text { match self { + Opt::TextBackground => tr(if s.file.bool("backgroundForChatOnly") { + "options.accessibility.text_background.chat" + } else { + "options.accessibility.text_background.everywhere" + }), + Opt::Narrator => tr("options.narrator.off"), + Opt::ChatDelay => tr("options.chat.delay_none"), + Opt::HideLightningFlashes => on_off(s.file.bool("hideLightningFlashes")), + Opt::MonochromeLogo => on_off(s.file.bool("darkMojangStudiosBackground")), + Opt::HideSplashTexts => on_off(s.file.bool("hideSplashTexts")), + Opt::NarratorHotkey => on_off(s.file.bool("narratorHotkey")), + Opt::RotateWithMinecarts => on_off(s.file.bool("rotateWithMinecart")), + Opt::HighContrastBlockOutlines => on_off(s.file.bool("highContrastBlockOutline")), Opt::InvertY => on_off(s.invert_y), Opt::DiscreteScroll => on_off(s.discrete_scroll), Opt::ViewBobbing => on_off(s.view_bobbing), @@ -481,8 +614,20 @@ impl Opt { } /// Set a slider from its 0..1 position (OptionInstance value sets). pub fn set_slider(self, s: &mut Settings, v: f32) { + if !self.available() { + return; + } + let v = v.clamp(0.0, 1.0); let step = |lo: f32, hi: f32| (lo + v * (hi - lo)).round(); match self { + Opt::FovEffects | Opt::DarknessPulsing => s.file.set( + self.file_key().unwrap(), + crate::options_file::V::Double(f64::from(v).powi(2)), + ), + Opt::DamageTilt | Opt::PanoramaSpeed => s.file.set( + self.file_key().unwrap(), + crate::options_file::V::Double(f64::from(v)), + ), Opt::Fov => s.fov = step(30.0, 110.0), Opt::RenderDistance => s.render_distance = step(2.0, 64.0) as i32, Opt::SimulationDistance => s.simulation_distance = step(5.0, 32.0) as i32, @@ -538,6 +683,9 @@ impl Opt { } /// Advance a cycle button (CycleButton.cycleValue). pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) { + if !self.available() { + return; + } let next = |n: u8, count: u8| { if back { (n + count - 1) % count @@ -557,6 +705,11 @@ impl Opt { value + 1 }; } + Opt::TextBackground | Opt::HideLightningFlashes | Opt::HideSplashTexts => { + let key = self.file_key().unwrap(); + s.file + .set(key, crate::options_file::V::Bool(!s.file.bool(key))); + } Opt::InvertY => s.invert_y = !s.invert_y, Opt::DiscreteScroll => s.discrete_scroll = !s.discrete_scroll, Opt::ViewBobbing => s.view_bobbing = !s.view_bobbing, @@ -896,6 +1049,9 @@ fn inactive(mut w: Widget) -> Widget { w } fn option_widget(s: &Settings, opt: Opt, x: f32, y: f32, w: f32) -> Widget { + if !opt.available() { + return inactive(button(x, y, w, opt.label(s), Act::Cycle(opt))); + } match opt.kind(s) { Kind::Slider(v) => Widget { x, @@ -1016,28 +1172,41 @@ impl OptionsUi { if query.is_empty() { return rows; } - rows.into_iter() - .flat_map(|row| match row { - Row::Big(opt) if lang::get(opt.caption()).to_lowercase().contains(&query) => { - vec![Row::Big(opt)] + let mut filtered = Vec::new(); + let mut pending_header = None; + for row in rows { + let matches = |opt: Opt| lang::get(opt.caption()).to_lowercase().contains(&query); + let visible = match row { + Row::Header(key) => { + pending_header = Some(key); + continue; } - Row::Pair(a, b) => { - let matches = - |opt: Opt| lang::get(opt.caption()).to_lowercase().contains(&query); - pairs( - &[Some(a), b] - .into_iter() - .flatten() - .filter(|opt| matches(*opt)) - .collect::>(), - ) + Row::Big(opt) if matches(opt) => vec![Row::Big(opt)], + Row::Pair(a, b) => pairs( + &[Some(a), b] + .into_iter() + .flatten() + .filter(|opt| matches(*opt)) + .collect::>(), + ), + // Keep navigation available regardless of the query. + Row::Buttons(a, b) => { + filtered.push(Row::Buttons(a, b)); + continue; } - // Keep navigation available and omit section headers with no visible options. - Row::Buttons(a, b) => vec![Row::Buttons(a, b)], _ => Vec::new(), - }) - .collect() + }; + if !visible.is_empty() { + // Emit a section heading only when its first matching option is found. + if let Some(key) = pending_header.take() { + filtered.push(Row::Header(key)); + } + filtered.extend(visible); + } + } + filtered } + fn list_rows(&self, s: &Settings) -> Vec { match self.page() { Page::Extras => crate::extras::rows() @@ -1217,19 +1386,20 @@ impl OptionsUi { Opt::AutoSuggestions, Opt::ReducedDebugInfo, ]), - Page::Accessibility => pairs(&[ - Opt::ShowSubtitles, - Opt::HighContrast, - Opt::MenuBlur, - Opt::TextBackgroundOpacity, - Opt::ChatOpacity, - Opt::ChatLineSpacing, - Opt::NotificationDisplayTime, - Opt::ViewBobbing, - Opt::ToggleCrouch, - Opt::ToggleSprint, - Opt::AutoJump, - ]), + Page::Accessibility => { + let mut rows = vec![Row::Buttons( + option_widget(s, Opt::Narrator, 0.0, 0.0, 150.0), + Some(button( + 0.0, + 0.0, + 150.0, + tr("options.controls"), + Act::Push(Page::Controls), + )), + )]; + rows.extend(pairs(&ACCESSIBILITY_OPTIONS[1..])); + rows + } Page::Font => pairs(&[Opt::ForceUnicode, Opt::JapaneseGlyphs]), Page::Mods => { if s.mods.installed.is_empty() { @@ -1820,6 +1990,17 @@ impl OptionsUi { if let Some(key) = key.filter(|key| lang::has(key)) { tooltip = Some(atlas.font.split(&tr(&key), 170.0)); } + if let WKind::Button { + act: Act::Cycle(opt), + .. + } = &wd.kind + && !opt.available() + { + tooltip = Some(atlas.font.split( + &Text::literal("This feature is not yet available in Horizon."), + 170.0, + )); + } if let WKind::Button { act: Act::ToggleMod(i), .. @@ -2475,6 +2656,90 @@ mod tests { use super::*; use crate::ui_theme::{MenuStyle, set_style, style}; + #[test] + fn accessibility_sliders_and_toggles_survive_options_round_trip() { + let mut s = Settings::default(); + for opt in [ + Opt::FovEffects, + Opt::DarknessPulsing, + Opt::DamageTilt, + Opt::PanoramaSpeed, + ] { + for position in [0.0, 0.5, 1.0] { + opt.set_slider(&mut s, position); + let loaded = Settings::parse(&s.serialize()); + assert_eq!(opt.slider_position(&loaded), Some(position)); + let expected = if matches!(opt, Opt::FovEffects | Opt::DarknessPulsing) { + f64::from(position).powi(2) + } else { + f64::from(position) + }; + assert_eq!(loaded.file.double(opt.file_key().unwrap()), expected); + } + } + for opt in [ + Opt::TextBackground, + Opt::HideLightningFlashes, + Opt::HideSplashTexts, + ] { + let key = opt.file_key().unwrap(); + let before = s.file.bool(key); + opt.cycle(&mut s, false, [854, 480]); + assert_eq!(Settings::parse(&s.serialize()).file.bool(key), !before); + } + Opt::TextBackground.cycle(&mut s, false, [854, 480]); + let chat_only = s.text_background(0.0); + Opt::TextBackground.cycle(&mut s, false, [854, 480]); + assert_ne!(s.text_background(0.0), chat_only); + } + + #[test] + fn accessibility_has_all_options_and_disabled_placeholders() { + let mut s = Settings::default(); + let mut ui = OptionsUi::default(); + ui.show(Page::Accessibility); + let (widgets, _, _, _) = ui.layout(&s, 480.0, 1200.0); + let options: Vec<_> = widgets + .iter() + .filter_map(|w| match w.kind { + WKind::Button { + act: Act::Cycle(opt), + .. + } + | WKind::Slider { opt, .. } => Some(opt), + _ => None, + }) + .collect(); + assert_eq!(options, ACCESSIBILITY_OPTIONS); + for &opt in ACCESSIBILITY_OPTIONS { + let widget = widgets + .iter() + .find(|w| match w.kind { + WKind::Button { + act: Act::Cycle(o), .. + } + | WKind::Slider { opt: o, .. } => o == opt, + _ => false, + }) + .expect("every accessibility option has a control"); + if !opt.available() { + assert!(matches!(widget.kind, WKind::Button { active: false, .. })); + let before = s.serialize(); + opt.cycle(&mut s, false, [854, 480]); + opt.set_slider(&mut s, 0.0); + assert_eq!(s.serialize(), before); + } + } + assert!(widgets.iter().any(|w| matches!( + w.kind, + WKind::Button { + act: Act::Push(Page::Controls), + active: true, + .. + } + ))); + } + #[test] fn render_distance_slider_round_trips_through_extended_options_range() { let mut s = Settings::default(); @@ -2726,6 +2991,76 @@ mod tests { } } + #[test] + fn classic_video_search_keeps_only_headings_with_matching_options() { + let mut ui = OptionsUi::default(); + ui.show(Page::Video); + let settings = Settings::default(); + let headers = |rows: Vec| { + rows.into_iter() + .filter_map(|row| match row { + Row::Header(key) => Some(key), + _ => None, + }) + .collect::>() + }; + let all_headers = vec![ + "options.video.display.header", + "options.video.quality.header", + "options.video.preferences.header", + ]; + assert_eq!(headers(ui.list_rows(&settings)), all_headers); + for (opt, header) in [ + (Opt::Fullscreen, all_headers[0]), + (Opt::RenderDistance, all_headers[1]), + (Opt::Preset, all_headers[1]), + (Opt::Autosave, all_headers[2]), + ] { + ui.settings_search + .set_value(&lang::get(opt.caption()).to_uppercase()); + let rows = ui.list_rows(&settings); + assert_eq!(headers(ui.list_rows(&settings)), vec![header]); + assert!(rows.iter().any(|row| match row { + Row::Big(found) => *found == opt, + Row::Pair(a, b) => *a == opt || *b == Some(opt), + _ => false, + })); + assert!(rows.iter().any(|row| matches!(row, Row::Buttons(..)))); + } + ui.settings_search.set_value("no matching video setting"); + let rows = ui.list_rows(&settings); + assert!(headers(ui.list_rows(&settings)).is_empty()); + assert!(rows.iter().all(|row| matches!(row, Row::Buttons(..)))); + ui.settings_search.set_value(""); + assert_eq!(headers(ui.list_rows(&settings)), all_headers); + } + + #[test] + fn classic_search_emits_each_matching_heading_once_in_section_order() { + let mut ui = OptionsUi::default(); + ui.settings_search + .set_value(&lang::get(Opt::Fullscreen.caption())); + let rows = ui.filter_option_rows(vec![ + Row::Header("empty"), + Row::Header("display"), + Row::Pair(Opt::Fullscreen, Some(Opt::Fullscreen)), + Row::Big(Opt::Fullscreen), + Row::Header("quality"), + Row::Big(Opt::Fullscreen), + Row::Header("trailing empty"), + ]); + assert!(matches!( + rows.as_slice(), + [ + Row::Header("display"), + Row::Pair(Opt::Fullscreen, Some(Opt::Fullscreen)), + Row::Big(Opt::Fullscreen), + Row::Header("quality"), + Row::Big(Opt::Fullscreen), + ] + )); + } + #[test] fn classic_video_gui_scale_cycles_on_press_without_dragging() { let atlas = atlas(); @@ -3550,6 +3885,8 @@ mod tests { #[test] fn classic_video_settings_lead_back_to_horizon_menus() { + let previous_style = style(); + set_style(MenuStyle::Horizon); let s = Settings::default(); let mut ui = OptionsUi::default(); ui.push(Page::Video); @@ -3571,5 +3908,6 @@ mod tests { crate::options_horizon::SECTIONS[ui.section].name, "Interface" ); + set_style(previous_style); } } diff --git a/crates/horizon-client/src/streaming.rs b/crates/horizon-client/src/streaming.rs index 0a63428e9..5e4266894 100644 --- a/crates/horizon-client/src/streaming.rs +++ b/crates/horizon-client/src/streaming.rs @@ -768,6 +768,15 @@ impl Streaming { pub fn pending(&self) -> usize { self.shared.queue.lock().unwrap().len() } + /// Whether any chunk is queued or on its way from generation to a mesh. + pub fn busy(&self) -> bool { + !(self.generating.is_empty() + && self.decorating == 0 + && self.finishing.is_empty() + && self.lighting.is_empty() + && self.meshing.is_empty() + && self.pending() == 0) + } /// How much work each stage holds: queued jobs, then what is in flight or /// waiting at each step from generation to meshing. pub fn stages(&self) -> [(&'static str, usize); 7] { diff --git a/crates/horizon-client/src/ui_theme.rs b/crates/horizon-client/src/ui_theme.rs index 7f99e9830..2c30bf219 100644 --- a/crates/horizon-client/src/ui_theme.rs +++ b/crates/horizon-client/src/ui_theme.rs @@ -38,7 +38,7 @@ pub enum MenuStyle { /// Vanilla's screens, exactly as the parity harnesses expect them. Classic, } -static STYLE: AtomicU8 = AtomicU8::new(0); +static STYLE: AtomicU8 = AtomicU8::new(1); pub fn style() -> MenuStyle { if STYLE.load(Ordering::Relaxed) == 1 { MenuStyle::Classic @@ -55,16 +55,18 @@ pub fn set_style(s: MenuStyle) { /// Horizon-only preferences live in `horizon.txt` beside `options.txt`, so /// vanilla's options file stays exactly as vanilla writes it. pub fn load_preferences(dir: &Path) { - let text = std::fs::read_to_string(dir.join("horizon.txt")).unwrap_or_default(); - let classic = text.lines().any(|l| l.trim() == "menuStyle:classic"); + let saved = preference(dir, "menuStyle"); // HORIZON_MENU_STYLE=classic forces vanilla's screens (tests, harnesses). let forced = std::env::var("HORIZON_MENU_STYLE").ok(); - set_style(match forced.as_deref() { + set_style(preferred_style(saved.as_deref(), forced.as_deref())); +} +fn preferred_style(saved: Option<&str>, forced: Option<&str>) -> MenuStyle { + match forced { Some("classic") => MenuStyle::Classic, Some("horizon") => MenuStyle::Horizon, - _ if classic => MenuStyle::Classic, - _ => MenuStyle::Horizon, - }); + _ if saved == Some("horizon") => MenuStyle::Horizon, + _ => MenuStyle::Classic, + } } pub fn save_preferences(dir: &Path) { let value = match style() { @@ -1419,6 +1421,27 @@ pub const fn id(name: &str, index: u64) -> u64 { mod tests { use super::*; + #[test] + fn classic_is_the_default_and_explicit_menu_preferences_are_preserved() { + for saved in [None, Some("classic"), Some("invalid")] { + assert_eq!(preferred_style(saved, None), MenuStyle::Classic); + } + assert_eq!(preferred_style(Some("horizon"), None), MenuStyle::Horizon); + assert_eq!(preferred_style(None, Some("horizon")), MenuStyle::Horizon); + assert_eq!( + preferred_style(Some("classic"), Some("horizon")), + MenuStyle::Horizon + ); + assert_eq!( + preferred_style(Some("horizon"), Some("classic")), + MenuStyle::Classic + ); + assert_eq!( + preferred_style(Some("horizon"), Some("invalid")), + MenuStyle::Horizon + ); + } + #[test] fn atlas_reload_regenerates_text_and_corners_at_the_same_address() { let atlas = HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap(); diff --git a/crates/horizon-mod-sdk/src/lib.rs b/crates/horizon-mod-sdk/src/lib.rs index 428638c6d..ccfdb7947 100644 --- a/crates/horizon-mod-sdk/src/lib.rs +++ b/crates/horizon-mod-sdk/src/lib.rs @@ -21,7 +21,7 @@ //! ``` //! //! Every interface but `log` is a capability: list the ones the mod uses in -//! `horizon-mod.toml` (`game-read`, `chat`, `hud`). +//! `horizon-mod.toml` (`game-read`, `chat`, `hud`, `storage`). wit_bindgen::generate!({ path: "wit", @@ -32,7 +32,7 @@ wit_bindgen::generate!({ }); pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; -pub use horizon::mods::{chat, game, hud, log}; +pub use horizon::mods::{chat, game, hud, log, storage}; /// The game's calls into a mod. Only the hooks [`Registration`] asks for /// are called; the others may stay as their defaults. diff --git a/crates/horizon-mod-sdk/wit/horizon.wit b/crates/horizon-mod-sdk/wit/horizon.wit index 749183bbd..972389a82 100644 --- a/crates/horizon-mod-sdk/wit/horizon.wit +++ b/crates/horizon-mod-sdk/wit/horizon.wit @@ -66,6 +66,17 @@ interface hud { clear: func(); } +/// Capability `storage`: a per-mod folder of small key/value files, quota'd +/// (docs/mods.md). Keys are `[a-z0-9_.-]{1,64}`, one path segment. +interface storage { + /// None if `key` has never been `set`, or the key is not well-formed. + get: func(key: string) -> option>; + /// Errs on a malformed key or over quota (bytes for the whole mod). + set: func(key: string, value: list) -> result<_, string>; + /// No error if `key` was already absent. + delete: func(key: string); +} + /// What the game calls. Only the hooks `init` asks for are ever called. interface events { record registration { @@ -93,5 +104,6 @@ world horizon-mod { import game; import chat; import hud; + import storage; export events; } diff --git a/crates/horizon-mods/src/content.rs b/crates/horizon-mods/src/content.rs index 9afe95d0a..f17c2bb8a 100644 --- a/crates/horizon-mods/src/content.rs +++ b/crates/horizon-mods/src/content.rs @@ -3,9 +3,11 @@ //! declares in `data//horizon/block/` and `data//horizon/item/`. //! //! Content is data, not code: nothing here runs in the sandbox. What a mod -//! may add is fenced instead. Its own namespace, plus additions to vanilla -//! tags and to the convention tags (`c`, which NeoForge and Fabric mods share). Paths are plain, files and totals are capped, and vanilla ids -//! cannot be redefined. +//! may add is fenced instead. Its own namespaces (its id and the ones its +//! manifest lists), plus additions to vanilla tags and to the convention +//! tags (`c`, which NeoForge and Fabric mods share). Paths are plain, files +//! and totals are capped, vanilla ids cannot be redefined, and no two mods +//! share a namespace ([`clash`]). use crate::manifest::{Capability, MANIFEST, Manifest}; use serde::Deserialize; use std::{ @@ -141,6 +143,19 @@ pub struct Content { pub files: Vec, pub blocks: Vec, pub items: Vec, + /// The namespaces it owns: the mod id, then the manifest's `namespaces`. + pub namespaces: Vec, +} + +/// Why two content mods cannot be on together: a namespace both own (one's +/// id or listed namespace is the other's), which would mix their files. +/// `a` and `b` are (mod id, owned namespaces). +pub fn clash(a: (&str, &[String]), b: (&str, &[String])) -> Option { + let shared = a.1.iter().find(|ns| b.1.contains(ns))?; + Some(format!( + "mods {} and {} both use the namespace {shared}; turn one of them off", + a.0, b.0 + )) } impl Content { @@ -187,6 +202,7 @@ impl Content { files, blocks: Vec::new(), items: Vec::new(), + namespaces: manifest.owned_namespaces().map(str::to_owned).collect(), }; content.check(manifest)?; Ok(content) @@ -249,13 +265,19 @@ impl Content { parts.next().unwrap_or(""), ); let own = namespace == id; + let owned = own || manifest.namespaces.iter().any(|n| n == namespace); // Vanilla's own files stay vanilla's; a mod may only add to its // tags, and to the convention tags mods share. let shared = matches!(namespace, "minecraft" | "c"); - let allowed = own || (top == "data" && shared && rest.starts_with("tags/")); + let allowed = owned || (top == "data" && shared && rest.starts_with("tags/")); if !allowed { return Err(format!( - "{name}: a mod adds files in its own namespace ({top}/{id}/) or to vanilla and convention (c) tags" + "{name}: a mod adds files in its own namespaces ({top}/{id}/ and those listed in namespaces) or to vanilla and convention (c) tags" + )); + } + if !own && top == "data" && rest.starts_with("horizon/") { + return Err(format!( + "{name}: blocks and items are declared in data/{id}/horizon/" )); } let Some(decl) = (own && top == "data") @@ -471,7 +493,7 @@ capabilities = ["registries"] e }; let e = refused("other-ns", &[("data/other/horizon/block/a.json", BLOCK)]); - assert!(e.contains("own namespace"), "{e}"); + assert!(e.contains("own namespaces"), "{e}"); refused( "vanilla-asset", &[("assets/minecraft/textures/block/stone.png", b"x")], @@ -522,6 +544,38 @@ capabilities = ["registries"] ); } + #[test] + fn listed_namespaces_hold_content() { + let manifest = format!("{MANIFEST_TEXT}namespaces = [\"kaisyn\"]\n"); + let files: &[(&str, &[u8])] = &[ + ("data/kaisyn/worldgen/template_pool/a.json", b"{}"), + ("data/kaisyn/structure/a.nbt", b"nbt"), + ("assets/kaisyn/lang/en_us.json", b"{}"), + ]; + let content = hmod("listed", &manifest, files).unwrap(); + assert_eq!(content.files.len(), 3); + assert_eq!(content.namespaces, ["ruby", "kaisyn"]); + // Declarations stay in the id's namespace. + let decl: &[(&str, &[u8])] = &[("data/kaisyn/horizon/block/a.json", BLOCK)]; + let e = hmod("listed-decl", &manifest, decl).unwrap_err(); + assert!(e.contains("declared in data/ruby/horizon/"), "{e}"); + // A namespace it does not list is still outside. + let other: &[(&str, &[u8])] = &[("data/other/structure/a.nbt", b"nbt")]; + assert!(hmod("listed-other", &manifest, other).is_err()); + } + + #[test] + fn mods_sharing_a_namespace_clash() { + let t_and_t = ["t_and_t".to_owned(), "kaisyn".to_owned()]; + let kaisyn = ["kaisyn".to_owned()]; + let ruby = ["ruby".to_owned(), "gems".to_owned()]; + assert_eq!( + clash(("t_and_t", &t_and_t), ("kaisyn", &kaisyn)).as_deref(), + Some("mods t_and_t and kaisyn both use the namespace kaisyn; turn one of them off") + ); + assert_eq!(clash(("t_and_t", &t_and_t), ("ruby", &ruby)), None); + } + #[test] fn content_needs_the_registries_capability() { let code_only = MANIFEST_TEXT diff --git a/crates/horizon-mods/src/manifest.rs b/crates/horizon-mods/src/manifest.rs index 47eeba8fe..44cdbd418 100644 --- a/crates/horizon-mods/src/manifest.rs +++ b/crates/horizon-mods/src/manifest.rs @@ -13,6 +13,9 @@ pub const API: &str = "0.1"; /// `assets/` and `data/` in the `.hmod`, with blocks and items declared in /// `data//horizon/` (docs/modpacks.md). Code still links API 0.1. pub const APIS: [&str; 2] = [API, "0.2"]; +/// Namespaces no mod may claim: vanilla's, the convention tags' (mods add +/// to those, docs/mods.md) and the game's own. +const RESERVED_NAMESPACES: [&str; 3] = ["minecraft", "c", "horizon"]; /// The biggest `mod.wasm` a mod may ship. const MAX_WASM: u64 = 32 << 20; @@ -33,6 +36,12 @@ pub struct Manifest { pub side: Side, #[serde(default)] pub capabilities: Vec, + /// Namespaces besides `id` that the mod's `assets/` and `data/` use, for + /// a content mod whose files sit under other names than its id (Towns + /// and Towers ships `kaisyn` and `towns_and_towers`). No two content mods + /// that are on may share one (`content::clash`). + #[serde(default)] + pub namespaces: Vec, } #[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq)] @@ -55,15 +64,17 @@ pub enum Capability { GameRead, Chat, Hud, + Storage, /// New blocks and items from the mod's `data/` (API 0.2): no WIT /// interface, the game reads them before the world loads. Registries, } impl Capability { - pub const ALL: [Capability; 4] = [ + pub const ALL: [Capability; 5] = [ Capability::GameRead, Capability::Chat, Capability::Hud, + Capability::Storage, Capability::Registries, ]; /// The WIT interface it grants, in `horizon:mods`. @@ -72,6 +83,7 @@ impl Capability { Capability::GameRead => "game", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Storage => "storage", Capability::Registries => "registries", } } @@ -81,6 +93,7 @@ impl Capability { Capability::GameRead => "see your position, health and the time", Capability::Chat => "show you chat messages", Capability::Hud => "draw text on your screen", + Capability::Storage => "save its own settings to disk", Capability::Registries => "add blocks and items to your worlds", } } @@ -110,6 +123,7 @@ impl fmt::Display for Capability { Capability::GameRead => "game-read", Capability::Chat => "chat", Capability::Hud => "hud", + Capability::Storage => "storage", Capability::Registries => "registries", }; f.write_str(name) @@ -141,8 +155,37 @@ impl Manifest { "{MANIFEST}: capability registries needs api = \"0.2\"" )); } + if !m.namespaces.is_empty() && !m.capabilities.contains(&Capability::Registries) { + return Err(format!( + "{MANIFEST}: namespaces are for content, which needs capability registries" + )); + } + for (i, ns) in m.namespaces.iter().enumerate() { + // Vanilla's namespace characters, at most as long as an id. + let chars_ok = (1..=64).contains(&ns.len()) + && ns + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b)); + if !chars_ok { + return Err(format!( + "{MANIFEST}: namespace {ns:?} is not [a-z0-9_.-]{{1,64}}" + )); + } + if RESERVED_NAMESPACES.contains(&ns.as_str()) { + return Err(format!( + "{MANIFEST}: namespace {ns} is not a mod's to claim (only to add to its tags)" + )); + } + if *ns == m.id || m.namespaces[..i].contains(ns) { + return Err(format!("{MANIFEST}: namespace {ns} is listed twice")); + } + } Ok(m) } + /// The namespaces the mod's content owns: its id, then `namespaces`. + pub fn owned_namespaces(&self) -> impl Iterator { + std::iter::once(self.id.as_str()).chain(self.namespaces.iter().map(String::as_str)) + } /// Checks that the component's imports need only declared capabilities. pub fn check_imports<'a>( &self, @@ -300,6 +343,14 @@ capabilities = ["game-read", "hud"] ); assert!(m.check_imports(["wasi:filesystem/types@0.2.0"]).is_err()); assert!(m.check_imports(["horizon:mods/game@0.2.0"]).is_err()); + let storage = m.check_imports(["horizon:mods/storage@0.1.0"]); + assert_eq!( + storage, + Err("uses capability storage, missing from horizon-mod.toml".into()) + ); + let with_storage = EXAMPLE.replace("\"hud\"", "\"hud\", \"storage\""); + let m = Manifest::parse(&with_storage).unwrap(); + assert_eq!(m.check_imports(["horizon:mods/storage@0.1.0"]), Ok(())); } #[test] @@ -312,6 +363,25 @@ capabilities = ["game-read", "hud"] assert!(Manifest::parse(&unknown).is_err()); } + #[test] + fn checks_extra_namespaces() { + let content = "id = \"t_and_t\"\nname = \"T\"\nversion = \"1\"\napi = \"0.2\"\ncapabilities = [\"registries\"]\n"; + let with = |list: &str| Manifest::parse(&format!("{content}namespaces = [{list}]\n")); + let m = with("\"kaisyn\", \"towns_and_towers\"").unwrap(); + let owned: Vec<&str> = m.owned_namespaces().collect(); + assert_eq!(owned, ["t_and_t", "kaisyn", "towns_and_towers"]); + for reserved in ["minecraft", "c", "horizon"] { + let e = with(&format!("\"{reserved}\"")).unwrap_err(); + assert!(e.contains("not a mod's to claim"), "{e}"); + } + assert!(with("\"t_and_t\"").unwrap_err().contains("twice")); + assert!(with("\"a\", \"a\"").unwrap_err().contains("twice")); + assert!(with("\"Kaisyn\"").unwrap_err().contains("is not")); + assert!(with("\"\"").unwrap_err().contains("is not")); + let code = format!("{EXAMPLE}namespaces = [\"kaisyn\"]\n"); + assert!(Manifest::parse(&code).unwrap_err().contains("registries")); + } + #[test] fn hmod_round_trips() { let dir = std::env::temp_dir().join(format!("horizon-mods-{}", std::process::id())); diff --git a/crates/horizon-mods/src/runtime.rs b/crates/horizon-mods/src/runtime.rs index f8a6e5865..975cd1461 100644 --- a/crates/horizon-mods/src/runtime.rs +++ b/crates/horizon-mods/src/runtime.rs @@ -23,7 +23,7 @@ pub use bindings::horizon::mods::{ use bindings::{ HorizonMod, exports::horizon::mods::events::Registration, - horizon::mods::{chat, game, hud, log as mod_log}, + horizon::mods::{chat, game, hud, log as mod_log, storage}, }; /// A mod's linear memory cap. @@ -38,6 +38,20 @@ const FUEL_EVENT: u64 = 100_000_000; const CHAT_PER_CALL: usize = 8; const HUD_LINES: usize = 16; const LINE_CHARS: usize = 256; +/// Total bytes a mod's `storage` may hold on disk, across all its keys. +const STORAGE_QUOTA: u64 = 4 << 20; +/// Distinct keys a mod's `storage` may hold: `STORAGE_QUOTA` alone doesn't +/// bound a flood of zero- or near-zero-byte files (each still a file name, +/// a directory entry and an inode). +const STORAGE_MAX_KEYS: usize = 64; +/// Bytes `storage::set` may write across one hook call: fuel bounds a +/// mod's CPU time per call, not the time a synchronous disk write takes, so +/// a cheap-in-fuel loop replacing one key with large payloads needs its own +/// cap, separate from the on-disk quota it would otherwise stay under. +const STORAGE_WRITE_BUDGET: u64 = 1 << 20; +/// A mod's data, beside its `horizon-mods` folder (`find`'s `path.parent()` +/// never has a manifest there, so `find` never mistakes it for a mod). +const STORAGE_DIR: &str = ".horizon-mod-data"; /// What mods may read of the game, copied once per tick by the game. #[derive(Clone, Debug, Default)] @@ -97,6 +111,13 @@ struct State { snapshot: Arc, out: Vec, panel: Option, + /// Capability `storage`'s folder; made on first `set`. + data_dir: PathBuf, + /// Bytes `storage::set` may still write before this hook call ends + /// (reset per call in [`Mods::call`]): fuel bounds a mod's CPU time but + /// not disk I/O time, so a loop of small-fuel, large-payload `set`s + /// needs its own budget. + storage_budget: u64, limits: StoreLimits, } @@ -156,13 +177,14 @@ impl Mods { // Content is read before the world loads; a mod whose // content is refused stays off, with the reason. let content = crate::Content::read(path, &package.manifest); - entry.status = match content.and_then(|_| mods.start(&package, &reserved)) { - Ok(run) => { - entry.run = run; - Status::Running - } - Err(e) => Status::Failed(e), - }; + entry.status = + match content.and_then(|_| mods.start(path, &package, &reserved)) { + Ok(run) => { + entry.run = run; + Status::Running + } + Err(e) => Status::Failed(e), + }; } } } @@ -189,8 +211,11 @@ impl Mods { /// Starts a mod's code; `Ok(None)` for a content-only mod, which has /// nothing to run (the game reads its content before the world loads). + /// `path` is the mod's own `.hmod` or folder, for capability `storage`'s + /// per-mod directory. fn start( &mut self, + path: &Path, package: &Package, reserved: &dyn Fn(&str) -> bool, ) -> Result, String> { @@ -201,6 +226,15 @@ impl Mods { if m.side == Side::Server { return Err("server mods do not run yet".into()); } + // Two running mods with the same id would share one `data_dir` + // (capability `storage`): the first loaded keeps the id. + if self + .entries + .iter() + .any(|e| e.run.is_some() && e.manifest.as_ref().is_some_and(|other| other.id == m.id)) + { + return Err(format!("another running mod already uses id {}", m.id)); + } let taken: Vec = self .entries .iter() @@ -217,12 +251,19 @@ impl Mods { .map(|(name, _)| name.to_string()) .collect(); m.check_imports(imports.iter().map(String::as_str))?; + let data_dir = path + .parent() + .unwrap_or(Path::new(".")) + .join(STORAGE_DIR) + .join(&m.id); let state = State { name: m.name.clone(), id: m.id.clone(), snapshot, out: Vec::new(), panel: None, + data_dir, + storage_budget: STORAGE_WRITE_BUDGET, limits: StoreLimitsBuilder::new() .memory_size(MEMORY) .instances(16) @@ -292,6 +333,7 @@ impl Mods { let entry = &mut self.entries[i]; let run = entry.run.as_mut()?; run.store.data_mut().snapshot = self.snapshot.clone(); + run.store.data_mut().storage_budget = STORAGE_WRITE_BUDGET; let started = Instant::now(); let result = run .store @@ -402,9 +444,10 @@ impl Mods { any = true; self.entries[i].modified = now; self.entries[i].run = None; - let started = Package::read(&self.entries[i].path).and_then(|p| { + let path = self.entries[i].path.clone(); + let started = Package::read(&path).and_then(|p| { self.entries[i].manifest = Some(p.manifest.clone()); - self.start(&p, &reserved) + self.start(&path, &p, &reserved) }); let entry = &mut self.entries[i]; let id = entry.manifest.as_ref().map_or("?", |m| m.id.as_str()); @@ -504,3 +547,59 @@ impl hud::Host for State { self.panel = None; } } +impl storage::Host for State { + fn get(&mut self, key: String) -> Option> { + storage_key_ok(&key) + .then(|| std::fs::read(self.data_dir.join(&key)).ok()) + .flatten() + } + fn set(&mut self, key: String, value: Vec) -> Result<(), String> { + if !storage_key_ok(&key) { + return Err(format!("{key:?} is not [a-z0-9_.-]{{1,64}}")); + } + let len = value.len() as u64; + if len > self.storage_budget { + return Err("too much storage traffic in one call".into()); + } + // Everything already on disk but the file this call replaces. + let existing: Vec = std::fs::read_dir(&self.data_dir) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_name().to_string_lossy() != key) + .collect(); + if existing.len() >= STORAGE_MAX_KEYS { + return Err(format!("would hold over {STORAGE_MAX_KEYS} keys")); + } + let used: u64 = existing + .iter() + .filter_map(|e| e.metadata().ok()) + .map(|m| m.len()) + .sum(); + if used + len > STORAGE_QUOTA { + return Err(format!( + "would use over {} MiB of storage", + STORAGE_QUOTA >> 20 + )); + } + std::fs::create_dir_all(&self.data_dir).map_err(|e| e.to_string())?; + std::fs::write(self.data_dir.join(&key), value).map_err(|e| e.to_string())?; + self.storage_budget -= len; + Ok(()) + } + fn delete(&mut self, key: String) { + if storage_key_ok(&key) { + let _ = std::fs::remove_file(self.data_dir.join(&key)); + } + } +} + +/// A storage key: one path segment of `[a-z0-9_.-]{1,64}`, not `.` or `..`. +/// No `/`, so a key can never leave the mod's own directory. +fn storage_key_ok(key: &str) -> bool { + let chars_ok = (1..=64).contains(&key.len()) + && key + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-".contains(&b)); + chars_ok && key != "." && key != ".." +} diff --git a/crates/horizon-mods/tests/guest/src/lib.rs b/crates/horizon-mods/tests/guest/src/lib.rs index 86caf17bf..674c5e995 100644 --- a/crates/horizon-mods/tests/guest/src/lib.rs +++ b/crates/horizon-mods/tests/guest/src/lib.rs @@ -1,7 +1,9 @@ //! A mod for the runtime's tests: `/spin` loops forever, `/panic` panics, -//! `/grow` asks for a gigabyte, `/hello` chats; `tick` and `frame` do -//! nothing, to measure the cost of a call. -use horizon_mod_sdk::{Mod, Registration, chat}; +//! `/grow` asks for a gigabyte, `/hello` chats, `/save` and `/load` exercise +//! capability `storage` on a fixed key, `/save_key ` exercises +//! it on an arbitrary key (for the quota and key-count limits); `tick` and +//! `frame` do nothing, to measure the cost of a call. +use horizon_mod_sdk::{Mod, Registration, chat, storage}; struct Guest { ticks: u64, @@ -9,7 +11,7 @@ struct Guest { impl Mod for Guest { fn init() -> Result<(Self, Registration), String> { - let hooks = ["spin", "panic", "grow", "hello"] + let hooks = ["spin", "panic", "grow", "hello", "save", "load", "save_key"] .into_iter() .fold(Registration::new(), Registration::command) .on_tick() @@ -33,6 +35,23 @@ impl Mod for Guest { let big = std::hint::black_box(vec![1u8; 1 << 30]); Ok(Some(format!("{}", big.len()))) } + "save" => { + storage::set("note", args.as_bytes())?; + Ok(Some("saved".into())) + } + "load" => { + let text = + storage::get("note").map(|bytes| String::from_utf8_lossy(&bytes).into_owned()); + chat::show(text.as_deref().unwrap_or("(empty)")); + Ok(None) + } + "save_key" => { + let (key, text) = args + .split_once(' ') + .ok_or("Usage: /save_key ")?; + storage::set(key, text.as_bytes())?; + Ok(Some("saved".into())) + } _ => { chat::show(&format!("hello {args} after {} ticks", self.ticks)); Ok(None) diff --git a/crates/horizon-mods/tests/sandbox.rs b/crates/horizon-mods/tests/sandbox.rs index 6aa45e5cc..a246c07b0 100644 --- a/crates/horizon-mods/tests/sandbox.rs +++ b/crates/horizon-mods/tests/sandbox.rs @@ -15,7 +15,7 @@ id = "test_guest" name = "Test Guest" version = "0.1.0" api = "0.1" -capabilities = ["chat"] +capabilities = ["chat", "storage"] "#; /// Builds both mods once and writes their `.hmod` files; returns the folder. @@ -133,7 +133,7 @@ fn undeclared_capabilities_are_refused() { .unwrap() .wasm .expect("the guest has code"); - let manifest = GUEST_MANIFEST.replace("[\"chat\"]", "[]"); + let manifest = GUEST_MANIFEST.replace("\"chat\", ", ""); std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); let mods = Mods::load(&[dir], |_| true, |_| false); @@ -207,6 +207,129 @@ fn hot_reload_restarts_a_changed_mod() { assert_eq!(mods.drain(), [chat]); } +#[test] +fn storage_persists_across_reload() { + let dir = mods_dir().join("storage_reload"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("guest.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &path).unwrap(); + let mut mods = Mods::load(std::slice::from_ref(&path), |_| true, |_| false); + assert!(mods.command("save remembered")); + let saved = Output::Feedback { + text: "saved".into(), + error: false, + }; + assert_eq!(mods.drain(), [saved]); + + // A rebuild (hot_reload_restarts_a_changed_mod's pattern): a fresh Store, + // but the same on-disk data directory. + let later = std::time::SystemTime::now() + std::time::Duration::from_secs(5); + std::fs::File::options() + .write(true) + .open(&path) + .unwrap() + .set_modified(later) + .unwrap(); + assert!(mods.reload_changed(|_| false)); + + assert!(mods.command("load")); + let chat = Output::Chat { + name: "Test Guest".into(), + text: "remembered".into(), + }; + assert_eq!(mods.drain(), [chat]); +} + +#[test] +fn storage_write_budget_limits_one_call() { + let dir = mods_dir().join("storage_budget"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("guest.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &path).unwrap(); + let mut mods = Mods::load(std::slice::from_ref(&path), |_| true, |_| false); + // Under the 4 MiB on-disk quota, but over the 1 MiB a single call may + // write: a loop replacing one key can never bypass the quota by + // writing a lot in one call, only across many. + let over_budget = "a".repeat((1 << 20) + 1024); + assert!(mods.command(&format!("save {over_budget}"))); + let refused = Output::Feedback { + text: "too much storage traffic in one call".into(), + error: true, + }; + assert_eq!(mods.drain(), [refused]); +} + +#[test] +fn storage_quota_is_enforced() { + let dir = mods_dir().join("storage_quota"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("guest.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &path).unwrap(); + let mut mods = Mods::load(std::slice::from_ref(&path), |_| true, |_| false); + // Each call is under the per-call write budget; distinct keys so the + // quota (not the fixed "note" key being overwritten) is what's tested. + let chunk = "a".repeat(900 << 10); + for i in 0..4 { + assert!(mods.command(&format!("save_key k{i} {chunk}"))); + assert_eq!( + mods.drain(), + [Output::Feedback { + text: "saved".into(), + error: false, + }] + ); + } + assert!(mods.command(&format!("save_key k4 {chunk}"))); + let refused = Output::Feedback { + text: "would use over 4 MiB of storage".into(), + error: true, + }; + assert_eq!(mods.drain(), [refused]); +} + +#[test] +fn storage_key_count_is_bounded() { + let dir = mods_dir().join("storage_keys"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("guest.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &path).unwrap(); + let mut mods = Mods::load(std::slice::from_ref(&path), |_| true, |_| false); + for i in 0..64 { + assert!(mods.command(&format!("save_key k{i} x"))); + assert_eq!( + mods.drain(), + [Output::Feedback { + text: "saved".into(), + error: false, + }], + "key {i}" + ); + } + assert!(mods.command("save_key k64 x")); + let refused = Output::Feedback { + text: "would hold over 64 keys".into(), + error: true, + }; + assert_eq!(mods.drain(), [refused]); +} + +#[test] +fn duplicate_mod_ids_are_refused() { + let dir = mods_dir().join("duplicate_ids"); + std::fs::create_dir_all(&dir).unwrap(); + let first = dir.join("first.hmod"); + let second = dir.join("second.hmod"); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &first).unwrap(); + std::fs::copy(mods_dir().join("horizon_mods_test_guest.hmod"), &second).unwrap(); + // Both declare id "test_guest" (the guest's own manifest): sharing a + // `data_dir` would let the second read, overwrite or delete the + // first's storage, so only the first-loaded one may start. + let mods = Mods::load(&[first, second], |_| true, |_| false); + assert_eq!(mods.entries()[0].status, Status::Running); + let refused = Status::Failed("another running mod already uses id test_guest".into()); + assert_eq!(mods.entries()[1].status, refused); +} + /// `cargo test -p horizon-mods --release -- --ignored --nocapture`: the /// cost of the per-tick and per-frame hooks (docs/mods.md, Performance). #[test] diff --git a/crates/horizon-port-pack/src/carry.rs b/crates/horizon-port-pack/src/carry.rs index 0cf36b88b..d778d2018 100644 --- a/crates/horizon-port-pack/src/carry.rs +++ b/crates/horizon-port-pack/src/carry.rs @@ -16,6 +16,9 @@ use std::{ #[derive(Debug, Default, Serialize)] pub struct Report { pub copied: usize, + /// Namespaces besides the mod id its content owns ([`extra_namespaces`]), + /// listed in the manifest's `namespaces`. + pub namespaces: Vec, /// Files outside what a content mod may hold (other namespaces, vanilla /// data other than tags), kept in `outside/` for review. pub outside: Vec, @@ -25,6 +28,8 @@ pub struct Report { pub unreadable: BTreeMap, pub recipes_upgraded: usize, pub loot_tables_upgraded: usize, + /// Advancements whose criteria were rewritten ([`upgrade_advancement`]). + pub advancements_upgraded: usize, /// Blocks whose jar has no loot table but drop themselves in the oracle: /// the mod registers that table in code, and carry-over writes it. pub loot_tables_added: usize, @@ -54,6 +59,14 @@ pub struct Report { pub convention_biome_tags: usize, } +/// The pack around a mod being carried. +pub struct Pack<'a> { + /// The mods ported along, for the conditions of worldgen modifiers. + pub loaded: &'a dyn Fn(&str) -> bool, + /// Every mod of the pack by id, ported or not: their namespaces are theirs. + pub mods: &'a dyn Fn(&str) -> bool, +} + /// Vanilla blocks by their sorted property names. const TEMPLATES: &[(&str, &str)] = &[ ("", "minecraft:stone"), @@ -103,6 +116,52 @@ pub fn template(name: &str, properties: &BTreeSet) -> Option<&'static st .map(|(_, t)| t) } +/// [`template`] for a blockstate file. A wall's sides are `none`, `low` or +/// `tall`; sides and `up` that are `true` or `false` are a vine's (Chipped's +/// vines), which the names alone take for a wall. +pub fn block_template(name: &str, blockstate: &Value) -> Option<&'static str> { + let t = template(name, &properties(blockstate))?; + let boolean = ["north", "east", "south", "west"] + .iter() + .flat_map(|side| values(blockstate, side)) + .any(|v| v == "true" || v == "false"); + Some(if t == "minecraft:cobblestone_wall" && boolean { + "minecraft:vine" + } else { + t + }) +} + +/// The values a blockstate file tests a property for. +fn values(blockstate: &Value, property: &str) -> BTreeSet { + let mut out = BTreeSet::new(); + for key in blockstate["variants"] + .as_object() + .into_iter() + .flatten() + .map(|(k, _)| k) + { + for pair in key.split(',') { + if let Some((k, v)) = pair.split_once('=') + && k == property + { + out.insert(v.to_owned()); + } + } + } + for part in blockstate["multipart"].as_array().into_iter().flatten() { + let when = &part["when"]; + let mut conditions: Vec<&Value> = vec![when]; + for or in ["OR", "AND"] { + conditions.extend(when[or].as_array().into_iter().flatten()); + } + for v in conditions.iter().filter_map(|c| c[property].as_str()) { + out.extend(v.trim_start_matches('!').split('|').map(str::to_owned)); + } + } + out +} + /// The property names a blockstate file uses. pub fn properties(blockstate: &Value) -> BTreeSet { let mut out = BTreeSet::new(); @@ -228,15 +287,49 @@ pub fn renamed_ids(v: &mut Value) -> bool { } } +/// A 1.21.1 advancement in 26.3's shape, in place: an `enter_block` +/// criterion names its block as `blocks`, which 26.3 reads as a block list. +/// 26.3 skips the old `block` field, so the criterion matched any block the +/// player entered (Regions Unexplored's "Downer" on the first dive). +pub fn upgrade_advancement(v: &mut Value) -> bool { + let mut changed = false; + let criteria = v.get_mut("criteria").and_then(Value::as_object_mut); + for c in criteria.into_iter().flat_map(|o| o.values_mut()) { + let trigger = c.get("trigger").and_then(Value::as_str); + if !matches!(trigger, Some("minecraft:enter_block" | "enter_block")) { + continue; + } + if let Some(conditions) = c.get_mut("conditions").and_then(Value::as_object_mut) + && !conditions.contains_key("blocks") + && let Some(block) = conditions.remove("block") + { + conditions.insert("blocks".into(), block); + changed = true; + } + } + changed +} + /// 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 /// silk touch alone, or on shears alone, becomes 26.3's -/// `minecraft:tool/can_silk_touch` or `minecraft:tool/can_shear`. +/// `minecraft:tool/can_silk_touch` or `minecraft:tool/can_shear`. Number +/// providers written as a bare `{min, max}` get their `type` +/// ([`type_number`]). pub fn upgrade_loot(v: &mut Value) { match v { Value::Array(a) => a.iter_mut().for_each(upgrade_loot), Value::Object(o) => { + if let Some(Value::Array(pools)) = o.get_mut("pools") { + for pool in pools { + for key in ["rolls", "bonus_rolls"] { + if let Some(n) = pool.get_mut(key) { + type_number(n); + } + } + } + } if let Some(Value::Array(mut list)) = o.remove("conditions") { list.iter_mut().for_each(upgrade_condition); let one = match <[Value; 1]>::try_from(list) { @@ -248,6 +341,7 @@ pub fn upgrade_loot(v: &mut Value) { if let Some(Value::Array(mut list)) = o.remove("functions") { for f in &mut list { rename_kind(f, "function"); + type_function_numbers(f); upgrade_loot(f); } o.insert("modifier".to_owned(), Value::Array(list)); @@ -262,6 +356,87 @@ pub fn upgrade_loot(v: &mut Value) { } } +/// A number provider in 26.3's shape, in place. 1.21.1 read a `{min, max}` +/// with no `type` as a uniform one (NumberProviders.CODEC's fallback to +/// UniformGenerator); 26.3 dispatches on `type` alone and refuses the table. +/// Bounds nested in a uniform or binomial one get theirs too. +fn type_number(v: &mut Value) { + let Some(o) = v.as_object_mut() else { + return; + }; + if !o.contains_key("type") && o.contains_key("min") && o.contains_key("max") { + o.insert("type".to_owned(), json!("minecraft:uniform")); + } + let kind = o.get("type").and_then(Value::as_str).unwrap_or_default(); + let bounds: &[&str] = match kind.strip_prefix("minecraft:").unwrap_or(kind) { + "uniform" => &["min", "max"], + "binomial" => &["n", "p"], + _ => &[], + }; + for key in bounds { + if let Some(b) = o.get_mut(*key) { + type_number(b); + } + } +} + +/// The number providers of one loot function ([`type_number`]): the fields +/// its 1.21.1 codec reads with NumberProviders.CODEC. Range bounds such as +/// `limit_count`'s are providers too, the range itself is not. +fn type_function_numbers(f: &mut Value) { + let kind = f["type"].as_str().unwrap_or_default().to_owned(); + let Some(f) = f.as_object_mut() else { + return; + }; + let mut each = |list: &str, key: &str| { + for x in f + .get_mut(list) + .and_then(Value::as_array_mut) + .into_iter() + .flatten() + { + if let Some(n) = x.get_mut(key) { + type_number(n); + } + } + }; + match kind.strip_prefix("minecraft:").unwrap_or(&kind) { + "set_stew_effect" => each("effects", "duration"), + "set_attributes" => each("modifiers", "amount"), + "set_enchantments" => { + for level in f + .get_mut("enchantments") + .and_then(Value::as_object_mut) + .into_iter() + .flatten() + { + type_number(level.1); + } + } + "limit_count" => { + if let Some(limit) = f.get_mut("limit") { + for key in ["min", "max"] { + if let Some(n) = limit.get_mut(key) { + type_number(n); + } + } + } + } + k => { + let key = match k { + "set_count" | "enchanted_count_increase" => "count", + "set_damage" => "damage", + "enchant_with_levels" => "levels", + "set_ominous_bottle_amplifier" => "amplifier", + _ => return, + }; + if let Some(n) = f.get_mut(key) { + type_number(n); + } + } + } +} + /// `{"": kind, ...}` as `{"type": kind, ...}`. fn rename_kind(v: &mut Value, key: &str) { if let Some(o) = v.as_object_mut() @@ -312,18 +487,99 @@ fn named_tool_condition(predicate: &Value) -> Option<&'static str> { } } -/// Where a jar entry goes: `Some(true)` inside the content mod (its own -/// namespace, additions to vanilla and convention tags), `Some(false)` -/// to `outside/`, `None` not carried (code, metadata). -fn place(name: &str, id: &str) -> Option { +/// A jar entry's root (`assets` or `data`), namespace and the rest, for +/// the files a content mod may carry. +fn split(name: &str) -> Option<(&str, &str, &str)> { let mut parts = name.splitn(3, '/'); let (root, ns, rest) = (parts.next()?, parts.next()?, parts.next()?); - if !(root == "assets" || root == "data") || rest.is_empty() || name.ends_with('/') { - return None; + let carried = (root == "assets" || root == "data") && !rest.is_empty() && !name.ends_with('/'); + carried.then_some((root, ns, rest)) +} + +/// Additions to vanilla and convention tags, which every mod may hold. +fn shared_tag(root: &str, ns: &str, rest: &str) -> bool { + root == "data" && (ns == "minecraft" || ns == "c") && rest.starts_with("tags/") +} + +/// Where a jar entry goes: `Some(true)` inside the content mod (its own +/// namespaces, additions to vanilla and convention tags), `Some(false)` +/// to `outside/`, `None` not carried (code, metadata). +fn place(name: &str, owned: &[&str]) -> Option { + let (root, ns, rest) = split(name)?; + Some(owned.contains(&ns) || shared_tag(root, ns, rest)) +} + +/// Namespaces no carried mod claims: vanilla's, the convention tags', the +/// game's own and the loaders'. +const NOT_CLAIMED: [&str; 6] = ["minecraft", "c", "horizon", "forge", "neoforge", "fabric"]; + +/// The namespaces besides `id` a mod's content owns. Some mods ship their +/// files under other names than their id (Towns and Towers, `t_and_t`, +/// under `kaisyn` and `towns_and_towers`); others ship files for mods they +/// support (`wares`, `morevillagers`) or configure (`cristellib`). A +/// namespace is the mod's when its own files (its id's, its tag additions +/// and the namespaces already claimed) name ids in it, and no mod of the +/// pack (`pack_mod`) has it as its id. +fn extra_namespaces( + zip: &mut zip::ZipArchive, + id: &str, + pack_mod: &dyn Fn(&str) -> bool, +) -> Vec { + let mut candidates = BTreeSet::new(); + for name in zip.file_names() { + if let Some((_, ns, _)) = split(name) + && ns != id + && !NOT_CLAIMED.contains(&ns) + && !pack_mod(ns) + { + candidates.insert(ns.to_owned()); + } } - let shared_tags = - root == "data" && (ns == "minecraft" || ns == "c") && rest.starts_with("tags/"); - Some(ns == id || shared_tags) + if candidates.is_empty() { + return Vec::new(); + } + // The JSON files that could be the mod's, by namespace ("" for tag additions). + let mut texts: Vec<(String, Vec)> = Vec::new(); + for i in 0..zip.len() { + let Ok(mut entry) = zip.by_index(i) else { + continue; + }; + let Some((root, ns, rest)) = split(entry.name()) else { + continue; + }; + let ns = match () { + _ if shared_tag(root, ns, rest) => String::new(), + _ if ns == id || candidates.contains(ns) => ns.to_owned(), + _ => continue, + }; + let mut bytes = Vec::new(); + if entry.name().ends_with(".json") && entry.read_to_end(&mut bytes).is_ok() { + texts.push((ns, bytes)); + } + } + let mut owned: BTreeSet = [String::new(), id.to_owned()].into(); + let mut claimed = Vec::new(); + loop { + let named = candidates.iter().find(|ns| { + let (id, tag) = (format!("\"{ns}:"), format!("\"#{ns}:")); + texts.iter().any(|(owner, text)| { + owned.contains(owner) + && (contains(text, id.as_bytes()) || contains(text, tag.as_bytes())) + }) + }); + let Some(ns) = named.cloned() else { + break; + }; + candidates.remove(&ns); + owned.insert(ns.clone()); + claimed.push(ns); + } + claimed.sort(); + claimed +} + +fn contains(haystack: &[u8], needle: &[u8]) -> bool { + haystack.windows(needle.len()).any(|w| w == needle) } /// Why the game would refuse a file of the mod's own content, if it would. @@ -341,7 +597,7 @@ fn unreadable(name: &str, bytes: &mut Vec) -> Option { if bytes.starts_with(b"\xEF\xBB\xBF") { bytes.drain(..3); } - let value: Value = match serde_json::from_slice(bytes) { + let mut value: Value = match serde_json::from_slice(bytes) { Ok(v) => v, // Minecraft reads data files with Gson's lenient reader, which skips // comments: YUNG's pools have them. The carry is plain JSON. @@ -357,6 +613,13 @@ fn unreadable(name: &str, bytes: &mut Vec) -> Option { if shared_tag && value.get("replace").and_then(Value::as_bool) == Some(true) { return Some("replaces a shared tag; a content mod may only add to it".into()); } + // A tag of the mod's own that replaces: no pack before it defines the + // tag, so it is the same tag added to (Towns and Towers' biome tags). + let own_tag = name.starts_with("data/") && name.contains("/tags/"); + if own_tag && let Some(o) = value.as_object_mut().filter(|o| o.contains_key("replace")) { + o.remove("replace"); + *bytes = serde_json::to_vec_pretty(&value).expect("a parsed value serializes"); + } None } @@ -410,17 +673,17 @@ fn without_comments(bytes: &[u8]) -> Vec { /// 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; -/// `loaded` which mods are ported along, for the conditions of the mod's -/// worldgen modifiers. +/// `pack` which mods the pack holds and ports along. pub fn carry( jar: &Path, info: &JarInfo, out: &Path, facts: Option<&Facts>, allowed: &dyn Fn(&str) -> bool, - loaded: &dyn Fn(&str) -> bool, + pack: &Pack, conventions: &BTreeMap, ) -> Result { + let loaded = pack.loaded; let id = &info.mod_id; if id.is_empty() || id.len() > 64 @@ -446,10 +709,14 @@ pub fn carry( 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); + report.namespaces = extra_namespaces(&mut zip, id, pack.mods); + let owned: Vec<&str> = std::iter::once(id.as_str()) + .chain(report.namespaces.iter().map(String::as_str)) + .collect(); 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(); - let Some(keep) = place(&name, id) else { + let Some(keep) = place(&name, &owned) else { continue; }; if name.split('/').any(|p| p == ".." || p.is_empty()) { @@ -476,7 +743,13 @@ pub fn carry( outside.join(&name) }; if keep { - let rel = name.split_once(&format!("/{id}/")).map_or("", |(_, r)| r); + // The path in one of the mod's own namespaces; "" for tag additions. + let (ns, rel) = match split(&name) { + Some((_, ns, rest)) if owned.contains(&ns) => (ns, rest), + _ => ("", ""), + }; + // Blocks and items are declared under the mod id only. + let own = ns == id; if name.starts_with("data/") && (rel.starts_with("worldgen/") || rel.starts_with("structure/")) { @@ -524,7 +797,7 @@ pub fn carry( 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")); + let structure = format!("{ns}:{}", path.trim_end_matches(".json")); changed |= crate::worldgen::disables(&structure, &mut v); changed |= crate::worldgen::add_piece_counts(&structure, &mut v, &piece_counts); @@ -574,10 +847,21 @@ pub fn carry( if let Ok(v) = serde_json::from_slice::(&bytes) { crate::worldgen::convention_tags(&v, &mut biome_conventions); } + } else if rel.starts_with("advancement/") + && name.starts_with("data/") + && name.ends_with(".json") + { + if let Ok(mut advancement) = serde_json::from_slice::(&bytes) + && upgrade_advancement(&mut advancement) + { + report.advancements_upgraded += 1; + bytes = serde_json::to_vec_pretty(&advancement).unwrap_or(bytes); + } } else if rel.starts_with("loot_table/") && name.starts_with("data/") { if let Some(b) = rel .strip_prefix("loot_table/blocks/") .and_then(|b| b.strip_suffix(".json")) + .filter(|_| own) { block_loot.insert(b.to_owned()); } @@ -593,6 +877,7 @@ pub fn carry( } else if let Some(b) = rel .strip_prefix("blockstates/") .and_then(|b| b.strip_suffix(".json")) + .filter(|_| own) { if let Ok(v) = serde_json::from_slice(&bytes) { blockstates.insert(b.to_owned(), v); @@ -600,6 +885,7 @@ pub fn carry( } else if let Some(m) = rel .strip_prefix("models/item/") .and_then(|m| m.strip_suffix(".json")) + .filter(|_| own) { item_models.insert(m.to_owned()); } @@ -780,7 +1066,7 @@ pub fn carry( } } else { for (b, state) in &blockstates { - match template(b, &properties(state)) { + match block_template(b, state) { Some(t) => { write_decl("block", b, &json!({"template": t}))?; report.blocks.insert(b.clone(), t.to_owned()); @@ -799,7 +1085,7 @@ pub fn carry( } let q = |s: &str| toml::Value::String(s.to_owned()).to_string(); let name = if info.name.is_empty() { id } else { &info.name }; - let manifest = format!( + let mut manifest = format!( "# Carried over from {jar} by horizon-port-pack, for local use only.\n# Licence: {license}\nid = {}\nname = {}\nversion = {}\napi = \"0.2\"\nside = \"both\"\ncapabilities = [\"registries\"]\n", q(id), q(name), @@ -811,6 +1097,10 @@ pub fn carry( &info.license }, ); + if !report.namespaces.is_empty() { + let list: Vec = report.namespaces.iter().map(|n| q(n)).collect(); + manifest.push_str(&format!("namespaces = [{}]\n", list.join(", "))); + } write(&inside.join("horizon-mod.toml"), manifest.as_bytes())?; write( &out.join("carry-report.json"), @@ -885,6 +1175,33 @@ mod tests { ); } + #[test] + fn enter_block_criteria_name_their_blocks() { + let mut a = json!({"criteria": { + "dive": {"trigger": "minecraft:enter_block", + "conditions": {"block": "m:giant_lily_pad"}}, + "swim": {"trigger": "minecraft:enter_block", + "conditions": {"blocks": ["minecraft:water"]}}, + "has": {"trigger": "minecraft:recipe_unlocked", + "conditions": {"recipe": "m:boat"}}}}); + assert!(upgrade_advancement(&mut a)); + assert_eq!( + a["criteria"]["dive"]["conditions"], + json!({"blocks": "m:giant_lily_pad"}) + ); + assert_eq!( + a["criteria"]["swim"]["conditions"], + json!({"blocks": ["minecraft:water"]}) + ); + assert_eq!( + a["criteria"]["has"]["conditions"], + json!({"recipe": "m:boat"}) + ); + // Already 26.3's: unchanged. + assert!(!upgrade_advancement(&mut a)); + assert!(!upgrade_advancement(&mut json!({"parent": "m:root"}))); + } + #[test] fn upgrades_ingredients() { let mut r = json!({"type": "minecraft:crafting_shaped", "pattern": ["##"], @@ -937,6 +1254,47 @@ mod tests { assert_eq!(new, glass); } + #[test] + fn types_bare_number_ranges() { + // When Dungeons Arise's and Structory's chests: rolls and counts as + // bare ranges, nested in each other or in a binomial. + let mut chest = json!({"pools": [{"rolls": {"min": 1, "max": 2}, "bonus_rolls": 0, + "entries": [{"type": "minecraft:item", "name": "minecraft:cod", "functions": [ + {"function": "minecraft:set_count", "count": {"min": 3, "max": {"min": 5, "max": 7}}}, + {"function": "minecraft:enchant_with_levels", "levels": {"type": "minecraft:binomial", + "n": {"min": 1, "max": 3}, "p": 0.5}}, + {"function": "minecraft:limit_count", "limit": {"min": {"min": 0, "max": 1}, "max": 4}}, + {"function": "minecraft:set_count", "count": 2, + "conditions": [{"condition": "minecraft:match_tool", + "predicate": {"count": {"min": 1, "max": 3}}}]}]}]}]}); + upgrade_loot(&mut chest); + let uniform = + |min: Value, max: Value| json!({"type": "minecraft:uniform", "min": min, "max": max}); + let pool = &chest["pools"][0]; + assert_eq!(pool["rolls"], uniform(json!(1), json!(2))); + assert_eq!(pool["bonus_rolls"], 0); + let modifiers = &pool["entries"][0]["modifier"]; + assert_eq!( + modifiers[0]["count"], + uniform(json!(3), uniform(json!(5), json!(7))) + ); + assert_eq!(modifiers[1]["levels"]["n"], uniform(json!(1), json!(3))); + // A range stays a range; its bounds are providers. + assert_eq!( + modifiers[2]["limit"], + json!({"min": uniform(json!(0), json!(1)), "max": 4}) + ); + // An item predicate's count is a range too. + assert_eq!( + modifiers[3]["condition"]["predicate"]["count"], + json!({"min": 1, "max": 3}) + ); + // Already typed, it stays as it is. + let mut again = chest.clone(); + upgrade_loot(&mut again); + assert_eq!(again, chest); + } + #[test] fn renames_ids_vanilla_renamed() { let mut recipe = json!({"type": "minecraft:crafting_shaped", "pattern": ["c"], @@ -998,6 +1356,18 @@ mod tests { template("gem_block", &properties(&json!({"variants": {"": {}}}))), Some("minecraft:stone") ); + // Walls and vines have the same sides and up; their values tell them apart. + let wall = json!({"multipart": [{"when": {"up": "true"}}, + {"when": {"north": "low"}}, {"when": {"east": "tall"}}, + {"when": {"south": "low"}}, {"when": {"west": "low"}}]}); + assert_eq!( + block_template("gem_wall", &wall), + Some("minecraft:cobblestone_wall") + ); + let vine = json!({"multipart": [{"when": {"up": "true"}}, + {"when": {"up": "false", "north": "false", "east": "false", "south": "false", + "west": "false"}}, {"when": {"north": "true"}}]}); + assert_eq!(block_template("gem_vine", &vine), Some("minecraft:vine")); let odd = json!({"variants": {"charge=1,mode=fast": {}}}); assert_eq!(template("gem_core", &properties(&odd)), None); } @@ -1096,7 +1466,10 @@ mod tests { &out, None, &|_| true, - &|_| true, + &Pack { + loaded: &|_| true, + mods: &|_| false, + }, &BTreeMap::new(), ) .unwrap(); @@ -1162,4 +1535,93 @@ mod tests { assert_eq!(content.items[0].id, "gem:gem"); fs::remove_dir_all(&dir).unwrap(); } + + /// A mod shipping its files under other names than its id: the + /// namespaces its own files name are its, compat files for other mods + /// and a pack mod's namespace stay outside. + #[test] + fn claims_the_namespaces_its_files_name() { + let dir = std::env::temp_dir().join(format!("horizon-port-pack-ns-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + let jar = dir.join("towers-1.0.jar"); + let mut zip = zip::ZipWriter::new(fs::File::create(&jar).unwrap()); + let files: &[(&str, &str)] = &[ + ( + "META-INF/neoforge.mods.toml", + "license = \"MIT\"\n[[mods]]\nmodId = \"towers\"\nversion = \"1.0\"\n", + ), + // Its tag addition names its structure; the structure names its pool. + ( + "data/minecraft/tags/worldgen/structure/village.json", + r#"{"values": ["towers_wg:tower"]}"#, + ), + ( + "data/towers_wg/worldgen/structure/tower.json", + r#"{"type": "minecraft:jigsaw", "start_pool": "kaisyn:tower/start"}"#, + ), + ("data/kaisyn/structure/tower.nbt", "nbt"), + ( + "data/towers_wg/tags/worldgen/biome/has_tower.json", + r#"{"replace": true, "values": ["minecraft:plains"]}"#, + ), + ( + "assets/kaisyn/blockstates/brick.json", + r#"{"variants": {}}"#, + ), + // Compat for a mod outside the pack, named by nothing of its own. + ("data/wares/loot_table/crate.json", r#"{"pools": []}"#), + // A pack mod's config naming the mod's sets, and a loader's file. + ( + "data/cristel/config/towers.json", + r#"{"sets": ["towers_wg:towns"]}"#, + ), + ( + "data/neoforge/loot_modifiers/global.json", + r#"{"entries": ["towers_wg:x"]}"#, + ), + ]; + for (name, text) in files { + zip.start_file(*name, zip::write::SimpleFileOptions::default()) + .unwrap(); + zip.write_all(text.as_bytes()).unwrap(); + } + zip.finish().unwrap(); + let info = crate::jar::read(&jar).unwrap(); + let out = dir.join("work/mods/towers"); + let pack = Pack { + loaded: &|_| true, + mods: &|m| m == "cristel", + }; + let report = carry(&jar, &info, &out, None, &|_| true, &pack, &BTreeMap::new()).unwrap(); + assert_eq!(report.namespaces, ["kaisyn", "towers_wg"]); + assert_eq!(report.worldgen, 2); + assert_eq!( + report.outside, + [ + "data/wares/loot_table/crate.json", + "data/cristel/config/towers.json", + "data/neoforge/loot_modifiers/global.json", + ] + ); + // No block is declared from another namespace's blockstate. + assert!(report.blocks.is_empty()); + let carried = out.join("carry"); + let package = horizon_mods::Package::read(&carried).unwrap(); + assert_eq!(package.manifest.namespaces, ["kaisyn", "towers_wg"]); + let content = horizon_mods::Content::read(&carried, &package.manifest).unwrap(); + assert!( + content + .files + .contains(&"data/kaisyn/structure/tower.nbt".to_owned()) + ); + assert!(content.blocks.is_empty()); + // Its own tag that replaces is the same tag added to. + let tag: Value = serde_json::from_slice( + &fs::read(carried.join("data/towers_wg/tags/worldgen/biome/has_tower.json")).unwrap(), + ) + .unwrap(); + assert_eq!(tag, json!({"values": ["minecraft:plains"]})); + fs::remove_dir_all(&dir).unwrap(); + } } diff --git a/crates/horizon-port-pack/src/pipeline.rs b/crates/horizon-port-pack/src/pipeline.rs index 7152dc921..26744d7bd 100644 --- a/crates/horizon-port-pack/src/pipeline.rs +++ b/crates/horizon-port-pack/src/pipeline.rs @@ -138,6 +138,23 @@ pub fn carry( .chain(["minecraft"]) .collect(); let loaded = |m: &str| ported.contains(m); + // Every mod of the pack, ported or not: a namespace one of them has as + // its id is never another mod's. + let in_pack: BTreeSet<&str> = records + .iter() + .flat_map(|r| { + [ + Some(r.key.as_str()), + r.info.as_ref().map(|i| i.mod_id.as_str()), + ] + }) + .flatten() + .collect(); + let in_pack = |m: &str| in_pack.contains(m); + let pack = carry::Pack { + loaded: &loaded, + mods: &in_pack, + }; let mut done = 0; for r in &records { let chosen = chosen(r); @@ -169,7 +186,7 @@ pub fn carry( &work.join("mods").join(&r.key), facts.as_ref().filter(seen), &allowed, - &loaded, + &pack, &conventions, ) { Ok(report) => { diff --git a/crates/horizon-port-pack/src/processors.rs b/crates/horizon-port-pack/src/processors.rs index 5dd9c9730..26a02ad31 100644 --- a/crates/horizon-port-pack/src/processors.rs +++ b/crates/horizon-port-pack/src/processors.rs @@ -157,6 +157,16 @@ fn carry_all( list: Vec, data: &ProcessorData, carried: &mut BTreeMap, +) -> (Vec, bool) { + carry_at(list, data, carried, 0) +} + +/// [`carry_all`] for a list `depth` pillars deep (see [`pillar`]). +fn carry_at( + list: Vec, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, ) -> (Vec, bool) { let (expanded, mut changed) = references(list, data, carried, 0); let mut out = Vec::with_capacity(expanded.len()); @@ -165,7 +175,10 @@ fn carry_all( 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 pillar_type(&kind) { + Some(to) => Some(vec![pillar(&p, to, data, carried, depth)]), + None => as_data(&kind, &p, data), + }, }; match replacement { Some(replacement) => { @@ -179,6 +192,63 @@ fn carry_all( (out, changed) } +/// The game's type for the mods' processors that place blocks past their +/// template, which keep their fields (`horizon-world`'s `pillars.rs`). +fn pillar_type(kind: &str) -> Option<&'static str> { + Some(match kind { + "repurposed_structures:pillar_processor" | "moogs_structures:pillar_processor" => { + "horizon:pillar" + } + "repurposed_structures:bottom_pillar_processor" => "horizon:bottom_pillar", + "repurposed_structures:close_off_fluid_sources_processor" + | "moogs_structures:close_off_fluid_sources_processor" => "horizon:close_off_fluid_sources", + "betterfortresses:pillar_processor" | "betterjungletemples:pillar_processor" => { + "horizon:yung_pillar" + } + "betterfortresses:stair_pillar_processor" => "horizon:stair_pillar", + _ => return None, + }) +} + +/// A pillar processor as the game's `to`. Its `pillar_processor_list` +/// (which runs on each block of the column; Repurposed's often names the +/// list it is in) is written in, carried; the pillars inside that copy lose +/// theirs, as a column's blocks are never the mods' triggers. Better +/// Fortresses' stair supports get the blocks its Java code names. +fn pillar( + p: &Value, + to: &str, + data: &ProcessorData, + carried: &mut BTreeMap, + depth: usize, +) -> Value { + if to == "horizon:stair_pillar" { + return json!({"processor_type": to, + "blocks": {"minecraft:stone_brick_stairs": "minecraft:red_nether_brick_stairs", + "minecraft:purpur_stairs": "minecraft:red_nether_bricks"}, + "front": "minecraft:red_nether_brick_stairs", + "pillar": "minecraft:red_nether_bricks"}); + } + let mut out = p.clone(); + out["processor_type"] = to.into(); + let Some(o) = out.as_object_mut() else { + return out; + }; + let Some(list) = o.remove("pillar_processor_list") else { + return out; + }; + let inner = match &list { + Value::String(id) if id == "minecraft:empty" => None, + _ if depth > 0 => None, + other => referenced(other, data), + }; + if let Some(inner) = inner { + let (inner, _) = carry_at(inner, data, carried, depth + 1); + o.insert("pillar_processor_list".into(), json!({"processors": inner})); + } + out +} + /// 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) -> Value { @@ -383,6 +453,11 @@ fn referenced(lists: &Value, data: &ProcessorData) -> Option> { fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { let (ns, _) = kind.split_once(':')?; Some(match kind { + // Its structure voids keep the world's block, as vanilla's + // block_ignore does (the templates hold them; vanilla places them). + "repurposed_structures:structure_void_processor" => vec![json!({ + "processor_type": "minecraft:block_ignore", + "blocks": ["minecraft:structure_void"]})], "moogs_structures:spawner_randomizing_processor" => { let mobs = p["weighted_entities"] .as_array()? @@ -504,11 +579,135 @@ fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option> { "min": 1, "max": 2, "chance": 0.2f32 as f64, "replacement": block("minecraft:cave_air")})] } + "betterwitchhuts:leg_processor" => vec![yung_leg( + "minecraft:brown_stained_glass", + json!({"id": "minecraft:oak_log", "properties": {"axis": "y"}}), + false, + )], + "betterwitchhuts:fence_leg_processor" => vec![yung_leg( + "minecraft:crimson_fence", + block("minecraft:oak_fence"), + true, + )], + _ if ns == "betteroceanmonuments" => ocean_monument(kind)?, _ if ns == "betterdungeons" || ns == "betterdeserttemples" => vec![yung_spawner(kind, p)?], _ => return None, }) } +/// YUNG's leg processors (Better Ocean Monuments, Better Witch Huts): a +/// placeholder block becomes `state` and a column of it runs down through +/// air and fluids: the game's `horizon:yung_pillar` with fixed states, and +/// the placeholder's properties kept for the fence legs. +fn yung_leg(target: &str, state: Value, keep_properties: bool) -> Value { + let fixed = json!({"entries": [], "defaultBlockState": state}); + json!({"processor_type": "horizon:yung_pillar", "target_block": block(target), + "target_block_output": fixed, "pillar_states": fixed, + "keep_properties": keep_properties}) +} + +/// Better Ocean Monuments' processors (no fields; what they do is in their +/// Java code): placeholder blocks as vanilla's `rule` or the game's +/// `horizon:pick` (a new `nextFloat` for each chance, as the mod draws), +/// and its sea-level ones as the game's `horizon:flood_air`, +/// `horizon:waterlog` and `horizon:keep_world_block`. +fn ocean_monument(kind: &str) -> Option> { + let rule = |rules: &[(&str, Value)]| { + let rules: Vec = rules + .iter() + .map(|(from, to)| { + json!({"input_predicate": {"predicate_type": "minecraft:block_match", "block": from}, + "location_predicate": {"predicate_type": "minecraft:always_true"}, + "output_state": to}) + }) + .collect(); + json!({"processor_type": "minecraft:rule", "rules": rules}) + }; + let state = |id: &str, props: Value| json!({"id": id, "properties": props}); + let pick = |from: &str, picks: Vec<(f32, Value)>, default: Value, keep: bool| { + let picks: Vec = picks + .into_iter() + .map(|(below, state)| json!({"below": below as f64, "state": state})) + .collect(); + json!({"processor_type": "horizon:pick", "block": from, "picks": picks, + "default": {"state": default}, "redraw": true, "keep_properties": keep}) + }; + let slabs = |from: &str, slab: &str, otherwise: &str| { + let wet = |t: &str| state(slab, json!({"type": t, "waterlogged": "true"})); + pick( + from, + vec![(0.4, wet("top")), (0.8, wet("bottom"))], + block(otherwise), + false, + ) + }; + // Exposed below 0.1, else weathered below a new 0.3, else oxidized, + // with the placeholder's properties for the stairs and slabs. + let copper = |kind: &str| { + let id = |age: &str| block(&format!("minecraft:{age}{kind}")); + pick( + &format!("minecraft:oxidized_{kind}"), + vec![(0.1, id("exposed_")), (0.3, id("weathered_"))], + id("oxidized_"), + true, + ) + }; + Some(match kind.strip_prefix("betteroceanmonuments:")? { + "random_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:lime_concrete", + "minecraft:prismarine_slab", + "minecraft:air", + )], + "random_dark_prismarine_slab_decoration_processor" => vec![slabs( + "minecraft:blue_concrete", + "minecraft:dark_prismarine_slab", + "minecraft:water", + )], + "sand_gravel_processor" => { + vec![rule(&[( + "minecraft:yellow_stained_glass", + block("minecraft:gravel"), + )])] + } + "random_oxidization_processor" => [ + "copper", + "cut_copper", + "cut_copper_stairs", + "cut_copper_slab", + ] + .into_iter() + .map(copper) + .collect(), + "structure_void_processor" => vec![json!({"processor_type": "horizon:keep_world_block", + "blocks": ["minecraft:purpur_slab", "minecraft:brown_wool"]})], + "air_processor" => vec![json!({"processor_type": "horizon:flood_air"})], + "waterlog_processor" => vec![json!({"processor_type": "horizon:waterlog"})], + "seagrass_processor" => vec![rule(&[ + ( + "minecraft:red_sandstone_slab", + state("minecraft:tall_seagrass", json!({"half": "lower"})), + ), + ( + "minecraft:end_stone_brick_slab", + state("minecraft:tall_seagrass", json!({"half": "upper"})), + ), + ("minecraft:brick_slab", block("minecraft:seagrass")), + ])], + "random_sponge_processor" => vec![pick( + "minecraft:orange_stained_glass", + vec![(0.75, block("minecraft:wet_sponge"))], + block("minecraft:water"), + false, + )], + "leg_processor" => vec![yung_leg( + "minecraft:blue_stained_glass", + block("minecraft:prismarine_bricks"), + false, + )], + _ => return None, + }) +} + /// A block's states, as (block, [(property, values)]). type States = ( &'static str, @@ -1306,4 +1505,145 @@ mod tests { &mut carried )); } + + #[test] + fn ocean_monuments_become_the_games() { + let names = [ + "random_prismarine_slab_decoration_processor", + "random_dark_prismarine_slab_decoration_processor", + "sand_gravel_processor", + "random_oxidization_processor", + "structure_void_processor", + "air_processor", + "waterlog_processor", + "seagrass_processor", + "random_sponge_processor", + "leg_processor", + ]; + let processors: Vec = names + .iter() + .map(|n| json!({"processor_type": format!("betteroceanmonuments:{n}")})) + .chain([json!({"processor_type": "betterwitchhuts:fence_leg_processor"})]) + .collect(); + let mut list = json!({"processors": processors}); + let mut carried = BTreeMap::new(); + assert!(carry( + "processor_list", + &mut list, + &ProcessorData::default(), + &mut carried + )); + let p = list["processors"].as_array().unwrap(); + let types: Vec<&str> = p + .iter() + .map(|p| p["processor_type"].as_str().unwrap()) + .collect(); + let mut want = vec!["horizon:pick", "horizon:pick", "minecraft:rule"]; + want.extend(["horizon:pick"; 4]); + want.extend([ + "horizon:keep_world_block", + "horizon:flood_air", + "horizon:waterlog", + "minecraft:rule", + "horizon:pick", + "horizon:yung_pillar", + "horizon:yung_pillar", + ]); + assert_eq!(types, want); + assert_eq!(carried.values().sum::(), 11); + // Copper stairs keep their properties, each chance on a new float. + let stairs = &p[5]; + assert_eq!(stairs["block"], "minecraft:oxidized_cut_copper_stairs"); + assert_eq!( + stairs["picks"][1]["state"]["id"], + "minecraft:weathered_cut_copper_stairs" + ); + assert_eq!( + (stairs["redraw"].clone(), stairs["keep_properties"].clone()), + (json!(true), json!(true)) + ); + assert_eq!(p[0]["picks"][0]["state"]["properties"]["type"], "top"); + assert_eq!(p[1]["default"]["state"]["id"], "minecraft:water"); + assert_eq!( + p[12]["target_block_output"]["defaultBlockState"]["id"], + "minecraft:prismarine_bricks" + ); + assert_eq!(p[13]["keep_properties"], true); + } + + #[test] + fn repurposed_structure_voids_keep_the_world() { + let mut list = json!({"processors": [ + {"processor_type": "repurposed_structures:structure_void_processor"}]}); + let mut carried = BTreeMap::new(); + assert!(carry( + "processor_list", + &mut list, + &ProcessorData::default(), + &mut carried + )); + assert_eq!( + list["processors"], + json!([{"processor_type": "minecraft:block_ignore", + "blocks": ["minecraft:structure_void"]}]) + ); + assert_eq!(carried["repurposed_structures:structure_void_processor"], 1); + } + + #[test] + fn pillars_become_the_games() { + let mut d = ProcessorData::default(); + // Repurposed's city list names itself as its pillar's list. + let city = json!({"processors": [ + {"processor_type": "repurposed_structures:pillar_processor", "direction": "down", + "pillar_length": 15, "pillar_processor_list": "repurposed_structures:cities/x", + "pillar_trigger_and_replacements": [{"trigger": {"Name": "minecraft:red_stained_glass"}, + "replacement": {"Name": "minecraft:cobblestone"}}]}, + {"processor_type": "minecraft:block_rot", "integrity": 0.5}]}); + d.lists + .insert("repurposed_structures:cities/x".into(), city.clone()); + let mut list = city; + list["processors"].as_array_mut().unwrap().extend([ + json!({"processor_type": "repurposed_structures:bottom_pillar_processor", + "pillar_processor_list": "minecraft:empty"}), + json!({"processor_type": "moogs_structures:close_off_fluid_sources_processor", + "weighted_list_of_replacement_blocks": [{"block": "minecraft:stone", "weight": 1}]}), + json!({"processor_type": "betterfortresses:pillar_processor", + "target_block": {"Name": "minecraft:orange_terracotta"}, + "target_block_output": {"defaultBlockState": {"Name": "minecraft:red_nether_bricks"}, "entries": []}, + "pillar_states": {"defaultBlockState": {"Name": "minecraft:nether_bricks"}, "entries": []}}), + json!({"processor_type": "betterfortresses:stair_pillar_processor"}), + ]); + let mut carried = BTreeMap::new(); + assert!(carry("processor_list", &mut list, &d, &mut carried)); + let p = list["processors"].as_array().unwrap(); + let types: Vec<&str> = p + .iter() + .map(|p| p["processor_type"].as_str().unwrap()) + .collect(); + assert_eq!( + types, + [ + "horizon:pillar", + "minecraft:block_rot", + "horizon:bottom_pillar", + "horizon:close_off_fluid_sources", + "horizon:yung_pillar", + "horizon:stair_pillar" + ] + ); + // The named list is written in once; its own pillar loses its list. + let inner = &p[0]["pillar_processor_list"]["processors"]; + assert_eq!(inner[0]["processor_type"], "horizon:pillar"); + assert!(inner[0].get("pillar_processor_list").is_none()); + assert_eq!( + inner[0]["pillar_trigger_and_replacements"], + p[0]["pillar_trigger_and_replacements"] + ); + assert_eq!(inner[1]["processor_type"], "minecraft:block_rot"); + assert!(p[2].get("pillar_processor_list").is_none()); + assert_eq!(p[5]["pillar"], "minecraft:red_nether_bricks"); + assert_eq!(carried["repurposed_structures:pillar_processor"], 2); + assert_eq!(carried["betterfortresses:stair_pillar_processor"], 1); + } } diff --git a/crates/horizon-port-pack/src/worldgen.rs b/crates/horizon-port-pack/src/worldgen.rs index 7b8f36b65..918dbf05e 100644 --- a/crates/horizon-port-pack/src/worldgen.rs +++ b/crates/horizon-port-pack/src/worldgen.rs @@ -401,6 +401,9 @@ fn drop_java_processors(list: &mut Value, dropped: &mut BTreeMap) .map(|(_, v)| v) .collect() } + Some("horizon:pillar" | "horizon:bottom_pillar") => { + p.get_mut("pillar_processor_list").into_iter().collect() + } _ => Vec::new(), }; for list in inner { @@ -507,6 +510,12 @@ fn upgrade_types( v["type"] = "minecraft:jigsaw".into(); true } + // Formations' SimpleStructure: its pool and placement, laid out + // by the game (`horizon_world::worldgen::structure::formations`). + Some("formations:simple") => { + v["type"] = "horizon:formations".into(); + true + } Some(t) if !t.starts_with("minecraft:") => { unsupported(t); false @@ -565,6 +574,15 @@ fn upgrade_types( } else if t == "yungsapi:yung_single_element" { yung_element(element, lost); changed = true; + } else if t == "formations:single_pool_element" { + // Vanilla's element with its own ground level (1 when + // missing, as its codec reads it). + element["element_type"] = "minecraft:single_pool_element".into(); + if let Some(o) = element.as_object_mut() { + let ground = o.remove("ground_level").unwrap_or(1.into()); + o.insert("horizon:ground_level".into(), ground); + } + changed = true; } else if !t.starts_with("minecraft:") { unsupported(t); } @@ -1204,14 +1222,47 @@ mod tests { const NO_TAGS: BTreeMap> = BTreeMap::new(); + #[test] + fn formations_become_the_games() { + let mut report = Upgrade::default(); + let mut s = json!({"type": "formations:simple", "template": "f:campsites", + "placement": "surface", "biomes": "#f:x", "step": "surface_structures", + "terrain_adaptation": "beard_thin", "spawn_overrides": {}}); + assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); + assert_eq!(s["type"], "horizon:formations"); + assert_eq!(s["placement"], "surface"); + let mut pool = json!({"elements": [ + {"weight": 1, "element": {"element_type": "formations:single_pool_element", + "location": "f:a", "projection": "rigid", "ground_level": 6, "processors": []}}, + {"weight": 1, "element": {"element_type": "formations:single_pool_element", + "location": "f:b", "projection": "rigid", "processors": []}}]}); + assert!(upgrade("template_pool", &mut pool, &mut report, &NO_TAGS)); + let e = |i: usize| &pool["elements"][i]["element"]; + assert_eq!(e(0)["element_type"], "minecraft:single_pool_element"); + assert_eq!( + ( + e(0)["horizon:ground_level"].clone(), + e(1)["horizon:ground_level"].clone() + ), + (json!(6), json!(1)) + ); + assert!(e(0).get("ground_level").is_none()); + // The pieced structure stays out. + let mut pieced = json!({"type": "formations:pieced", "start_pool": "f:p", "max_depth": 2, + "max_distance_from_center": 40, "placement": "surface", "biomes": "#f:x"}); + assert!(!upgrade("structure", &mut pieced, &mut report, &NO_TAGS)); + assert_eq!(report.unsupported.get("formations:pieced"), Some(&1)); + assert_eq!(report.unsupported.len(), 1); + } + #[test] fn maps_library_types_to_vanillas() { let mut report = Upgrade::default(); let mut s = json!({"type": "lithostitched:jigsaw", "start_pool": "a:b"}); assert!(upgrade("structure", &mut s, &mut report, &NO_TAGS)); assert_eq!(s["type"], "minecraft:jigsaw"); - let mut formation = json!({"type": "formations:simple"}); - assert!(!upgrade("structure", &mut formation, &mut report, &NO_TAGS)); + let mut other = json!({"type": "somelib:structure"}); + assert!(!upgrade("structure", &mut other, &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)); @@ -1255,8 +1306,8 @@ mod tests { assert_eq!( report.unsupported, BTreeMap::from([ - ("formations:simple".into(), 1), ("somelib:element".into(), 1), + ("somelib:structure".into(), 1), ]) ); } diff --git a/crates/horizon-release-sign/Cargo.toml b/crates/horizon-release-sign/Cargo.toml new file mode 100644 index 000000000..0585adcf8 --- /dev/null +++ b/crates/horizon-release-sign/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "horizon-release-sign" +version = "0.1.0" +edition.workspace = true +license.workspace = true +rust-version = "1.85" +description = "Signed release checksums: release.yml signs SHA256SUMS, the launcher and horizon-server check them before installing" + +[dependencies] +# Ed25519 and SHA-256, already in every build through rustls (ureq's TLS): no new crypto code. +ring = "0.17" +base64 = "0.22" + +[lints] +workspace = true diff --git a/crates/horizon-release-sign/release-keys.txt b/crates/horizon-release-sign/release-keys.txt new file mode 100644 index 000000000..c39be4435 --- /dev/null +++ b/crates/horizon-release-sign/release-keys.txt @@ -0,0 +1,5 @@ +# The public keys Horizon's releases are signed with (docs/security.md, "Signed updates"): one base64 Ed25519 +# key per line. The launcher and horizon-server build these in and refuse a download no key here signed. +# The private keys exist only as the RELEASE_SIGNING_KEY secret(s) of the repository's `release` environment. +# Changing this file needs Ludovic's review (.github/CODEOWNERS). +MU4oiIQcCxkZvbwSjjXs7SySCuM6ywRQ3nGaJYZG0gw= diff --git a/crates/horizon-release-sign/src/lib.rs b/crates/horizon-release-sign/src/lib.rs new file mode 100644 index 000000000..09f9a37b4 --- /dev/null +++ b/crates/horizon-release-sign/src/lib.rs @@ -0,0 +1,345 @@ +//! Signed release checksums (docs/security.md, "Signed updates"). +//! +//! Every release carries `SHA256SUMS` (`sha256sum`'s format, ` ` per line) and +//! `SHA256SUMS.sig`: one base64 Ed25519 signature per line, each over `horizon release \n` +//! followed by SHA256SUMS's bytes, so a signed list can't be passed off under another tag. +//! release.yml and launcher.yml sign with the key(s) in the `release` environment's secrets +//! (tools/ci/sign_release.sh, OpenSSL only); the launcher and `horizon-server update` check a +//! download against the public keys built in from `release-keys.txt` before installing it, and +//! refuse it otherwise. + +use base64::{Engine, engine::general_purpose::STANDARD}; +use ring::signature::{ED25519, Ed25519KeyPair, KeyPair, UnparsedPublicKey}; + +/// The checksum list's asset name. +pub const SUMS: &str = "SHA256SUMS"; +/// Its signatures' asset name. +pub const SIGNATURE: &str = "SHA256SUMS.sig"; + +const KEYS: &str = include_str!("../release-keys.txt"); + +/// An Ed25519 public key. +pub type PublicKey = [u8; 32]; + +/// The public keys built in: those in `release-keys.txt`. A file that doesn't parse gives none, +/// so every download is refused rather than trusted (a test keeps the file valid). +pub fn trusted_keys() -> Vec { + parse_keys(KEYS).unwrap_or_default() +} + +/// The keys in a keys file: one base64 key per line; blank lines and `#` comments are skipped. +pub fn parse_keys(text: &str) -> Result, String> { + text.lines() + .map(str::trim) + .filter(|line| !line.is_empty() && !line.starts_with('#')) + .map(|line| { + let bytes = STANDARD + .decode(line) + .map_err(|e| format!("{line}: not base64 ({e})"))?; + PublicKey::try_from(bytes.as_slice()) + .map_err(|_| format!("{line}: not a 32-byte Ed25519 public key")) + }) + .collect() +} + +/// What a signature covers: the tag, then the checksum list. +pub fn message(tag: &str, sums: &[u8]) -> Vec { + let mut message = format!("horizon release {tag}\n").into_bytes(); + message.extend_from_slice(sums); + message +} + +/// A checksum list for `(file name, SHA-256 hex)` pairs, as `sha256sum` writes it. +pub fn sums_file(files: &[(String, String)]) -> String { + files + .iter() + .map(|(name, hex)| format!("{hex} {name}\n")) + .collect() +} + +/// The `(file name, SHA-256 hex)` pairs of a checksum list (` ` or ` *`). +pub fn parse_sums(text: &str) -> Result, String> { + text.lines() + .filter(|line| !line.trim().is_empty()) + .map(|line| { + let (hex, name) = line + .split_once(' ') + .ok_or_else(|| format!("{SUMS}: {line:?} is not ` `"))?; + let name = name.strip_prefix([' ', '*']).unwrap_or(name); + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) || name.is_empty() { + return Err(format!("{SUMS}: {line:?} is not ` `")); + } + Ok((name.to_string(), hex.to_ascii_lowercase())) + }) + .collect() +} + +/// Checks that one of `keys` signed `sums` for `tag`, and returns the list. +pub fn verify( + tag: &str, + sums: &[u8], + signature: &str, + keys: &[PublicKey], +) -> Result, String> { + if keys.is_empty() { + return Err( + "This build has no release key built in, so it can't check downloads: none are installed." + .into(), + ); + } + let message = message(tag, sums); + let signed = signature + .lines() + .filter_map(|line| STANDARD.decode(line.trim()).ok()) + .any(|signature| { + keys.iter().any(|key| { + UnparsedPublicKey::new(&ED25519, key) + .verify(&message, &signature) + .is_ok() + }) + }); + if !signed { + return Err(format!( + "{tag}'s signature doesn't match Horizon's release key, so it was not installed. \ + The download may have been tampered with: please report it on Discord or GitHub." + )); + } + let text = std::str::from_utf8(sums).map_err(|_| format!("{SUMS} is not text"))?; + parse_sums(text) +} + +/// The signed SHA-256 of `asset` in release `tag`, or why the download must be refused. +/// `sums` and `signature` are the release's SHA256SUMS and SHA256SUMS.sig, None when it has none. +pub fn signed_digest( + tag: &str, + asset: &str, + sums: Option<&[u8]>, + signature: Option<&str>, + keys: &[PublicKey], +) -> Result { + let (Some(sums), Some(signature)) = (sums, signature) else { + return Err(format!( + "{tag} is not signed, and Horizon installs only signed releases: pick a newer version." + )); + }; + verify(tag, sums, signature, keys)? + .into_iter() + .find(|(name, _)| name == asset) + .map(|(_, hex)| hex) + .ok_or_else(|| { + format!("{asset} is not in {tag}'s signed checksums, so it was not installed.") + }) +} + +/// Whether a downloaded file's SHA-256 (`got`) is the signed one. +pub fn check(asset: &str, expected: &str, got: &str) -> Result<(), String> { + if expected.eq_ignore_ascii_case(got) { + Ok(()) + } else { + Err(format!( + "{asset} doesn't match its signed checksum (corrupted or tampered with), so it was \ + not installed. Try again." + )) + } +} + +/// SHA-256 over data that arrives in pieces (a download). +pub struct Sha256(ring::digest::Context); + +impl Default for Sha256 { + fn default() -> Self { + Self(ring::digest::Context::new(&ring::digest::SHA256)) + } +} + +impl Sha256 { + pub fn update(&mut self, bytes: &[u8]) { + self.0.update(bytes); + } + + pub fn hex(self) -> String { + self.0 + .finish() + .as_ref() + .iter() + .map(|b| format!("{b:02x}")) + .collect() + } +} + +/// The SHA-256 of `bytes`, in hex. +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut hash = Sha256::default(); + hash.update(bytes); + hash.hex() +} + +/// A private signing key: `keygen` makes them, and tests sign with them (releases are signed by +/// OpenSSL in tools/ci/sign_release.sh, from the same PKCS#8 document). +pub struct SigningKey(Ed25519KeyPair); + +impl SigningKey { + /// A new key, and its PKCS#8 document in base64 (what the secret holds). + /// + /// The document is PKCS#8 v1 (RFC 8410: the 32-byte seed alone), which every OpenSSL 3 reads; + /// ring makes v2 (with the public key too), which OpenSSL 3.0, Ubuntu's, refuses. + pub fn generate() -> Result<(Self, String), String> { + const V2_PREFIX: [u8; 16] = [ + 0x30, 0x51, 0x02, 0x01, 0x01, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, + 0x04, 0x20, + ]; + const V1_PREFIX: [u8; 16] = [ + 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, + 0x04, 0x20, + ]; + let v2 = Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()) + .map_err(|_| "no randomness to make a key with".to_string())?; + let seed = v2 + .as_ref() + .strip_prefix(&V2_PREFIX) + .and_then(|rest| rest.get(..32)) + .ok_or("ring's key document has an unexpected layout")?; + let v1 = [&V1_PREFIX[..], seed].concat(); + let key = Ed25519KeyPair::from_pkcs8_maybe_unchecked(&v1) + .map_err(|_| "the new key doesn't parse".to_string())?; + let same = Ed25519KeyPair::from_pkcs8(v2.as_ref()) + .is_ok_and(|k| k.public_key().as_ref() == key.public_key().as_ref()); + if !same { + return Err("the new key's two forms disagree".into()); + } + Ok((Self(key), STANDARD.encode(&v1))) + } + + /// The key a secret holds (base64 PKCS#8). The error never quotes the secret. + pub fn from_base64(text: &str) -> Result { + let document = STANDARD + .decode(text.trim()) + .map_err(|_| "the signing key is not base64".to_string())?; + Ed25519KeyPair::from_pkcs8_maybe_unchecked(&document) + .map(Self) + .map_err(|_| "the signing key is not an Ed25519 PKCS#8 key".to_string()) + } + + pub fn public(&self) -> PublicKey { + PublicKey::try_from(self.0.public_key().as_ref()).expect("Ed25519 public keys are 32 bytes") + } + + /// The public key in base64, as release-keys.txt lists it. + pub fn public_base64(&self) -> String { + STANDARD.encode(self.public()) + } + + /// A signature line for SHA256SUMS.sig. + pub fn sign(&self, tag: &str, sums: &[u8]) -> String { + STANDARD.encode(self.0.sign(&message(tag, sums)).as_ref()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn signed(tag: &str) -> (SigningKey, String, String) { + let (key, _) = SigningKey::generate().unwrap(); + let sums = sums_file(&[ + ("horizon-linux-x86_64.tar.gz".into(), sha256_hex(b"linux")), + ("horizon-windows-x64.zip".into(), sha256_hex(b"windows")), + ]); + let signature = key.sign(tag, sums.as_bytes()) + "\n"; + (key, sums, signature) + } + + #[test] + fn the_built_in_keys_file_parses() { + assert!(parse_keys(KEYS).is_ok()); + } + + #[test] + fn a_signed_release_gives_its_digests() { + let (key, sums, signature) = signed("v2026.10.19"); + let digest = signed_digest( + "v2026.10.19", + "horizon-windows-x64.zip", + Some(sums.as_bytes()), + Some(&signature), + &[key.public()], + ); + assert_eq!(digest, Ok(sha256_hex(b"windows"))); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"windows")).is_ok()); + assert!(check("x", &sha256_hex(b"windows"), &sha256_hex(b"linux")).is_err()); + } + + #[test] + fn tampering_is_refused() { + let (key, sums, signature) = signed("v2026.10.19"); + let keys = [key.public()]; + // Another tag: an old signed list replayed for a new release. + assert!(verify("v2026.10.20", sums.as_bytes(), &signature, &keys).is_err()); + // A changed checksum. + let changed = sums.replacen(&sha256_hex(b"linux"), &sha256_hex(b"evil"), 1); + assert!(verify("v2026.10.19", changed.as_bytes(), &signature, &keys).is_err()); + // Another key. + let (other, _) = SigningKey::generate().unwrap(); + assert!( + verify( + "v2026.10.19", + sums.as_bytes(), + &signature, + &[other.public()] + ) + .is_err() + ); + // No signature, no keys, an asset that isn't listed. + let none = signed_digest("v2026.10.19", "a", None, None, &keys).unwrap_err(); + assert!(none.contains("not signed"), "{none}"); + assert!(verify("v2026.10.19", sums.as_bytes(), &signature, &[]).is_err()); + let missing = signed_digest( + "v2026.10.19", + "horizon-macos-arm64.zip", + Some(sums.as_bytes()), + Some(&signature), + &keys, + ); + assert!(missing.unwrap_err().contains("not in")); + } + + #[test] + fn any_line_signed_by_any_trusted_key_passes() { + // While rotating, releases carry one signature per key and launchers trust one or both. + let (old, sums, old_line) = signed("v1"); + let (new, _) = SigningKey::generate().unwrap(); + let both = format!("{old_line}{}\n", new.sign("v1", sums.as_bytes())); + assert!(verify("v1", sums.as_bytes(), &both, &[old.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), &both, &[new.public()]).is_ok()); + assert!(verify("v1", sums.as_bytes(), "garbage\n\n", &[old.public()]).is_err()); + } + + #[test] + fn keys_round_trip_through_their_text_forms() { + let (key, secret) = SigningKey::generate().unwrap(); + // PKCS#8 v1 (version 0, the seed alone): what OpenSSL 3.0 reads. + let document = STANDARD.decode(&secret).unwrap(); + assert_eq!((document.len(), document[4]), (48, 0)); + let again = SigningKey::from_base64(&format!("{secret}\n")).unwrap(); + assert_eq!(again.public(), key.public()); + assert_eq!( + parse_keys(&format!("# comment\n\n{}\n", key.public_base64())), + Ok(vec![key.public()]) + ); + assert!(parse_keys("AAAA\n").is_err()); + let error = SigningKey::from_base64("bm90IGEga2V5").err().unwrap(); + assert!(!error.contains("bm90")); + } + + #[test] + fn checksum_lists_read_both_sha256sum_forms() { + let hex = sha256_hex(b"x"); + let list = + parse_sums(&format!("{hex} a.zip\n{} *b.tar.gz\n", hex.to_uppercase())).unwrap(); + assert_eq!( + list, + [("a.zip".into(), hex.clone()), ("b.tar.gz".into(), hex)] + ); + assert!(parse_sums("nothex a.zip\n").is_err()); + } +} diff --git a/crates/horizon-release-sign/src/main.rs b/crates/horizon-release-sign/src/main.rs new file mode 100644 index 000000000..108b5192a --- /dev/null +++ b/crates/horizon-release-sign/src/main.rs @@ -0,0 +1,139 @@ +//! horizon-release-sign: checks a release's signed checksums, and makes new keys +//! (docs/release-flow.md, "Signed checksums"). The signing itself is tools/ci/sign_release.sh: the +//! job that holds the private key runs only the runner's sha256sum and OpenSSL, no code from the +//! repository. +//! +//! horizon-release-sign verify --tag v2026.10.19 [--key ] [--publishing] +//! horizon-release-sign keygen --public-out key.pub | gh secret set RELEASE_SIGNING_KEY --env release +//! +//! `verify` checks SHA256SUMS.sig and every file SHA256SUMS lists with the keys built in from +//! release-keys.txt (or `--key`), as the launcher does. With `--publishing` (release.yml) a release +//! may go out unsigned, or signed with a key nobody can check yet, only while release-keys.txt +//! lists no key; once it lists one, anything launchers would refuse fails the release. + +use horizon_release_sign::{SIGNATURE, SUMS, Sha256, SigningKey, parse_keys, trusted_keys, verify}; +use std::io::{IsTerminal, Read, Write}; +use std::path::{Path, PathBuf}; +use std::process::ExitCode; + +fn main() -> ExitCode { + let args: Vec = std::env::args().skip(1).collect(); + let result = match args.first().map(String::as_str) { + Some("verify") => check_folder(&args[1..]), + Some("keygen") => keygen(&args[1..]), + _ => Err( + "usage: horizon-release-sign verify --tag [--key ]... [--publishing] \ + | keygen --public-out " + .into(), + ), + }; + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("horizon-release-sign: {e}"); + ExitCode::FAILURE + } + } +} + +/// The values of every `--name value` in `args`, and the other arguments. +fn options(args: &[String], name: &str) -> (Vec, Vec) { + let mut values = Vec::new(); + let mut rest = Vec::new(); + let mut it = args.iter(); + while let Some(arg) = it.next() { + if arg == name { + values.extend(it.next().cloned()); + } else { + rest.push(arg.clone()); + } + } + (values, rest) +} + +fn tag_of(args: &[String]) -> Result<(String, Vec), String> { + let (tags, rest) = options(args, "--tag"); + let tag = tags.into_iter().next().ok_or("--tag is needed")?; + Ok((tag, rest)) +} + +fn file_hash(path: &Path) -> Result { + let mut file = std::fs::File::open(path).map_err(|e| format!("{}: {e}", path.display()))?; + let mut hash = Sha256::default(); + let mut buffer = vec![0; 1 << 16]; + loop { + let n = file + .read(&mut buffer) + .map_err(|e| format!("{}: {e}", path.display()))?; + if n == 0 { + return Ok(hash.hex()); + } + hash.update(&buffer[..n]); + } +} + +/// Checks a folder holding a release's assets, as the launcher does. +fn check_folder(args: &[String]) -> Result<(), String> { + let (tag, rest) = tag_of(args)?; + let (keys, rest) = options(&rest, "--key"); + let publishing = rest.iter().any(|a| a == "--publishing"); + let folder = PathBuf::from( + rest.iter() + .find(|a| *a != "--publishing") + .ok_or("verify needs the release's folder")?, + ); + let keys = if keys.is_empty() { + trusted_keys() + } else { + parse_keys(&keys.join("\n"))? + }; + let sums = std::fs::read(folder.join(SUMS)).map_err(|e| format!("{SUMS}: {e}"))?; + let listed = match std::fs::read_to_string(folder.join(SIGNATURE)) { + Ok(signature) if !keys.is_empty() => verify(&tag, &sums, &signature, &keys)?, + Ok(_) if publishing => { + println!( + "::warning::{tag}: signed, but release-keys.txt lists no key yet, so launchers can't check it" + ); + horizon_release_sign::parse_sums(&String::from_utf8_lossy(&sums))? + } + Err(_) if publishing && keys.is_empty() => { + println!( + "::warning::{tag}: published with {SUMS} but unsigned: release-keys.txt lists no key yet" + ); + horizon_release_sign::parse_sums(&String::from_utf8_lossy(&sums))? + } + Ok(_) => return Err("no key to check the signature with".into()), + Err(_) => { + return Err(format!( + "{tag} has no {SIGNATURE}: launchers would refuse it (is the release environment's \ + RELEASE_SIGNING_KEY set?)" + )); + } + }; + for (name, hex) in &listed { + horizon_release_sign::check(name, hex, &file_hash(&folder.join(name))?)?; + } + println!("{tag}: {} files match {SUMS}", listed.len()); + Ok(()) +} + +/// Prints a new private key to stdout, which must be a pipe (into `gh secret set`), never a +/// terminal, and writes its public key to `--public-out`. +fn keygen(args: &[String]) -> Result<(), String> { + let (public_out, _) = options(args, "--public-out"); + let public_out = public_out + .into_iter() + .next() + .ok_or("keygen needs --public-out ")?; + if std::io::stdout().is_terminal() { + return Err( + "keygen writes the private key to its output: pipe it into `gh secret set`".into(), + ); + } + let (key, secret) = SigningKey::generate()?; + std::fs::write(&public_out, key.public_base64() + "\n").map_err(|e| e.to_string())?; + let mut out = std::io::stdout().lock(); + out.write_all(secret.as_bytes()) + .and_then(|()| out.flush()) + .map_err(|e| e.to_string()) +} diff --git a/crates/horizon-release-sign/tests/cli.rs b/crates/horizon-release-sign/tests/cli.rs new file mode 100644 index 000000000..8e9d5f047 --- /dev/null +++ b/crates/horizon-release-sign/tests/cli.rs @@ -0,0 +1,182 @@ +//! The release steps as release.yml runs them: `sums`, tools/ci/sign_release.sh (OpenSSL), `verify`. +use horizon_release_sign::{SIGNATURE, SUMS, SigningKey, trusted_keys}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const TAG: &str = "v2026.10.19"; + +fn folder(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!( + "horizon-release-sign-{name}-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("horizon-linux-x86_64.tar.gz"), b"linux build").unwrap(); + std::fs::write(dir.join("horizon-windows-x64.zip"), b"windows build").unwrap(); + let sums = horizon_release_sign::sums_file(&[ + ( + "horizon-linux-x86_64.tar.gz".into(), + horizon_release_sign::sha256_hex(b"linux build"), + ), + ( + "horizon-windows-x64.zip".into(), + horizon_release_sign::sha256_hex(b"windows build"), + ), + ]); + std::fs::write(dir.join(SUMS), sums).unwrap(); + dir +} + +fn tool(args: &[&str], paths: &[&Path]) -> Output { + Command::new(env!("CARGO_BIN_EXE_horizon-release-sign")) + .args(args) + .args(paths) + .output() + .unwrap() +} + +fn verify(dir: &Path, extra: &[&str]) -> Output { + let mut args = vec!["verify", "--tag", TAG]; + args.extend(extra); + tool(&args, &[dir]) +} + +/// An OpenSSL 3 (the runner's), or None on a machine without one (macOS ships LibreSSL). +fn openssl() -> Option { + [ + "openssl", + "/opt/homebrew/opt/openssl@3/bin/openssl", + "/usr/local/opt/openssl@3/bin/openssl", + ] + .into_iter() + .find(|o| { + Command::new(o) + .arg("version") + .output() + .is_ok_and(|v| v.stdout.starts_with(b"OpenSSL 3")) + }) + .map(String::from) +} + +fn sign_script(dir: &Path, env: &[(&str, &str)]) -> Output { + let script = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tools/ci/sign_release.sh"); + let mut cmd = Command::new("bash"); + cmd.arg(script) + .arg(TAG) + .arg(dir.join("horizon-linux-x86_64.tar.gz")) + .arg(dir.join("horizon-windows-x64.zip")) + .env_remove("RELEASE_SIGNING_KEY") + .env_remove("RELEASE_SIGNING_KEY_NEXT"); + cmd.env("OPENSSL", openssl().unwrap()); + for (k, v) in env { + cmd.env(k, v); + } + cmd.output().unwrap() +} + +#[test] +fn a_signature_made_like_openssls_checks_and_tampering_fails() { + let dir = folder("lib"); + let (key, _) = SigningKey::generate().unwrap(); + let sums = std::fs::read(dir.join(SUMS)).unwrap(); + std::fs::write(dir.join(SIGNATURE), key.sign(TAG, &sums) + "\n").unwrap(); + assert!( + verify(&dir, &["--key", &key.public_base64()]) + .status + .success() + ); + std::fs::write(dir.join("horizon-windows-x64.zip"), b"tampered").unwrap(); + let out = verify(&dir, &["--key", &key.public_base64()]); + assert!(!out.status.success()); + assert!(String::from_utf8_lossy(&out.stderr).contains("doesn't match its signed checksum")); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn unsigned_releases_go_out_only_until_a_key_is_listed() { + let dir = folder("unsigned"); + assert_eq!( + verify(&dir, &["--publishing"]).status.success(), + trusted_keys().is_empty() + ); + assert!(!verify(&dir, &[]).status.success()); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn the_openssl_script_signs_what_the_launcher_checks() { + if openssl().is_none() { + eprintln!("no OpenSSL 3 here: tools/ci/sign_release.sh is tested on Linux"); + return; + } + // A dry run: a throwaway key, its public key for the check. + let dir = folder("ephemeral"); + std::fs::remove_file(dir.join(SUMS)).unwrap(); // the script writes its own + let out = sign_script(&dir, &[("EPHEMERAL", "yes")]); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let key = std::fs::read_to_string(dir.join("ephemeral.pub")).unwrap(); + assert!(verify(&dir, &["--key", key.trim()]).status.success()); + std::fs::remove_dir_all(dir).unwrap(); + + // A release: both secrets (rotating), as keygen makes them; each signature line checks alone. + let dir = folder("secret"); + let (old, old_secret) = SigningKey::generate().unwrap(); + let (new, new_secret) = SigningKey::generate().unwrap(); + let out = sign_script( + &dir, + &[ + ("RELEASE_SIGNING_KEY", &old_secret), + ("RELEASE_SIGNING_KEY_NEXT", &new_secret), + ], + ); + let printed = format!( + "{}{}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ); + assert!(out.status.success(), "{printed}"); + assert!(!printed.contains(&old_secret) && !printed.contains(&new_secret)); + assert_eq!( + std::fs::read_to_string(dir.join(SIGNATURE)) + .unwrap() + .lines() + .count(), + 2 + ); + assert!( + verify(&dir, &["--key", &old.public_base64()]) + .status + .success() + ); + assert!( + verify(&dir, &["--key", &new.public_base64()]) + .status + .success() + ); + let (other, _) = SigningKey::generate().unwrap(); + assert!( + !verify(&dir, &["--key", &other.public_base64()]) + .status + .success() + ); + std::fs::remove_dir_all(dir).unwrap(); +} + +#[test] +fn keygen_writes_the_secret_to_a_pipe_and_the_public_key_to_a_file() { + let dir = folder("keygen"); + let public = dir.join("key.pub"); + let out = tool(&["keygen", "--public-out"], &[&public]); + assert!(out.status.success()); + let key = SigningKey::from_base64(&String::from_utf8(out.stdout).unwrap()).unwrap(); + assert_eq!( + std::fs::read_to_string(&public).unwrap().trim(), + key.public_base64() + ); + std::fs::remove_dir_all(dir).unwrap(); +} diff --git a/crates/horizon-server/src/cli.rs b/crates/horizon-server/src/cli.rs index 69a192105..af7c72788 100644 --- a/crates/horizon-server/src/cli.rs +++ b/crates/horizon-server/src/cli.rs @@ -303,9 +303,24 @@ pub fn backup(dir: &Path, name: Option<&str>) -> Result<(), String> { Ok(()) } -/// `backups`: the backups, newest first. -pub fn backups(dir: &Path) -> Result<(), String> { +/// `backups [--json]`: the backups, newest first. +pub fn backups(dir: &Path, as_json: bool) -> Result<(), String> { let all = backup::list(dir); + if as_json { + let list: Vec = all + .iter() + .map(|b| { + let modified = std::fs::metadata(dir.join(backup::DIR).join(&b.name)) + .and_then(|m| m.modified()) + .ok() + .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|d| d.as_secs()); + json!({ "name": b.name, "bytes": b.bytes, "modified": modified }) + }) + .collect(); + println!("{}", Value::Array(list)); + return Ok(()); + } if all.is_empty() { println!("No backups yet: `horizon-server backup` makes one."); } diff --git a/crates/horizon-server/src/config.rs b/crates/horizon-server/src/config.rs index 3c389f858..0a66b6fdf 100644 --- a/crates/horizon-server/src/config.rs +++ b/crates/horizon-server/src/config.rs @@ -49,6 +49,9 @@ restart_on_crash = true every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off keep = 12 # automatic backups kept (backups made by hand are never deleted) +[updates] +keep = 1 # other releases kept by updates, besides the one in use and the one rollback goes to + [panel] bind = "127.0.0.1:8130" # the web panel: this computer only, or a tailnet address (100.x); "" turns it off allow_public = false # true lets bind be any address; never put the panel on the open internet @@ -86,6 +89,8 @@ pub struct Config { #[serde(default)] pub backups: Backups, #[serde(default)] + pub updates: Updates, + #[serde(default)] pub panel: Panel, } @@ -181,6 +186,20 @@ pub struct Backups { pub keep: u32, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct Updates { + /// Releases kept in `releases/` after an update besides the one in use and the one `rollback` goes + /// back to (crate::update::Install::prune). + pub keep: u32, +} + +impl Default for Updates { + fn default() -> Self { + Self { keep: 1 } + } +} + impl Default for Server { fn default() -> Self { Self { @@ -378,6 +397,7 @@ pub fn render(config: &Config) -> String { ("engine", "restart_on_crash"), ("backups", "every"), ("backups", "keep"), + ("updates", "keep"), ("panel", "bind"), ("panel", "allow_public"), ] { @@ -426,10 +446,18 @@ pub fn sync_back(dir: &Path, written: &[(String, String)]) -> Result /// Sets one typed setting in `server.toml` (`whitelist on`), keeping the owner's comments. pub fn update(dir: &Path, section: &str, field: &str, value: toml::Value) -> Result<(), String> { + update_all(dir, &[(section.to_owned(), field.to_owned(), value)]) +} + +/// Sets settings in `server.toml`, keeping the owner's comments; nothing is written unless the result is +/// a valid configuration. +pub fn update_all(dir: &Path, changes: &[(String, String, toml::Value)]) -> Result<(), String> { let path = dir.join(FILE); let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; let mut doc: toml_edit::DocumentMut = text.parse().map_err(|e| format!("{e}"))?; - set(&mut doc, section, field, &value); + for (section, field, value) in changes { + set(&mut doc, section, field, value); + } let updated = doc.to_string(); Config::parse(&updated)?; std::fs::write(&path, updated).map_err(|e| e.to_string()) @@ -483,7 +511,7 @@ fn typed_value(text: &str, like: &toml::Value) -> Option { } /// A server.properties value for `[properties]`: a boolean or a number when it reads back the same. -fn loose_value(text: &str) -> toml::Value { +pub fn loose_value(text: &str) -> toml::Value { match text { "true" => toml::Value::Boolean(true), "false" => toml::Value::Boolean(false), diff --git a/crates/horizon-server/src/lists.rs b/crates/horizon-server/src/lists.rs index a6c466666..1a44251d3 100644 --- a/crates/horizon-server/src/lists.rs +++ b/crates/horizon-server/src/lists.rs @@ -1,6 +1,11 @@ //! `op`, `deop` and `whitelist`. While the server runs, the game owns the lists: the command goes to its //! console. While it is stopped, they edit vanilla's files with the code the game reads them with //! (horizon-server-files) and answer with vanilla's console messages. +//! +//! One exception: `whitelist add` on a running offline server. The game asks Mojang for the name first, as +//! vanilla does, so a name someone owns gets that account's UUID, and the player, who joins under the +//! offline UUID, is still refused. There the offline entry is written to whitelist.json and the game +//! reloads it (`whitelist reload`), as it would be written while the server is stopped. use crate::{config, supervisor}; use horizon_server_files::user_lists::{NameAndId, OpEntry, OpList, WhiteEntry, WhiteList}; @@ -10,6 +15,12 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { let config = config::Config::load(dir)?; // Holding the folder's lock keeps the server from starting halfway through. let Ok(_lock) = supervisor::lock(dir) else { + if let ("whitelist", [add, name]) = (command, args) + && add == "add" + && !config.server.online_mode + { + return add_offline(dir, name); + } let mut words = vec![command.to_owned()]; words.extend_from_slice(args); return crate::cli::command(dir, &words); @@ -99,6 +110,26 @@ pub fn run(dir: &Path, command: &str, args: &[String]) -> Result<(), String> { Ok(()) } +/// `whitelist add` on a running offline server: the offline entry, then the game reloads the list. +fn add_offline(dir: &Path, name: &str) -> Result<(), String> { + if crate::api::Client::open(dir)?.is_none() { + return Err(format!("no server is running in {}", dir.display())); + } + let user = account(name, false)?; + let mut white = load(WhiteList::new(dir.join("whitelist.json")))?; + if white.contains(&user) { + println!("Player is already whitelisted"); + return Ok(()); + } + white.add(WhiteEntry { user }); + white + .save() + .map_err(|e| format!("{}: {e}", white.file.display()))?; + crate::cli::command(dir, &["whitelist".to_owned(), "reload".to_owned()])?; + println!("Added {name} to the whitelist"); + Ok(()) +} + /// The profile a running server would store for `name`: the offline one, or in online mode the account the /// services know by that name. pub fn account(name: &str, online: bool) -> Result { @@ -161,12 +192,19 @@ mod tests { // A running server owns the lists: without its API, nothing changes. let lock = supervisor::lock(&dir).unwrap(); assert!(run(&dir, "op", &s(&["Alex"])).is_err()); + config::update(&dir, "server", "online_mode", toml::Value::Boolean(false)).unwrap(); + assert!(run(&dir, "whitelist", &s(&["add", "Kai"])).is_err()); drop(lock); assert!( !std::fs::read_to_string(dir.join("ops.json")) .unwrap() .contains("Alex") ); + assert!( + !std::fs::read_to_string(dir.join("whitelist.json")) + .unwrap() + .contains("Kai") + ); std::fs::remove_dir_all(&dir).unwrap(); } } diff --git a/crates/horizon-server/src/main.rs b/crates/horizon-server/src/main.rs index 8fda74fba..627961d81 100644 --- a/crates/horizon-server/src/main.rs +++ b/crates/horizon-server/src/main.rs @@ -11,6 +11,7 @@ mod init; mod lists; mod panel; mod service; +mod settings; mod signals; mod supervisor; mod update; @@ -37,7 +38,8 @@ Usage: horizon-server [--dir DIR] The last N lines of the log (default 50); -f follows it backup [NAME] Zip the world and the settings into backups/ (a running server saves first and stays up) - backups List the backups + backups [--json] + List the backups restore BACKUP [--yes] Put a backup's world in place (the current one is kept in backups/); a running server restarts with it @@ -46,11 +48,17 @@ Usage: horizon-server [--dir DIR] with sudo), a launchd agent on macOS, a task at logon on Windows panel A one-time login link for the web panel ([panel] in server.toml; 127.0.0.1:8130 by default) - update [--check] [--version TAG] [--timeout SECONDS] + update [--check [--json]] [--version TAG] [--timeout SECONDS] Install the newest release (checked against GitHub's SHA-256), back up the world and restart on it; goes back by itself if the game isn't up within the timeout (300 s). --archive FILE --version NAME installs an archive you have rollback Back to the release used before the update + config [--json] + The settings in server.toml + config set KEY=VALUE... [--json] + Change settings (for example world.difficulty=hard server.max_players=10), checked first; + a running server takes the difficulty, default game mode and whitelist at once, the rest + at its next start import FILE Write server.toml from a vanilla server.properties op NAME, deop NAME whitelist on|off|list, whitelist add|remove NAME @@ -91,13 +99,14 @@ fn main() -> ExitCode { Some("logs") => logs(&dir, &args[1..]), Some("panel") => cli::panel(&dir), Some("backup") => cli::backup(&dir, args.get(1).map(String::as_str)), - Some("backups") => cli::backups(&dir), + Some("backups") => cli::backups(&dir, args[1..].iter().any(|a| a == "--json")), Some("service") => service::command(&dir, &args[1..]), Some("restore") => match args.get(1) { Some(name) => cli::restore(&dir, name, args[2..].iter().any(|a| a == "--yes")), None => Err("restore needs a backup (`horizon-server backups` lists them)".into()), }, Some("import") => import(&dir, &args[1..]), + Some("config") => settings::command(&dir, &args[1..]), Some("update") => update::command(&dir, &args[1..]), Some("rollback") => update::rollback(&dir, &args[1..]), Some(command @ ("op" | "deop" | "whitelist")) => lists::run(&dir, command, &args[1..]), diff --git a/crates/horizon-server/src/settings.rs b/crates/horizon-server/src/settings.rs new file mode 100644 index 000000000..ed0ec912b --- /dev/null +++ b/crates/horizon-server/src/settings.rs @@ -0,0 +1,330 @@ +//! `horizon-server config`: read server.toml's settings, and change them the way the server checks them +//! (docs/server.md, section 4). A running server takes what vanilla can change live through its console +//! (difficulty, the default game mode, the whitelist) at once; the rest applies at the next start. + +use crate::{api::Client, config}; +use serde_json::{Value, json}; +use std::path::Path; + +/// `config [--json]` and `config set KEY=VALUE... [--json]`. +pub fn command(dir: &Path, args: &[String]) -> Result<(), String> { + let as_json = args.iter().any(|a| a == "--json"); + let args: Vec<&str> = args + .iter() + .map(String::as_str) + .filter(|a| *a != "--json") + .collect(); + match args.as_slice() { + [] => show(dir, as_json), + ["set", changes @ ..] if !changes.is_empty() => { + let outcome = set(dir, changes)?; + if as_json { + println!("{}", outcome.to_json()); + } else { + print!("{}", outcome.describe()); + } + Ok(()) + } + _ => Err( + "config takes no arguments, or `set KEY=VALUE...` (for example: config set world.difficulty=hard)" + .into(), + ), + } +} + +fn show(dir: &Path, as_json: bool) -> Result<(), String> { + let cfg = config::Config::load(dir)?; + let table = toml::Table::try_from(&cfg).map_err(|e| e.to_string())?; + if as_json { + println!( + "{}", + serde_json::to_value(&table).map_err(|e| e.to_string())? + ); + return Ok(()); + } + for (section, values) in &table { + for (key, value) in values.as_table().into_iter().flatten() { + println!("{section}.{key} = {value}"); + } + } + Ok(()) +} + +/// What `config set` did. +#[derive(Debug, Default, PartialEq)] +pub struct Outcome { + /// Every setting written to server.toml. + pub saved: Vec, + /// Those the running server took at once. + pub applied: Vec, + /// Those that wait for the game's next start, while it runs. + pub restart: Vec, + pub running: bool, +} + +impl Outcome { + fn to_json(&self) -> Value { + json!({ + "saved": self.saved, + "applied": self.applied, + "restart": self.restart, + "running": self.running, + }) + } + + fn describe(&self) -> String { + if !self.running { + return format!( + "Saved {}: the server uses them from its next start.\n", + self.saved.join(", ") + ); + } + let mut out = String::new(); + if !self.applied.is_empty() { + out += &format!("Applied now: {}\n", self.applied.join(", ")); + } + if !self.restart.is_empty() { + out += &format!( + "Saved; restart the server to apply: {} (`horizon-server restart`)\n", + self.restart.join(", ") + ); + } + out + } +} + +/// One `KEY=VALUE`: the section, the field and the value as server.toml types it. +pub fn parse_change( + current: &toml::Table, + change: &str, +) -> Result<(String, String, toml::Value), String> { + let (key, text) = change + .split_once('=') + .ok_or_else(|| format!("{change:?}: write KEY=VALUE, like world.difficulty=hard"))?; + let (section, field) = key + .trim() + .split_once('.') + .ok_or_else(|| format!("{key:?}: name a setting as section.name, like server.port"))?; + let text = text.trim(); + let value = if section == "properties" { + config::loose_value(text) + } else { + let like = current + .get(section) + .and_then(|s| s.get(field)) + .ok_or_else(|| { + format!("{key} is not a setting (`horizon-server config` lists them)") + })?; + match like { + toml::Value::Boolean(_) => toml::Value::Boolean(match text { + "true" | "on" | "yes" => true, + "false" | "off" | "no" => false, + _ => return Err(format!("{key} is on or off: use true or false")), + }), + toml::Value::Integer(_) => toml::Value::Integer( + text.parse() + .map_err(|_| format!("{key} is a number, not {text:?}"))?, + ), + _ => toml::Value::String(text.to_owned()), + } + }; + if let (Some(range), toml::Value::Integer(n)) = (range(section, field), &value) + && !range.contains(n) + { + return Err(format!( + "{key} is {n}: use {} to {}", + range.start(), + range.end() + )); + } + Ok((section.to_owned(), field.to_owned(), value)) +} + +/// The values vanilla uses for the numbers it clamps (`ChunkMap` keeps both distances within 2 to 32). +fn range(section: &str, field: &str) -> Option> { + match (section, field) { + ("server", "view_distance" | "simulation_distance") => Some(2..=32), + ("server", "max_players") => Some(1..=1000), + ("backups", "keep") => Some(1..=1000), + _ => None, + } +} + +/// The console command that applies a setting to a running game, if vanilla has one; `Some("")` for the +/// settings the supervisor itself reads every time (backups, updates). +pub fn live_command(section: &str, field: &str, value: &toml::Value) -> Option { + let text = match value { + toml::Value::String(s) => s.clone(), + other => other.to_string(), + }; + match (section, field) { + ("world", "difficulty") => Some(format!("difficulty {text}")), + ("world", "game_mode") => Some(format!("defaultgamemode {text}")), + ("server", "whitelist") => Some(format!( + "whitelist {}", + if value.as_bool() == Some(true) { + "on" + } else { + "off" + } + )), + ("backups" | "updates", _) => Some(String::new()), + _ => None, + } +} + +pub fn set(dir: &Path, changes: &[&str]) -> Result { + let current = toml::Table::try_from(config::Config::load(dir)?).map_err(|e| e.to_string())?; + let parsed = changes + .iter() + .map(|c| parse_change(¤t, c)) + .collect::, _>>()?; + config::update_all(dir, &parsed)?; + let mut outcome = Outcome { + saved: parsed.iter().map(|(s, f, _)| format!("{s}.{f}")).collect(), + ..Outcome::default() + }; + let Some(client) = Client::open(dir)? else { + return Ok(outcome); + }; + outcome.running = true; + let up = client + .call("GET", "/api/v1/status", None) + .is_ok_and(|s| s["phase"] == "running"); + for (section, field, value) in &parsed { + let key = format!("{section}.{field}"); + let unchanged = current.get(section).and_then(|s| s.get(field)) == Some(value); + match live_command(section, field, value) { + _ if unchanged => {} + Some(line) if line.is_empty() => outcome.applied.push(key), + Some(line) + if up + && client + .call("POST", "/api/v1/command", Some(&json!({ "line": line }))) + .is_ok() => + { + outcome.applied.push(key) + } + _ => outcome.restart.push(key), + } + } + Ok(outcome) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn table() -> toml::Table { + toml::Table::try_from(config::Config::default()).unwrap() + } + + #[test] + fn changes_take_the_settings_types() { + let t = table(); + assert_eq!( + parse_change(&t, "server.max_players=8").unwrap(), + ( + "server".into(), + "max_players".into(), + toml::Value::Integer(8) + ) + ); + assert_eq!( + parse_change(&t, "server.whitelist=off").unwrap().2, + toml::Value::Boolean(false) + ); + assert_eq!( + parse_change(&t, "server.motd= Friends only ").unwrap().2, + toml::Value::String("Friends only".into()) + ); + assert_eq!( + parse_change(&t, "properties.spawn-protection=0").unwrap(), + ( + "properties".into(), + "spawn-protection".into(), + toml::Value::Integer(0) + ) + ); + for (bad, says) in [ + ("server.view_distance=40", "use 2 to 32"), + ("server.max_players=many", "is a number"), + ("server.online_mode=maybe", "use true or false"), + ("server.colour=red", "is not a setting"), + ("difficulty=hard", "section.name"), + ("world.difficulty", "KEY=VALUE"), + ] { + let e = parse_change(&t, bad).unwrap_err(); + assert!(e.contains(says), "{bad}: {e}"); + } + } + + #[test] + fn vanilla_changes_these_live() { + let s = |v: &str| toml::Value::String(v.into()); + assert_eq!( + live_command("world", "difficulty", &s("hard")).as_deref(), + Some("difficulty hard") + ); + assert_eq!( + live_command("world", "game_mode", &s("creative")).as_deref(), + Some("defaultgamemode creative") + ); + assert_eq!( + live_command("server", "whitelist", &toml::Value::Boolean(false)).as_deref(), + Some("whitelist off") + ); + assert_eq!( + live_command("backups", "every", &s("1h")).as_deref(), + Some("") + ); + assert_eq!( + live_command("server", "view_distance", &toml::Value::Integer(8)), + None + ); + } + + #[test] + fn a_stopped_server_saves_and_keeps_comments() { + let dir = + std::env::temp_dir().join(format!("horizon-server-config-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join(config::FILE), config::TEMPLATE).unwrap(); + let outcome = set( + &dir, + &[ + "world.difficulty=hard", + "server.max_players=5", + "backups.every=0", + ], + ) + .unwrap(); + assert_eq!( + outcome, + Outcome { + saved: vec![ + "world.difficulty".into(), + "server.max_players".into(), + "backups.every".into() + ], + ..Outcome::default() + } + ); + let text = std::fs::read_to_string(dir.join(config::FILE)).unwrap(); + assert!( + text.contains("difficulty = \"hard\" # peaceful, easy, normal or hard"), + "{text}" + ); + let cfg = config::Config::load(&dir).unwrap(); + assert_eq!( + (cfg.server.max_players, cfg.backups.every.as_str()), + (5, "0") + ); + // Checked as the server checks it: nothing is written. + assert!(set(&dir, &["world.difficulty=impossible"]).is_err()); + assert!(set(&dir, &["world.name=a/b", "server.port=1"]).is_err()); + assert_eq!(config::Config::load(&dir).unwrap(), cfg); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/horizon-server/src/supervisor.rs b/crates/horizon-server/src/supervisor.rs index 1cd36e83e..4de011362 100644 --- a/crates/horizon-server/src/supervisor.rs +++ b/crates/horizon-server/src/supervisor.rs @@ -80,6 +80,8 @@ struct Watch { backup: String, timeout: Duration, deadline: Instant, + /// `updates.keep`: the other releases kept once the game is up. + keep: u32, } pub fn run(dir: &Path) -> Result<(), String> { @@ -315,9 +317,24 @@ fn switch( backup, timeout, deadline: Instant::now() + timeout, + keep: config.updates.keep, }) } +/// The game is up on the release switched to: the update is done, and the old releases beyond the ones +/// kept are deleted. +fn came_up(shared: &Shared, w: &Watch) { + let mut message = format!("Now on {} (was {}): the game is up", w.to, w.from); + if let Some(install) = &shared.install { + let (removed, failed) = install.prune(w.keep); + let pruned = update::pruned(&removed, &failed); + if !pruned.is_empty() { + message = format!("{message}. {pruned}"); + } + } + shared.finish_update(true, message); +} + /// Undoes a switch whose game never came up: `current` back on the release before, and the world as it /// was just before the switch (the one the new game left is kept in backups/). fn roll_back(shared: &Shared, dir: &Path, config: &Config, w: &Watch, reason: &str) { @@ -576,10 +593,7 @@ fn supervise( loop { if let Some(w) = watch.as_ref() { if up(shared) { - shared.finish_update( - true, - format!("Now on {} (was {}): the game is up", w.to, w.from), - ); + came_up(shared, w); *watch = None; } else if Instant::now() > w.deadline && stopping.is_none() { note( @@ -748,6 +762,29 @@ mod tests { std::fs::remove_dir_all(&install.root).unwrap(); } + #[cfg(unix)] + #[test] + fn a_game_that_comes_up_ends_the_update_and_prunes_old_releases() { + let (shared, dir) = installed("prune", &[("v1", 0), ("v2", 0), ("v3", 0)]); + let install = shared.install.clone().unwrap(); + let mut config = Config::default(); + config.updates.keep = 0; + let watch = switch(&shared, &dir, &config, "v3", Duration::from_secs(60)).unwrap(); + came_up(&shared, &watch); + assert_eq!(install.current().as_deref(), Some("v3")); + // The release before stays for `rollback`; the other one goes. + assert_eq!(install.previous().as_deref(), Some("v1")); + assert!(!install.release("v2").exists()); + let update = shared.update.lock().unwrap(); + assert!(update.ok && update.busy.is_none() && update.finished == 1); + assert_eq!( + update.last.as_deref(), + Some("Now on v3 (was v1): the game is up. Deleted old releases: v2") + ); + drop(update); + std::fs::remove_dir_all(&install.root).unwrap(); + } + #[cfg(unix)] #[test] fn a_game_that_cant_load_is_never_switched_to() { diff --git a/crates/horizon-server/src/update.rs b/crates/horizon-server/src/update.rs index bebbedc76..f1f60a061 100644 --- a/crates/horizon-server/src/update.rs +++ b/crates/horizon-server/src/update.rs @@ -120,6 +120,73 @@ impl Install { } .map_err(|e| format!("{}: {e}", file.display())) } + + /// Deletes old releases after a successful update: it keeps the one `current` points at, the one + /// `previous` names (where `rollback` goes), the one this program runs from, and the `keep` newest of + /// the others. Returns the releases deleted, and what couldn't be (a program still running from it on + /// Windows), which stays for the next update to try again. + pub fn prune(&self, keep: u32) -> (Vec, Vec) { + let releases = self.root.join("releases"); + let running = std::env::current_exe() + .ok() + .and_then(|e| std::fs::canonicalize(e).ok()); + let Some(current) = self.current() else { + // `current` points nowhere: nothing is known to be safe to delete. + return (Vec::new(), Vec::new()); + }; + let previous = self.previous(); + let mut others: Vec = std::fs::read_dir(&releases) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.file_type().is_ok_and(|t| t.is_dir())) + .map(|e| e.file_name().to_string_lossy().into_owned()) + // `..unpacking` is an update in progress. + .filter(|tag| { + !tag.starts_with('.') && *tag != current && previous.as_deref() != Some(tag) + }) + .filter(|tag| { + let dir = std::fs::canonicalize(releases.join(tag)).ok(); + !running + .as_ref() + .zip(dir) + .is_some_and(|(exe, dir)| exe.starts_with(dir)) + }) + .collect(); + // Newest first; names that aren't release tags (archives installed by hand) by name. + others.sort_by(|a, b| { + if newer(a, b) { + std::cmp::Ordering::Less + } else if newer(b, a) { + std::cmp::Ordering::Greater + } else { + b.cmp(a) + } + }); + let (mut removed, mut failed) = (Vec::new(), Vec::new()); + for tag in others.into_iter().skip(keep as usize) { + match std::fs::remove_dir_all(releases.join(&tag)) { + Ok(()) => removed.push(tag), + Err(e) => failed.push(format!("{tag} ({e})")), + } + } + (removed, failed) + } +} + +/// What [`Install::prune`] did, for the log: empty when it deleted nothing. +pub fn pruned(removed: &[String], failed: &[String]) -> String { + let mut parts = Vec::new(); + if !removed.is_empty() { + parts.push(format!("Deleted old releases: {}", removed.join(", "))); + } + if !failed.is_empty() { + parts.push(format!( + "Couldn't delete old releases: {}", + failed.join(", ") + )); + } + parts.join(". ") } /// Makes `link` point at the folder `target`, replacing what it pointed at. @@ -301,8 +368,11 @@ pub fn unpack(install: &Install, archive: &Path, tag: &str) -> Result String { /// `update [--check] [--version TAG] [--archive FILE --version TAG] [--timeout SECONDS]`. pub fn command(dir: &Path, args: &[String]) -> Result<(), String> { let mut check = false; + let mut as_json = false; let mut version = None; let mut archive = None; let mut timeout = crate::api::UPDATE_TIMEOUT; @@ -400,6 +471,7 @@ pub fn command(dir: &Path, args: &[String]) -> Result<(), String> { }; match arg.as_str() { "--check" => check = true, + "--json" => as_json = true, "--version" => version = Some(value()?), "--archive" => archive = Some(PathBuf::from(value()?)), "--timeout" => timeout = seconds(&value()?)?, @@ -419,6 +491,18 @@ pub fn command(dir: &Path, args: &[String]) -> Result<(), String> { } None => { let release = release(version.as_deref())?; + if check && as_json { + println!( + "{}", + json!({ + "installed": current, + "newest": release.tag, + "available": newer(&release.tag, ¤t), + "previous": install.previous(), + }) + ); + return Ok(()); + } if check { if newer(&release.tag, ¤t) { println!( @@ -582,6 +666,11 @@ fn switch_stopped(dir: &Path, install: &Install, tag: &str) -> Result<(), String "" } ); + let (removed, failed) = install.prune(config.updates.keep); + let pruned = pruned(&removed, &failed); + if !pruned.is_empty() { + println!("{pruned}."); + } Ok(()) } @@ -701,6 +790,59 @@ mod tests { std::fs::remove_dir_all(&install.root).unwrap(); } + #[cfg(unix)] + #[test] + fn pruning_keeps_current_previous_and_the_newest_others() { + let tags = [ + "v2026.10.19", + "v2026.10.1", + "v2026.10.2", + "v2026.10.10", + "v2026.10.18.3", + "local", + ]; + let install = installed("prune", &tags); + // After a rollback `previous` can be any release, even the oldest. + std::fs::write(install.root.join("previous"), "v2026.10.1\n").unwrap(); + std::fs::create_dir_all(install.root.join("releases/.v2026.10.20.unpacking")).unwrap(); + std::fs::write(install.root.join("releases/notes.txt"), "").unwrap(); + let left = || { + let mut names: Vec = std::fs::read_dir(install.root.join("releases")) + .unwrap() + .map(|e| e.unwrap().file_name().to_string_lossy().into_owned()) + .collect(); + names.sort(); + names + }; + let (removed, failed) = install.prune(1); + assert_eq!(removed, ["v2026.10.10", "v2026.10.2", "local"]); + assert!(failed.is_empty()); + assert_eq!( + left(), + [ + ".v2026.10.20.unpacking", + "notes.txt", + "v2026.10.1", + "v2026.10.18.3", + "v2026.10.19" + ] + ); + assert_eq!( + pruned(&removed, &failed), + "Deleted old releases: v2026.10.10, v2026.10.2, local" + ); + // Nothing more to delete at the same count; none at all kept besides current and previous. + assert_eq!(install.prune(1), (Vec::new(), Vec::new())); + assert_eq!(install.prune(0).0, ["v2026.10.18.3"]); + assert_eq!(install.current().as_deref(), Some("v2026.10.19")); + assert_eq!(install.previous().as_deref(), Some("v2026.10.1")); + // Without a `current` nothing is deleted. + std::fs::remove_file(install.root.join("current")).unwrap(); + assert_eq!(install.prune(0), (Vec::new(), Vec::new())); + assert!(install.release("v2026.10.19").is_dir()); + std::fs::remove_dir_all(&install.root).unwrap(); + } + #[cfg(unix)] #[test] fn an_archive_unpacks_beside_the_others_with_the_game_files_linked() { diff --git a/crates/horizon-shaderpack/src/lib.rs b/crates/horizon-shaderpack/src/lib.rs index 0cfec68f9..71b6abbd3 100644 --- a/crates/horizon-shaderpack/src/lib.rs +++ b/crates/horizon-shaderpack/src/lib.rs @@ -12,6 +12,7 @@ pub mod preprocess; pub mod properties; pub mod source; pub mod translate; +pub mod uniforms; use include::{IncludeGraph, Inlined}; use options::{Annotated, OptionSet, OptionValues}; diff --git a/crates/horizon-shaderpack/src/pipeline.rs b/crates/horizon-shaderpack/src/pipeline.rs index dfff469c4..7ebb35442 100644 --- a/crates/horizon-shaderpack/src/pipeline.rs +++ b/crates/horizon-shaderpack/src/pipeline.rs @@ -318,6 +318,47 @@ pub struct Passes { /// After `final`, these targets' alternate side is copied back so the /// next frame starts unflipped. pub flipped_at_end: BTreeSet, + pub directives: Directives, +} + +/// The `const` directives of a program folder that aren't about targets +/// (`PackDirectives`), read from the same programs in the same order. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Directives { + /// `sunPathRotation`, degrees: how far the sun and moon's path tilts + /// toward the north or south (a Z rotation between the sky's Y -90 and + /// its angle, `CelestialUniforms`). + pub sun_path_rotation: f32, + /// `eyeBrightnessHalflife`, tenths of a second: `eyeBrightnessSmooth`. + pub eye_brightness_half_life: f32, +} + +impl Default for Directives { + fn default() -> Self { + Self { + sun_path_rotation: 0.0, + eye_brightness_half_life: 10.0, + } + } +} + +impl Directives { + /// Read from `fragments` in order, the last one winning. + pub fn read<'a>(fragments: impl IntoIterator) -> Self { + let mut out = Self::default(); + for fragment in fragments { + for c in const_directives(fragment) { + // Java's `Float.parseFloat` takes a trailing `f`. + let value = c.value.trim_end_matches(['f', 'F']).parse::(); + match (c.ty, c.key.as_str(), value) { + ("float", "sunPathRotation", Ok(v)) => out.sun_path_rotation = v, + ("float", "eyeBrightnessHalflife", Ok(v)) => out.eye_brightness_half_life = v, + _ => {} + } + } + } + out + } } /// Iris's single programs (`ProgramId`), in order. @@ -435,6 +476,7 @@ impl JavaPack { } let mut out = Passes { targets: target_settings(sources.iter().map(String::as_str), properties), + directives: Directives::read(sources.iter().map(String::as_str)), ..Passes::default() }; @@ -689,6 +731,19 @@ mod tests { assert!(draw_buffers("/* DRAWBUFFERS:0a */").is_err()); } + #[test] + fn sky_directives_last_one_wins() { + assert_eq!(Directives::read([]), Directives::default()); + assert_eq!(Directives::default().eye_brightness_half_life, 10.0); + let d = Directives::read([ + "const float sunPathRotation = 30.0;\nconst float eyeBrightnessHalflife = 4.0f;", + "const float sunPathRotation = -40.0; // Complementary Unbound", + "const int sunPathRotation = 5;", + ]); + assert_eq!(d.sun_path_rotation, -40.0); + assert_eq!(d.eye_brightness_half_life, 4.0); + } + #[test] fn const_directives_and_target_settings() { let text = "\ diff --git a/crates/horizon-shaderpack/src/properties.rs b/crates/horizon-shaderpack/src/properties.rs index cc3069620..8c3f29c8f 100644 --- a/crates/horizon-shaderpack/src/properties.rs +++ b/crates/horizon-shaderpack/src/properties.rs @@ -307,6 +307,34 @@ fn parse_blend(value: &str) -> Result { } } +/// `clouds = off | fast | fancy`: replaces the player's cloud setting while +/// the pack runs (`ShaderProperties.cloudSetting`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum CloudSetting { + Off, + Fast, + Fancy, +} + +/// The vanilla sky the pack keeps: Iris draws no clouds with `clouds = off`, +/// and no sun or moon with `sun = false` / `moon = false`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SkyDirectives { + pub clouds: Option, + pub sun: bool, + pub moon: bool, +} + +impl Default for SkyDirectives { + fn default() -> Self { + Self { + clouds: None, + sun: true, + moon: true, + } + } +} + /// A pack's `shaders.properties`. #[derive(Debug, Default)] pub struct ShaderProperties { @@ -484,6 +512,31 @@ impl ShaderProperties { .collect() } + /// `uniform.*` and `variable.*`: the pack's custom uniforms. + pub fn custom_uniforms(&self) -> crate::uniforms::CustomUniforms { + crate::uniforms::CustomUniforms::parse(self.preprocessed.iter()) + } + + /// `clouds`, `sun` and `moon`: what the pack does with the vanilla sky. + pub fn sky(&self) -> SkyDirectives { + let boolean = |key| { + !matches!( + self.preprocessed.get(key).map(str::trim), + Some("false" | "0") + ) + }; + SkyDirectives { + clouds: match self.preprocessed.get("clouds").map(str::trim) { + Some("off") => Some(CloudSetting::Off), + Some("fast") => Some(CloudSetting::Fast), + Some("fancy") => Some(CloudSetting::Fancy), + _ => None, + }, + sun: boolean("sun"), + moon: boolean("moon"), + } + } + /// `blend.`: the program's blend override. pub fn blend(&self, program: &str) -> Option> { self.preprocessed diff --git a/crates/horizon-shaderpack/src/uniforms.rs b/crates/horizon-shaderpack/src/uniforms.rs new file mode 100644 index 000000000..842aeb51f --- /dev/null +++ b/crates/horizon-shaderpack/src/uniforms.rs @@ -0,0 +1,838 @@ +//! Custom uniforms: `uniform.. = ` and +//! `variable.. = ` in `shaders.properties`, evaluated +//! once a frame the way Iris does (`CustomUniforms`, the `kroppeb.stareval` +//! parser, `IrisFunctions`, `SmoothFloat`). +//! +//! Values are lists of floats: one for `bool`, `int` and `float` (a bool is 0 +//! or 1), two to four for vectors. Iris types each expression; evaluating in +//! floats gives the same results for what packs write (its only integer +//! operations are `+ - * %`, exact in floats at these sizes; `/` is always a +//! float division). +//! +//! A definition Iris can't resolve (a syntax error, an unknown name or +//! function, a cycle) is left out, and so is every definition using it: the +//! shader's uniform keeps its default, zero. Here a name is unknown when it is +//! neither another definition nor a value the `builtin` lookup gives. + +use std::collections::HashMap; + +/// The custom uniforms and variables of a pack, in evaluation order. +#[derive(Clone, Debug, Default)] +pub struct CustomUniforms { + defs: Vec, + /// Evaluation order (indices into `defs`): dependencies first. + order: Vec, + /// What couldn't be parsed or resolved, for the log. + pub problems: Vec, +} + +#[derive(Clone, Debug)] +struct Def { + name: String, + /// Components of the result: 1, 2, 3 or 4. + size: usize, + /// `bool` (0 or 1) or `int` (truncated) rather than float. + kind: Kind, + /// `uniform.` (given to the shaders) rather than `variable.`. + uniform: bool, + expr: Expr, +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Kind { + Bool, + Int, + Float, +} + +#[derive(Clone, Debug, PartialEq)] +enum Expr { + Number(f32), + Name(String), + /// A vector's component (`.x`, `.g`, `.t`, `.2`...). + Access(Box, usize), + Not(Box), + Negate(Box), + Binary(Op, Box, Box), + /// A function; `smooth` calls carry their own state slot. + Call(String, Vec, usize), +} + +#[derive(Clone, Copy, Debug, PartialEq)] +enum Op { + Multiply, + Divide, + Remainder, + Add, + Subtract, + Equals, + NotEquals, + Less, + More, + LessOrEqual, + MoreOrEqual, + And, + Or, +} + +impl Op { + /// `IrisOptions`: lower binds tighter; equal priorities associate left. + fn priority(self) -> u8 { + match self { + Op::Multiply | Op::Divide | Op::Remainder => 0, + Op::Add | Op::Subtract => 1, + Op::Equals + | Op::NotEquals + | Op::Less + | Op::More + | Op::LessOrEqual + | Op::MoreOrEqual => 2, + Op::And | Op::Or => 3, + } + } +} + +/// The per-frame state: `smooth` accumulators, `random`'s generator and the +/// last values. +#[derive(Clone, Debug, Default)] +pub struct UniformState { + smooth: Vec, + seed: u64, + values: HashMap>, +} + +impl UniformState { + /// A uniform's value this frame; `None` for variables and for + /// definitions that couldn't be resolved. + pub fn get(&self, name: &str) -> Option<&[f32]> { + self.values.get(name).map(Vec::as_slice) + } + + /// Every uniform's value this frame, by name. + pub fn values(&self) -> &HashMap> { + &self.values + } +} + +impl CustomUniforms { + /// The definitions in `properties` (key, value), in file order. + pub fn parse<'a>(properties: impl IntoIterator) -> Self { + let mut out = Self::default(); + let mut smooth = 0; + for (key, value) in properties { + let (uniform, rest) = if let Some(rest) = key.strip_prefix("uniform.") { + (true, rest) + } else if let Some(rest) = key.strip_prefix("variable.") { + (false, rest) + } else { + continue; + }; + let Some((ty, name)) = rest.split_once('.') else { + continue; + }; + let (kind, size) = match ty { + "bool" => (Kind::Bool, 1), + "int" => (Kind::Int, 1), + "float" => (Kind::Float, 1), + "vec2" => (Kind::Float, 2), + "vec3" => (Kind::Float, 3), + "vec4" => (Kind::Float, 4), + _ => { + out.problems.push(format!("{key}: unknown type `{ty}`")); + continue; + } + }; + if out.defs.iter().any(|d| d.name == name) { + out.problems.push(format!("{key}: duplicated variable")); + continue; + } + match parse(value, &mut smooth) { + Ok(expr) => out.defs.push(Def { + name: name.to_owned(), + size, + kind, + uniform, + expr, + }), + Err(e) => out.problems.push(format!("{key}: {e} ( = {value})")), + } + } + out.order = out.sort(); + out + } + + /// Whether the pack defines none. + pub fn is_empty(&self) -> bool { + self.defs.is_empty() + } + + /// Dependencies first; a definition in a cycle is left out. + fn sort(&mut self) -> Vec { + let index: HashMap<&str, usize> = self + .defs + .iter() + .enumerate() + .map(|(i, d)| (d.name.as_str(), i)) + .collect(); + // 0 unvisited, 1 in progress, 2 done, 3 broken. + let mut mark = vec![0u8; self.defs.len()]; + let mut order = Vec::new(); + fn visit( + i: usize, + defs: &[Def], + index: &HashMap<&str, usize>, + mark: &mut [u8], + order: &mut Vec, + ) -> bool { + match mark[i] { + 1 | 3 => return false, + 2 => return true, + _ => {} + } + mark[i] = 1; + let mut names = Vec::new(); + defs[i].expr.names(&mut names); + let ok = names.iter().all(|n| match index.get(n.as_str()) { + Some(&j) => visit(j, defs, index, mark, order), + None => true, + }); + mark[i] = if ok { 2 } else { 3 }; + if ok { + order.push(i); + } + ok + } + for i in 0..self.defs.len() { + if !visit(i, &self.defs, &index, &mut mark, &mut order) && mark[i] == 3 { + self.problems + .push(format!("{}: circular reference", self.defs[i].name)); + } + } + order + } + + /// Evaluate every definition for this frame: `builtin` gives Iris's own + /// uniforms, `frame_time` (seconds) drives `smooth`. + pub fn update( + &self, + state: &mut UniformState, + frame_time: f32, + builtin: &dyn Fn(&str) -> Option>, + ) { + let mut values: HashMap<&str, Vec> = HashMap::new(); + let mut broken: Vec<&str> = Vec::new(); + state.values.clear(); + for &i in &self.order { + let def = &self.defs[i]; + let mut eval = Eval { + frame_time, + builtin, + values: &values, + broken: &broken, + smooth: &mut state.smooth, + seed: &mut state.seed, + }; + let Some(mut value) = eval.expr(&def.expr) else { + broken.push(&def.name); + continue; + }; + value.resize(def.size, value.last().copied().unwrap_or(0.0)); + match def.kind { + Kind::Bool => value[0] = f32::from(u8::from(value[0] != 0.0)), + Kind::Int => value[0] = value[0].trunc(), + Kind::Float => {} + } + if def.uniform { + state.values.insert(def.name.clone(), value.clone()); + } + values.insert(&def.name, value); + } + } +} + +impl Expr { + fn names(&self, out: &mut Vec) { + match self { + Expr::Number(_) => {} + Expr::Name(n) => out.push(n.clone()), + Expr::Access(e, _) | Expr::Not(e) | Expr::Negate(e) => e.names(out), + Expr::Binary(_, a, b) => { + a.names(out); + b.names(out); + } + Expr::Call(_, args, _) => args.iter().for_each(|a| a.names(out)), + } + } +} + +struct Eval<'a> { + frame_time: f32, + builtin: &'a dyn Fn(&str) -> Option>, + values: &'a HashMap<&'a str, Vec>, + broken: &'a [&'a str], + smooth: &'a mut Vec, + seed: &'a mut u64, +} + +/// Apply `f` component by component, a scalar standing for every component. +fn zip(args: &[Vec], f: impl Fn(&[f32]) -> f32) -> Vec { + let n = args.iter().map(Vec::len).max().unwrap_or(1); + (0..n) + .map(|i| { + let a: Vec = args + .iter() + .map(|v| { + if v.len() == 1 { + v[0] + } else { + v.get(i).copied().unwrap_or(0.0) + } + }) + .collect(); + f(&a) + }) + .collect() +} + +fn truth(b: bool) -> f32 { + f32::from(u8::from(b)) +} + +impl Eval<'_> { + fn expr(&mut self, e: &Expr) -> Option> { + Some(match e { + Expr::Number(n) => vec![*n], + Expr::Name(n) => self.name(n)?, + Expr::Access(e, i) => vec![*self.expr(e)?.get(*i)?], + Expr::Not(e) => zip(&[self.expr(e)?], |a| truth(a[0] == 0.0)), + Expr::Negate(e) => self.expr(e)?.iter().map(|v| -v).collect(), + Expr::Binary(op, a, b) => { + let a = self.expr(a)?; + let b = self.expr(b)?; + let f = |x: f32, y: f32| match op { + Op::Multiply => x * y, + Op::Divide => x / y, + // Java's `%`, on ints and floats: the sign of x. + Op::Remainder => x % y, + Op::Add => x + y, + Op::Subtract => x - y, + Op::Equals => truth(x == y), + Op::NotEquals => truth(x != y), + Op::Less => truth(x < y), + Op::More => truth(x > y), + Op::LessOrEqual => truth(x <= y), + Op::MoreOrEqual => truth(x >= y), + Op::And => truth(x != 0.0 && y != 0.0), + Op::Or => truth(x != 0.0 || y != 0.0), + }; + zip(&[a, b], |v| f(v[0], v[1])) + } + Expr::Call(name, args, slot) => self.call(name, args, *slot)?, + }) + } + + fn name(&self, n: &str) -> Option> { + if self.broken.contains(&n) { + return None; + } + if let Some(v) = self.values.get(n) { + return Some(v.clone()); + } + match n { + "true" => return Some(vec![1.0]), + "false" => return Some(vec![0.0]), + "pi" => return Some(vec![std::f32::consts::PI]), + _ => {} + } + (self.builtin)(n) + } + + fn random(&mut self) -> f32 { + // xorshift64*, seeded once. + if *self.seed == 0 { + *self.seed = 0x9E37_79B9_7F4A_7C15; + } + let mut x = *self.seed; + x ^= x >> 12; + x ^= x << 25; + x ^= x >> 27; + *self.seed = x; + ((x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 40) as f32) / (1u64 << 24) as f32 + } + + fn call(&mut self, name: &str, args: &[Expr], slot: usize) -> Option> { + // `if` evaluates only the branch it takes. + if name == "if" { + if args.len() < 3 || args.len() % 2 == 0 { + return None; + } + for pair in args[..args.len() - 1].chunks(2) { + if self.expr(&pair[0])?[0] != 0.0 { + return self.expr(&pair[1]); + } + } + return self.expr(&args[args.len() - 1]); + } + if name == "smooth" { + return self.smooth(args, slot); + } + let v: Vec> = args.iter().map(|a| self.expr(a)).collect::>()?; + let unary = |f: fn(f32) -> f32| { + (v.len() == 1).then(|| v[0].iter().map(|&x| f(x)).collect::>()) + }; + let n = v.len(); + Some(match (name, n) { + ("sin", 1) => unary(f32::sin)?, + ("cos", 1) => unary(f32::cos)?, + ("tan", 1) => unary(f32::tan)?, + ("asin", 1) => unary(f32::asin)?, + ("acos", 1) => unary(f32::acos)?, + ("atan", 1) => unary(f32::atan)?, + ("atan" | "atan2", 2) => zip(&v, |a| a[0].atan2(a[1])), + ("torad" | "radians", 1) => unary(f32::to_radians)?, + ("todeg" | "degrees", 1) => unary(f32::to_degrees)?, + ("pow", 2) => zip(&v, |a| a[0].powf(a[1])), + ("exp", 1) => unary(f32::exp)?, + ("exp2", 1) => unary(f32::exp2)?, + ("exp10", 1) => unary(|x| 10f32.powf(x))?, + ("log", 1) => unary(f32::ln)?, + ("log", 2) => zip(&v, |a| a[1].ln() / a[0].ln()), + ("log2", 1) => unary(f32::log2)?, + ("log10", 1) => unary(f32::log10)?, + ("sqrt", 1) => unary(f32::sqrt)?, + ("abs", 1) => unary(f32::abs)?, + // Math.signum: 0 stays 0. + ("sign" | "signum", 1) => unary(|x| if x == 0.0 { x } else { x.signum() })?, + ("floor", 1) => unary(f32::floor)?, + ("ceil", 1) => unary(f32::ceil)?, + ("frac", 1) => unary(|x| x - x.floor())?, + // Math.round: half up. + ("round", 1) => unary(|x| (x + 0.5).floor())?, + ("min", 2..) => zip(&v, |a| a.iter().copied().fold(f32::INFINITY, f32::min)), + ("max", 2..) => zip(&v, |a| a.iter().copied().fold(f32::NEG_INFINITY, f32::max)), + ("clamp", 3) => zip(&v, |a| a[0].max(a[1]).min(a[2])), + ("mix", 3) => zip(&v, |a| a[0] + (a[1] - a[0]) * a[2]), + ("edge", 2) => zip(&v, |a| truth(a[1] >= a[0])), + ("fmod", 2) => zip(&v, |a| (a[0] % a[1] + a[1]) % a[1]), + ("between", 3) => vec![truth(v[0][0] >= v[1][0] && v[0][0] <= v[2][0])], + ("equals", 3) => vec![truth((v[0][0] - v[1][0]).abs() <= v[2][0])], + ("in", 2..) => vec![truth(v[1..].iter().any(|x| x[0] == v[0][0]))], + ("random", 0) => vec![self.random()], + ("random", 2) => { + let r = self.random(); + vec![v[0][0] + r * (v[1][0] - v[0][0])] + } + ("vec2" | "ivec2" | "bvec2", 2) + | ("vec3" | "ivec3" | "bvec3", 3) + | ("vec4" | "ivec4" | "bvec4", 4) => { + let mut out: Vec = v.iter().map(|a| a[0]).collect(); + if name.starts_with('i') { + out.iter_mut().for_each(|x| *x = x.trunc()); + } else if name.starts_with('b') { + out.iter_mut().for_each(|x| *x = truth(*x != 0.0)); + } + out + } + _ => return None, + }) + } + + /// `smooth([id,] value[, fadeTime[, fadeDownTime]])`: the half-lives, in + /// tenths of a second, default to 1. A constant first argument of two or + /// three is OptiFine's id; with four it always is. + fn smooth(&mut self, args: &[Expr], slot: usize) -> Option> { + let id = matches!(args.first(), Some(Expr::Number(_))) && args.len() >= 2; + let args = if id || args.len() == 4 { + &args[1..] + } else { + args + }; + let value = self.expr(args.first()?)?[0]; + let up = match args.get(1) { + Some(e) => self.expr(e)?[0], + None => 1.0, + }; + let down = match args.get(2) { + Some(e) => self.expr(e)?[0], + None => up, + }; + if args.len() > 3 { + return None; + } + if self.smooth.len() <= slot { + self.smooth.resize(slot + 1, SmoothFloat::default()); + } + Some(vec![self.smooth[slot].update( + value, + up, + down, + self.frame_time, + )]) + } +} + +/// Iris's `SmoothFloat`: exponential smoothing with separate half-lives up +/// and down, in tenths of a second; the first value is taken as is. +#[derive(Clone, Copy, Debug, Default)] +pub struct SmoothFloat { + value: Option, +} + +impl SmoothFloat { + pub fn update(&mut self, target: f32, half_life_up: f32, half_life_down: f32, dt: f32) -> f32 { + let Some(acc) = self.value else { + self.value = Some(target); + return target; + }; + let half_life = if target > acc { + half_life_up + } else { + half_life_down + }; + let next = if half_life == 0.0 { + target + } else { + let decay = std::f32::consts::LN_2 / (half_life * 0.1); + let alpha = 1.0 - (-decay * dt).exp(); + (1.0 - alpha) * acc + alpha * target + }; + self.value = Some(next); + next + } +} + +/// Parse one expression; `smooth` counts the `smooth` calls so far (each +/// keeps its own state). +fn parse(text: &str, smooth: &mut usize) -> Result { + let tokens = tokenize(text)?; + let mut p = Parser { + tokens, + at: 0, + smooth, + }; + let e = p.binary(3)?; + match p.tokens.get(p.at) { + None => Ok(e), + Some(t) => Err(format!("unexpected {t:?}")), + } +} + +#[derive(Clone, Debug, PartialEq)] +enum Token { + Number(f32), + Id(String), + /// `.` followed by an accessor. + Access(String), + Op(String), + Open, + Close, + Comma, +} + +fn tokenize(text: &str) -> Result, String> { + let chars: Vec = text.chars().collect(); + let mut out = Vec::new(); + let mut i = 0; + let read_while = |i: &mut usize, f: &dyn Fn(char) -> bool| { + let start = *i; + while *i < chars.len() && f(chars[*i]) { + *i += 1; + } + chars[start..*i].iter().collect::() + }; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + } else if c.is_ascii_alphabetic() || c == '_' { + out.push(Token::Id(read_while(&mut i, &|c| { + c.is_ascii_alphanumeric() || c == '_' + }))); + } else if c == '.' + && matches!( + out.last(), + Some(Token::Id(_) | Token::Close | Token::Access(_)) + ) + { + i += 1; + while i < chars.len() && chars[i].is_whitespace() { + i += 1; + } + let access = read_while(&mut i, &|c| c.is_ascii_alphanumeric() || c == '_'); + if access.is_empty() { + return Err("an expression can't end with `.`".into()); + } + out.push(Token::Access(access)); + } else if c.is_ascii_digit() || c == '.' { + let s = read_while(&mut i, &|c| c.is_ascii_alphanumeric() || c == '.'); + let n = s + .parse::() + .or_else(|_| s.trim_end_matches(['f', 'F']).parse::()) + .map_err(|_| format!("bad number `{s}`"))?; + out.push(Token::Number(n)); + } else if c == '(' { + out.push(Token::Open); + i += 1; + } else if c == ')' { + out.push(Token::Close); + i += 1; + } else if c == ',' { + out.push(Token::Comma); + i += 1; + } else { + let two: String = chars[i..(i + 2).min(chars.len())].iter().collect(); + let op = ["==", "!=", "<=", ">=", "&&", "||"] + .into_iter() + .find(|o| two == *o) + .map(str::to_owned) + .or_else(|| "*/%+-<>!≠≤≥".contains(c).then(|| c.to_string())) + .ok_or_else(|| format!("unexpected character `{c}`"))?; + i += op.chars().count(); + out.push(Token::Op(op)); + } + } + Ok(out) +} + +struct Parser<'a> { + tokens: Vec, + at: usize, + smooth: &'a mut usize, +} + +impl Parser<'_> { + fn next(&mut self) -> Option { + let t = self.tokens.get(self.at).cloned(); + self.at += 1; + t + } + + fn peek_op(&self) -> Option { + let Some(Token::Op(o)) = self.tokens.get(self.at) else { + return None; + }; + Some(match o.as_str() { + "*" => Op::Multiply, + "/" => Op::Divide, + "%" => Op::Remainder, + "+" => Op::Add, + "-" => Op::Subtract, + "==" => Op::Equals, + "!=" | "≠" => Op::NotEquals, + "<" => Op::Less, + ">" => Op::More, + "<=" | "≤" => Op::LessOrEqual, + ">=" | "≥" => Op::MoreOrEqual, + "&&" => Op::And, + "||" => Op::Or, + _ => return None, + }) + } + + /// Operators of priority `max` or tighter, left to right. + fn binary(&mut self, max: u8) -> Result { + let mut left = self.unary()?; + while let Some(op) = self.peek_op() { + let p = op.priority(); + if p > max { + break; + } + self.at += 1; + // The right side takes only tighter operators: equal priorities + // associate to the left. + let right = if p == 0 { + self.unary()? + } else { + self.binary(p - 1)? + }; + left = Expr::Binary(op, Box::new(left), Box::new(right)); + } + Ok(left) + } + + /// Prefix `!` and `-`, which bind tighter than any binary operator. + fn unary(&mut self) -> Result { + match self.tokens.get(self.at) { + Some(Token::Op(o)) if o == "!" => { + self.at += 1; + Ok(Expr::Not(Box::new(self.unary()?))) + } + Some(Token::Op(o)) if o == "-" => { + self.at += 1; + Ok(Expr::Negate(Box::new(self.unary()?))) + } + _ => self.postfix(), + } + } + + fn postfix(&mut self) -> Result { + let mut e = match self.next() { + Some(Token::Number(n)) => Expr::Number(n), + Some(Token::Id(id)) if self.tokens.get(self.at) == Some(&Token::Open) => { + self.at += 1; + let mut args = Vec::new(); + if self.tokens.get(self.at) == Some(&Token::Close) { + self.at += 1; + } else { + loop { + args.push(self.binary(3)?); + match self.next() { + Some(Token::Comma) => {} + Some(Token::Close) => break, + t => return Err(format!("expected `,` or `)`, found {t:?}")), + } + } + } + let slot = *self.smooth; + if id == "smooth" { + *self.smooth += 1; + } + Expr::Call(id, args, slot) + } + Some(Token::Id(id)) => Expr::Name(id), + Some(Token::Open) => { + let e = self.binary(3)?; + match self.next() { + Some(Token::Close) => e, + t => return Err(format!("expected `)`, found {t:?}")), + } + } + t => return Err(format!("expected a value, found {t:?}")), + }; + while let Some(Token::Access(a)) = self.tokens.get(self.at) { + let i = match a.as_str() { + "x" | "r" | "s" | "0" => 0, + "y" | "g" | "t" | "1" => 1, + "z" | "b" | "p" | "2" => 2, + "w" | "a" | "q" | "3" => 3, + _ => return Err(format!("unknown accessor `.{a}`")), + }; + self.at += 1; + e = Expr::Access(Box::new(e), i); + } + Ok(e) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn builtins(name: &str) -> Option> { + Some(match name { + "frameCounter" => vec![7.0], + "eyeBrightness" => vec![32.0, 120.0], + "isEyeInWater" => vec![0.0], + "eyeAltitude" => vec![40.0], + "cameraPosition" => vec![1.0, 64.5, -3.0], + "rainStrength" => vec![0.0], + _ => return None, + }) + } + + fn eval(text: &str) -> Option> { + let u = CustomUniforms::parse([("uniform.float.x", text)]); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + state.get("x").map(<[f32]>::to_vec) + } + + #[test] + fn operators_follow_iris_priorities() { + assert_eq!(eval("1 + 2 * 3"), Some(vec![7.0])); + assert_eq!(eval("10 - 4 - 3"), Some(vec![3.0])); + assert_eq!(eval("2 * 3 % 4"), Some(vec![2.0])); + assert_eq!(eval("-2 * 3"), Some(vec![-6.0])); + assert_eq!(eval("1 < 2 && 3 > 4 || 1"), Some(vec![1.0])); + assert_eq!(eval("!(1 == 1)"), Some(vec![0.0])); + assert_eq!(eval("frameCounter % 2"), Some(vec![1.0])); + assert_eq!(eval("7 / 2"), Some(vec![3.5])); + assert_eq!(eval("-7 % 4"), Some(vec![-3.0])); + assert_eq!(eval("eyeBrightness.y / 240.0"), Some(vec![0.5])); + assert_eq!(eval("cameraPosition.y - 0.5"), Some(vec![64.0])); + assert_eq!(eval("2.5f * 2"), Some(vec![5.0])); + } + + #[test] + fn functions() { + assert_eq!(eval("if(eyeBrightness.y > 239.0, 1, 0)"), Some(vec![0.0])); + assert_eq!(eval("if(0, 1, 1 == 1, 2, 3)"), Some(vec![2.0])); + assert_eq!( + eval("clamp(5, 0, 1) + max(1, 4, 2) + min(3, -1)"), + Some(vec![4.0]) + ); + assert_eq!(eval("fmod(-1, 4)"), Some(vec![3.0])); + assert_eq!(eval("in(3, 1, 2, 3)"), Some(vec![1.0])); + assert_eq!( + eval("between(2, 1, 3) && equals(1.0, 1.05, 0.1)"), + Some(vec![1.0]) + ); + assert_eq!(eval("frac(2.25) + floor(-0.5) + abs(-2)"), Some(vec![1.25])); + assert_eq!(eval("vec2(1, 2).y"), Some(vec![2.0])); + // An unknown name or function leaves the uniform out (zero). + assert_eq!(eval("biome_precipitation + 1"), None); + assert_eq!(eval("nope(1)"), None); + assert_eq!(eval("1 +"), None); + } + + #[test] + fn variables_resolve_in_dependency_order() { + let u = CustomUniforms::parse([ + ("uniform.float.b", "a * 2"), + ("variable.float.a", "frameCounter + 1"), + ("uniform.vec2.v", "vec2(a, b)"), + ("uniform.bool.flag", "b > 10"), + ("uniform.float.loop1", "loop2"), + ("uniform.float.loop2", "loop1"), + ("uniform.float.bad", "unknown"), + ("uniform.float.uses_bad", "bad + 1"), + ]); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + assert_eq!(state.get("b"), Some(&[16.0][..])); + assert_eq!(state.get("a"), None, "variables aren't uniforms"); + assert_eq!(state.get("v"), Some(&[8.0, 16.0][..])); + assert_eq!(state.get("flag"), Some(&[1.0][..])); + assert_eq!(state.get("loop1"), None); + assert_eq!(state.get("bad"), None); + assert_eq!(state.get("uses_bad"), None); + assert!(u.problems.iter().any(|p| p.contains("circular"))); + } + + #[test] + fn smooth_is_iris_exponential_smoothing() { + // Complementary's `eyeBrightnessM` and `isEyeInCave`. + let u = CustomUniforms::parse([ + ( + "uniform.float.m", + "smooth(4, eyeBrightness.y / 240.0, 5, 5)", + ), + ( + "uniform.float.cave", + "if(isEyeInWater == 0, 1.0 - smooth(202, if(eyeAltitude < 5.0, eyeBrightness.y / 240.0, 1.0), 6, 12), 0.0)", + ), + ("uniform.float.once", "smooth(frameCounter)"), + ]); + assert!(u.problems.is_empty(), "{:?}", u.problems); + let mut state = UniformState::default(); + u.update(&mut state, 0.05, &builtins); + // The first value isn't smoothed. + assert_eq!(state.get("m"), Some(&[0.5][..])); + assert_eq!(state.get("cave"), Some(&[0.0][..])); + // Half a second at a half-life of 5 tenths: halfway to the target. + let dark = |name: &str| -> Option> { + match name { + "eyeBrightness" => Some(vec![0.0, 0.0]), + _ => builtins(name), + } + }; + u.update(&mut state, 0.5, &dark); + let m = state.get("m").unwrap()[0]; + assert!((m - 0.25).abs() < 1e-5, "{m}"); + let mut s = SmoothFloat::default(); + s.update(0.0, 0.0, 10.0, 0.1); + assert_eq!(s.update(1.0, 0.0, 10.0, 0.1), 1.0, "a half-life of 0 jumps"); + let down = s.update(0.0, 0.0, 10.0, 1.0); + assert!((down - 0.5).abs() < 1e-5, "{down}"); + } +} diff --git a/crates/horizon-shaderpack/tests/pack.rs b/crates/horizon-shaderpack/tests/pack.rs index ce5115b37..7aa45e8fa 100644 --- a/crates/horizon-shaderpack/tests/pack.rs +++ b/crates/horizon-shaderpack/tests/pack.rs @@ -326,6 +326,14 @@ fn real_packs_properties() { } println!(" unknown screen options: {unknown:?}"); assert!(unknown.len() <= 2, "{unknown:?}"); + // Every custom uniform parses. + let uniforms = properties.custom_uniforms(); + println!( + " custom uniforms: {:?}, sky {:?}", + uniforms.problems, + properties.sky() + ); + assert!(uniforms.problems.is_empty(), "{:?}", uniforms.problems); } } diff --git a/crates/horizon-world/src/level/feature_world.rs b/crates/horizon-world/src/level/feature_world.rs index 53363ea6a..f19d3ae8c 100644 --- a/crates/horizon-world/src/level/feature_world.rs +++ b/crates/horizon-world/src/level/feature_world.rs @@ -96,6 +96,15 @@ impl PlacementContext for LevelFeatureWorld<'_, '_, L> self.sim.level.set_raw(pos(position), state); Ok(()) } + /// LevelChunk.setBlockState without neighbour or shape updates. + fn set_chunk_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.sim.set_block(pos(position), state, 2 | 16); + Ok(()) + } fn collision_full_block( &mut self, state: BlockStateId, diff --git a/crates/horizon-world/src/loot.rs b/crates/horizon-world/src/loot.rs index be6eea7bb..96ca5bdee 100644 --- a/crates/horizon-world/src/loot.rs +++ b/crates/horizon-world/src/loot.rs @@ -255,7 +255,37 @@ fn int_bounds(v: &Value, value: i32) -> bool { } } -fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) -> io::Result<()> { +/// A JSON number read by an int codec (`Number.intValue`): `3.0`, which +/// 1.21.1 mods write for rolls and counts, is 3. +fn int_value(v: &Value) -> Option { + v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)) +} + +/// `data///` of every namespace, as `ns:path`: vanilla's, and in +/// a content mods' root theirs (docs/modpacks.md), whose chests name their +/// own loot tables. +fn load_kind(data: &Path, kind: &str, out: &mut HashMap) -> io::Result<()> { + let Ok(entries) = fs::read_dir(data) else { + return Ok(()); + }; + let mut namespaces: Vec = entries + .flatten() + .filter(|e| e.path().is_dir()) + .filter_map(|e| e.file_name().to_str().map(str::to_owned)) + .collect(); + namespaces.sort(); + for ns in namespaces { + load_dir(&data.join(&ns).join(kind), &ns, "", out)?; + } + Ok(()) +} + +fn load_dir( + dir: &Path, + namespace: &str, + prefix: &str, + out: &mut HashMap, +) -> io::Result<()> { let Ok(entries) = fs::read_dir(dir) else { return Ok(()); }; @@ -265,10 +295,10 @@ fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap) -> io::R continue; }; if path.is_dir() { - load_dir(&path, &format!("{prefix}{stem}/"), out)?; + load_dir(&path, namespace, &format!("{prefix}{stem}/"), out)?; } else if path.extension().is_some_and(|e| e == "json") { let value = serde_json::from_slice(&fs::read(&path)?)?; - out.insert(format!("minecraft:{prefix}{stem}"), value); + out.insert(format!("{namespace}:{prefix}{stem}"), value); } } Ok(()) @@ -281,15 +311,18 @@ fn cost(v: &Value) -> (i32, i32) { } impl LootData { - /// Load from a resource root holding `items.json` and `data/minecraft`. + /// Load from a resource root holding `items.json` and `data/`: loot + /// tables, item modifiers, predicates, tags and recipes of every + /// namespace, vanilla's enchantments. pub fn load(root: &Path) -> io::Result { - let data = root.join("data/minecraft"); + let all = root.join("data"); + let data = all.join("minecraft"); let mut tables = HashMap::new(); - load_dir(&data.join("loot_table"), "", &mut tables)?; + load_kind(&all, "loot_table", &mut tables)?; let mut modifiers = HashMap::new(); - load_dir(&data.join("item_modifier"), "", &mut modifiers)?; + load_kind(&all, "item_modifier", &mut modifiers)?; let mut predicates = HashMap::new(); - load_dir(&data.join("predicate"), "", &mut predicates)?; + load_kind(&all, "predicate", &mut predicates)?; let raw: BTreeMap = serde_json::from_slice(&fs::read(root.join("items.json"))?)?; let items = raw @@ -308,7 +341,12 @@ impl LootData { }) .collect(); let mut raw_enchantments = HashMap::new(); - load_dir(&data.join("enchantment"), "", &mut raw_enchantments)?; + load_dir( + &data.join("enchantment"), + "minecraft", + "", + &mut raw_enchantments, + )?; let mut names: Vec<&String> = raw_enchantments.keys().collect(); names.sort(); let enchantments = names @@ -344,14 +382,14 @@ impl LootData { "damage_type", ] { let mut raw = HashMap::new(); - load_dir(&data.join("tags").join(registry), "", &mut raw)?; + load_kind(&all, &format!("tags/{registry}"), &mut raw)?; for (name, value) in raw { let values = value["values"].as_array().cloned().unwrap_or_default(); tags.insert((registry.to_owned(), name), values); } } let mut recipes = HashMap::new(); - load_dir(&data.join("recipe"), "", &mut recipes)?; + load_kind(&all, "recipe", &mut recipes)?; let mut ids: Vec<&String> = recipes.keys().collect(); ids.sort(); let smelting = ids @@ -833,7 +871,7 @@ impl Context<'_, R> { } fn int(&mut self, v: &Value) -> i32 { match v { - Value::Number(n) => n.as_i64().unwrap_or(0) as i32, + Value::Number(_) => int_value(v).unwrap_or(0) as i32, Value::Object(_) => match v["type"].as_str().unwrap_or("") { "minecraft:constant" => self.int(&v["value"]), "minecraft:uniform" => { @@ -1009,10 +1047,10 @@ impl Context<'_, R> { "minecraft:limit_count" => { let limit = &f["limit"]; let mut count = stack.get_count(); - if let Some(min) = limit["min"].as_i64() { + if let Some(min) = int_value(&limit["min"]) { count = count.max(min as i32); } - if let Some(max) = limit["max"].as_i64() { + if let Some(max) = int_value(&limit["max"]) { count = count.min(max as i32); } stack.count = count; @@ -1139,7 +1177,7 @@ impl Context<'_, R> { let addition = level as f32 * self.float(&f["count"]); // ItemStack.grow(Math.round(addition)). stack.count = stack.get_count() + (addition + 0.5).floor() as i32; - let limit = f["limit"].as_i64().unwrap_or(0) as i32; + let limit = int_value(&f["limit"]).unwrap_or(0) as i32; if limit > 0 && !stack.is_empty() && stack.count > limit { stack.count = limit; } @@ -1313,8 +1351,8 @@ impl Context<'_, R> { let luck = self.luck; let weight = |c: &Choice<'_>| { let e = c.entry; - let w = e["weight"].as_i64().unwrap_or(1) as f32 - + e["quality"].as_i64().unwrap_or(0) as f32 * luck; + let w = int_value(&e["weight"]).unwrap_or(1) as f32 + + int_value(&e["quality"]).unwrap_or(0) as f32 * luck; w.floor().max(0.0) as i32 }; let total: i32 = valid.iter().map(&weight).sum(); @@ -1358,7 +1396,7 @@ impl Context<'_, R> { true } "minecraft:item" | "minecraft:empty" | "minecraft:loot_table" => { - if entry["weight"].as_i64().unwrap_or(1) > 0 { + if int_value(&entry["weight"]).unwrap_or(1) > 0 { out.push(Choice { entry, item: None }); } true @@ -1368,7 +1406,7 @@ impl Context<'_, R> { if entry["expand"].as_bool().unwrap_or(false) { let items = self.data.holder_set("item", &entry["items"]); for item in items { - if entry["weight"].as_i64().unwrap_or(1) > 0 { + if int_value(&entry["weight"]).unwrap_or(1) > 0 { out.push(Choice { entry, item: Some(item), @@ -1377,7 +1415,7 @@ impl Context<'_, R> { } true } else { - if entry["weight"].as_i64().unwrap_or(1) > 0 { + if int_value(&entry["weight"]).unwrap_or(1) > 0 { out.push(Choice { entry, item: None }); } true @@ -1431,3 +1469,54 @@ fn enchant(stack: &mut LootStack, name: &str, level: i32) { None => stack.enchantments.push((name.to_owned(), level)), } } + +#[cfg(test)] +mod namespace_tests { + use super::*; + + /// A content mods' root: the mods' loot tables and tags load beside + /// vanilla's, under their own namespaces. + #[test] + fn loads_every_namespace() { + let root = std::env::temp_dir().join(format!("horizon-loot-ns-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let files = [ + ("items.json", r#"{"minecraft:bread": {}}"#), + ( + "data/minecraft/loot_table/chests/village.json", + r#"{"pools": []}"#, + ), + ( + "data/kaisyn/loot_table/village/forest/house.json", + r#"{"pools": []}"#, + ), + ( + "data/kaisyn/tags/item/food.json", + r#"{"values": ["minecraft:bread"]}"#, + ), + ]; + for (name, text) in files { + let path = root.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, text).unwrap(); + } + let data = LootData::load(&root).unwrap(); + assert!(data.has_table("minecraft:chests/village")); + assert!(data.has_table("kaisyn:village/forest/house")); + assert!(!data.has_table("minecraft:village/forest/house")); + assert!(data.in_tag("item", "kaisyn:food", "minecraft:bread")); + // Rolls and weights written as floats (Towns and Towers' tables). + let table = r#"{"pools": [{"rolls": {"type": "minecraft:uniform", "min": 3.0, "max": 3.0}, + "entries": [{"type": "minecraft:item", "name": "minecraft:bread", "weight": 2.0}]}]}"#; + fs::write( + root.join("data/kaisyn/loot_table/village/forest/house.json"), + table, + ) + .unwrap(); + let data = LootData::load(&root).unwrap(); + let filled = data.fill("kaisyn:village/forest/house", 1, 27, None); + let count: i32 = filled.iter().flatten().map(|s| s.count).sum(); + assert_eq!(count, 3); + let _ = fs::remove_dir_all(&root); + } +} diff --git a/crates/horizon-world/src/worldgen/block_feature.rs b/crates/horizon-world/src/worldgen/block_feature.rs index 00f0c64c1..1ee122772 100644 --- a/crates/horizon-world/src/worldgen/block_feature.rs +++ b/crates/horizon-world/src/worldgen/block_feature.rs @@ -54,6 +54,13 @@ impl<'r> FeatureBlockBindings<'r> { pub fn registry(&self) -> &'r BlockRegistry { self.registry } + /// BlockState.isSolid (legacy solidity), when block properties are bound. + pub(crate) fn solid(&self) -> Result { + self.physical_properties + .as_ref() + .map(|p| p[0].clone()) + .ok_or(DecodeError::Field("block properties")) + } /// Bind provider resources and precompiled placement operations to this registry. pub fn with_state_providers( diff --git a/crates/horizon-world/src/worldgen/feature_region.rs b/crates/horizon-world/src/worldgen/feature_region.rs index 46eaf4be7..5ab361985 100644 --- a/crates/horizon-world/src/worldgen/feature_region.rs +++ b/crates/horizon-world/src/worldgen/feature_region.rs @@ -521,6 +521,15 @@ where .map_err(RegionError::from)?; Ok(()) } + /// ProtoChunk.setBlockState: the section and the stage's heightmaps. + fn set_chunk_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.region.set_block_worldgen(position, state)?; + Ok(()) + } fn water_at(&mut self, position: [i32; 3]) -> Result { self.region.water_at(position) } diff --git a/crates/horizon-world/src/worldgen/generator.rs b/crates/horizon-world/src/worldgen/generator.rs index 0d1f409e6..2d7dd251c 100644 --- a/crates/horizon-world/src/worldgen/generator.rs +++ b/crates/horizon-world/src/worldgen/generator.rs @@ -1219,6 +1219,30 @@ where }); columns } + /// ChunkGenerator.getBaseColumn's blocks, by what structures test + /// (BlockState.isSolid is blocksMotion for the noise's blocks, which + /// are never cobwebs or bamboo saplings). + fn noise_blocks(&self, x: i32, z: i32) -> super::structure::start::NoiseColumn { + use super::structure::start::{NoiseBlock, NoiseColumn}; + let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); + let mut blocks = vec![NoiseBlock::Air; height as usize]; + let registry = self.data.registry; + self.noise_column(x, z, &mut |y, state| { + let props = self.data.states.get(state); + blocks[(y - min) as usize] = if props.is_air() { + NoiseBlock::Air + } else { + match registry.state(state).map(|s| s.name.as_str()) { + Some("minecraft:water") => NoiseBlock::Water, + Some("minecraft:lava") => NoiseBlock::Lava, + _ if props.blocks_motion_in_heightmap() => NoiseBlock::Solid, + _ => NoiseBlock::Other, + } + }; + false + }); + NoiseColumn { min, blocks } + } /// iterateNoiseColumn from the top down until `visit` returns true. fn noise_column(&self, x: i32, z: i32, visit: &mut dyn FnMut(i32, BlockStateId) -> bool) { let (min, height) = (self.settings.noise_min_y, self.settings.noise_height); @@ -1327,6 +1351,9 @@ where fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec> { self.pipeline.base_columns(x, z, kinds) } + fn noise_column(&mut self, x: i32, z: i32) -> super::structure::start::NoiseColumn { + self.pipeline.noise_blocks(x, z) + } fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool { let sea = self.pipeline.settings.sea_level; self.worker.temperatures[biome.0 as usize] diff --git a/crates/horizon-world/src/worldgen/generator_decoration.rs b/crates/horizon-world/src/worldgen/generator_decoration.rs index e8028dd5a..83fe82d24 100644 --- a/crates/horizon-world/src/worldgen/generator_decoration.rs +++ b/crates/horizon-world/src/worldgen/generator_decoration.rs @@ -974,6 +974,17 @@ impl PlacementContext for World<'_> { .zone .contains_block(BlockPos::new(position[0], position[1], position[2]))) } + /// ProtoChunk.setBlockState: the section and the stage's heightmaps. + fn set_chunk_block( + &mut self, + position: [i32; 3], + state: BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.region + .set_block_worldgen(position, state) + .map_err(|e| query(format!("{e:?}")))?; + Ok(()) + } /// BulkSectionAccess write: section storage only, no heightmap updates. fn set_section_block( &mut self, diff --git a/crates/horizon-world/src/worldgen/placement/context.rs b/crates/horizon-world/src/worldgen/placement/context.rs index 7da5310d4..8d2a1dab7 100644 --- a/crates/horizon-world/src/worldgen/placement/context.rs +++ b/crates/horizon-world/src/worldgen/placement/context.rs @@ -71,6 +71,17 @@ pub trait PlacementContext { ) -> Result<(), PlacementQueryError> { Err(PlacementQueryError::Unavailable) } + /// ChunkAccess.setBlockState(pos, state, false) in generation (a + /// ProtoChunk write with its heightmaps, no neighbour or block-entity + /// effects), as mods' structure processors write past their template. + /// Worlds without generation chunks write the section. + fn set_chunk_block( + &mut self, + position: [i32; 3], + state: crate::registry::BlockStateId, + ) -> Result<(), PlacementQueryError> { + self.set_section_block(position, state) + } /// BlockState.isCollisionShapeFullBlock for an already-read state. fn collision_full_block( &mut self, diff --git a/crates/horizon-world/src/worldgen/structure.rs b/crates/horizon-world/src/worldgen/structure.rs index 61a48f3ea..405073450 100644 --- a/crates/horizon-world/src/worldgen/structure.rs +++ b/crates/horizon-world/src/worldgen/structure.rs @@ -3,6 +3,7 @@ pub mod end_city; pub mod enhanced_terrain; pub mod features; +pub mod formations; pub mod fortress; pub mod jigsaw; pub mod legacy; diff --git a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs index 404b9ecca..ac4d01e98 100644 --- a/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs +++ b/crates/horizon-world/src/worldgen/structure/enhanced_terrain.rs @@ -308,6 +308,7 @@ mod tests { waterlogging: None, yung: None, enhanced_terrain: own.map(Arc::new), + ground_level: 1, }) } diff --git a/crates/horizon-world/src/worldgen/structure/formations.rs b/crates/horizon-world/src/worldgen/structure/formations.rs new file mode 100644 index 000000000..b93268116 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/formations.rs @@ -0,0 +1,340 @@ +//! Formations' SimpleStructure (`horizon:formations`, which +//! `horizon-port-pack` writes for its `formations:simple`; docs/modpacks.md): +//! one pool element at a random spot of the chunk, at a height its +//! placement finds in the noise columns under the element's corners and +//! centre ([`StartContext::noise_column`]). +use super::{ + BoundingBox, Rotation, StructureResources, + jigsaw::{PoolElement, PoolPiece, Pools}, + start::{NoiseBlock, NoiseColumn, StartContext}, +}; +use crate::{ + heightmap::HeightmapType, + worldgen::{DecodeError, block_feature::FeatureBlockBindings}, +}; +use horizon_core::position::ChunkPos; +use horizon_core::random::RandomSource; +use serde_json::Value; + +/// StructurePlacement: how the height is found. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Placement { + Surface, + Ceiling, + OnWater, + OnLava, + Underground, + UndergroundSurface, + UndergroundCeiling, + UndergroundBuried, + UndergroundOnLava, +} +impl Placement { + pub fn decode(name: &str) -> Result { + Ok(match name { + "surface" => Self::Surface, + "ceiling" => Self::Ceiling, + "on_water" => Self::OnWater, + "on_lava" => Self::OnLava, + "underground" => Self::Underground, + "underground_surface" => Self::UndergroundSurface, + "underground_ceiling" => Self::UndergroundCeiling, + "underground_buried" => Self::UndergroundBuried, + "underground_on_lava" => Self::UndergroundOnLava, + _ => return Err(DecodeError::Field("formations placement")), + }) + } +} + +/// The structure: a pool to draw the element from, and its placement. +#[derive(Clone, Debug)] +pub struct Def { + pub pool: String, + pub placement: Placement, +} +impl Def { + pub fn decode(v: &Value) -> Result { + Ok(Self { + // An inline element is never written by Formations' generators. + pool: v["template"] + .as_str() + .ok_or(DecodeError::Field("formations template"))? + .to_owned(), + placement: Placement::decode(v["placement"].as_str().unwrap_or_default())?, + }) + } +} + +/// SimpleStructure.findGenerationPoint: the start's position and piece. +pub fn generate( + def: &Def, + context: &mut impl StartContext, + pools: &Pools, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + random: &mut impl RandomSource, + chunk: ChunkPos, +) -> Option<([i32; 3], PoolPiece)> { + let element = pools + .get(&def.pool, resources, bindings)? + .random_template(random); + if matches!(element.as_ref(), PoolElement::Empty) { + return None; + } + let x = chunk.x * 16 + random.next_int_bound(16).ok()?; + let z = chunk.z * 16 + random.next_int_bound(16).ok()?; + let rotation = Rotation::random(random); + let b = element.bounding_box([x, 0, z], rotation); + let height = find_height(def.placement, context, b, random)?; + let ground = element.ground_level_delta(); + let y = height - ground + 1; + if y < context.min_y() { + return None; + } + let piece = PoolPiece { + bounding_box: b.moved([0, y, 0]), + ground_level_delta: ground, + element, + position: [x, y, z], + rotation, + junctions: Vec::new(), + // LiquidSettings.APPLY_WATERLOGGING. + waterlogging: true, + }; + Some(([x, y, z], piece)) +} + +/// The four corners (min x min z, min x max z, max x max z, max x min z) +/// and the centre, as Formations' cornersAndCenter. +fn corners_and_center(b: BoundingBox) -> [[i32; 2]; 5] { + let c = b.center(); + [ + [b.min[0], b.min[2]], + [b.min[0], b.max[2]], + [b.max[0], b.max[2]], + [b.max[0], b.min[2]], + [c[0], c[2]], + ] +} + +/// ChunkGenerator.getFirstOccupiedHeight on WORLD_SURFACE_WG. +fn first_occupied(context: &mut impl StartContext, x: i32, z: i32) -> i32 { + context.base_height(x, z, HeightmapType::WorldSurfaceWg) - 1 +} + +/// (int) Math.round of the heights' mean. +fn average(heights: &[i32]) -> i32 { + let mean = heights.iter().map(|h| f64::from(*h)).sum::() / heights.len() as f64; + (mean + 0.5).floor() as i32 +} + +/// The largest and the mean distance of the heights from `average`. +fn spread(heights: &[i32], average: i32) -> (i32, f64) { + let d: Vec = heights.iter().map(|h| (average - h).abs()).collect(); + let max = d.iter().copied().max().unwrap_or(0); + let mean = d.iter().map(|v| f64::from(*v)).sum::() / d.len() as f64; + (max, mean) +} + +fn find_height( + placement: Placement, + context: &mut impl StartContext, + b: BoundingBox, + random: &mut impl RandomSource, +) -> Option { + let solid = NoiseBlock::is_solid; + match placement { + Placement::Surface => from_top(context, b, 10, 3.0, solid), + Placement::OnWater => from_top(context, b, 1, 1.0, |n| n == NoiseBlock::Water), + Placement::OnLava => from_top(context, b, 1, 1.0, |n| n == NoiseBlock::Lava), + Placement::Ceiling => { + let min = context.min_y(); + let top = context.max_y() + 1; + let mut heights = Vec::with_capacity(5); + for [x, z] in corners_and_center(b) { + let highest = first_occupied(context, x, z).min(top); + let column = context.noise_column(x, z); + heights.push(((min + 1)..highest).find(|y| column.get(*y) != NoiseBlock::Air)?); + } + let average = average(&heights); + (spread(&heights, average).1 <= 4.0).then_some(average) + } + _ => underground(placement, context, b, random), + } +} + +/// findFromTop: every column's top block (WORLD_SURFACE_WG) passes +/// `target`, and the heights are close enough. +fn from_top( + context: &mut impl StartContext, + b: BoundingBox, + max_offset: i32, + max_average_offset: f64, + target: impl Fn(NoiseBlock) -> bool, +) -> Option { + let min = context.min_y(); + let points = corners_and_center(b); + let heights: Vec = points + .iter() + .map(|[x, z]| first_occupied(context, *x, *z)) + .collect(); + if heights.iter().any(|y| *y <= min) { + return None; + } + for ([x, z], y) in points.iter().zip(&heights) { + if !target(context.noise_column(*x, *z).get(*y)) { + return None; + } + } + let average = average(&heights); + let (max, mean) = spread(&heights, average); + (max <= max_offset && mean <= max_average_offset).then_some(average) +} + +/// The underground placements: the space between the highest first block +/// above the bottom and the lowest surface of the five columns, then a +/// random height in it, which each column adjusts to its floor (or +/// ceiling, or lava), within limits. +fn underground( + placement: Placement, + context: &mut impl StartContext, + b: BoundingBox, + random: &mut impl RandomSource, +) -> Option { + let (bottom, top) = (context.min_y(), context.max_y() + 1); + let mut columns: Vec<(NoiseColumn, i32, i32)> = Vec::with_capacity(5); + for [x, z] in corners_and_center(b) { + let highest = first_occupied(context, x, z).min(top); + let column = context.noise_column(x, z); + let lowest = ((bottom + 1)..highest).find(|y| column.get(*y) != NoiseBlock::Air)?; + columns.push((column, highest, lowest)); + } + let min = columns.iter().map(|c| c.2).max()?; + let max = columns.iter().map(|c| c.1).min()?; + let span = b.span()[1]; + if max - min - 2 <= span { + return None; + } + let draw = random.next_int_bound(max - min - span - 2).ok()?; + let air = |c: &NoiseColumn, y: i32| c.get(y) == NoiseBlock::Air; + let solid = |c: &NoiseColumn, y: i32| c.get(y).is_solid(); + // A floor (or lava) under air near `height`: down through up to 10 + // blocks (`step` -1) or up (`step` 1, the ceiling), then through up to + // `reach` blocks of air. + let floor = |c: &NoiseColumn, height: i32, step: i32, reach: i32, lava: bool| { + let mut y = height; + let mut i = 0; + while i < 10 && y > min && !air(c, y) { + y += step; + i += 1; + } + if !air(c, y) { + return None; + } + y += step; + let mut i = 0; + while i < reach && air(c, y) { + y += step; + i += 1; + } + let ok = if lava { + c.get(y) == NoiseBlock::Lava + } else { + solid(c, y) + }; + ok.then_some(y) + }; + let heights: Option> = match placement { + Placement::Underground => return Some(min + 1 + draw), + Placement::UndergroundSurface => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, -1, 20, false)) + .collect() + } + Placement::UndergroundCeiling => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, 1, 30, false)) + .collect() + } + Placement::UndergroundOnLava => { + let h = min + 1 + draw; + columns + .iter() + .map(|c| floor(&c.0, h, -1, 40, true)) + .collect() + } + Placement::UndergroundBuried => { + let h = min + span + 1 + draw; + let heights: Option> = columns + .iter() + .map(|(c, _, _)| { + let mut y = h; + let mut i = 0; + while i < 10 && y > min && !solid(c, y) { + y -= 1; + i += 1; + } + if !solid(c, y) { + return None; + } + y -= 2; + for _ in 0..span { + if !solid(c, y) { + return None; + } + y -= 1; + } + (solid(c, y) && solid(c, y - 1)).then_some(y) + }) + .collect(); + let heights = heights?; + let average = average(&heights); + let held = columns + .iter() + .all(|(c, _, _)| solid(c, average) && solid(c, average + span)); + return held.then_some(average); + } + _ => None, + }; + let heights = heights?; + let average = average(&heights); + let (max, mean) = spread(&heights, average); + (max <= 5 && mean <= 3.0).then_some(average) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn averages_round_as_math_round() { + assert_eq!(average(&[1, 2]), 2); + assert_eq!(average(&[-1, -2]), -1); + assert_eq!(average(&[64, 64, 65, 66, 64]), 65); + assert_eq!(spread(&[61, 64, 66], 63), (3, 2.0)); + } + + #[test] + fn corners_then_centre() { + let b = BoundingBox::new([0, 0, 10], [6, 4, 13]); + assert_eq!( + corners_and_center(b), + [[0, 10], [0, 13], [6, 13], [6, 10], [3, 12]] + ); + } + + #[test] + fn placements_by_name() { + assert_eq!( + Placement::decode("underground_on_lava").unwrap(), + Placement::UndergroundOnLava + ); + assert!(Placement::decode("floating").is_err()); + let def = Def::decode(&serde_json::json!({"template": "a:b", "placement": "surface"})); + assert_eq!(def.unwrap().placement, Placement::Surface); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/jigsaw.rs b/crates/horizon-world/src/worldgen/structure/jigsaw.rs index 8e2b96e63..add246517 100644 --- a/crates/horizon-world/src/worldgen/structure/jigsaw.rs +++ b/crates/horizon-world/src/worldgen/structure/jigsaw.rs @@ -45,6 +45,9 @@ pub enum PoolElement { /// The piece's own terrain kernel in a structure that has one /// (`"horizon:enhanced_terrain_adaptation"`). enhanced_terrain: Option>, + /// getGroundLevelDelta: 1, or Formations' `ground_level` + /// (`"horizon:ground_level"`). + ground_level: i32, }, Feature { feature: String, @@ -150,6 +153,13 @@ impl PoolElement { .get("horizon:enhanced_terrain_adaptation") .map(|a| super::enhanced_terrain::Adaptation::decode(a).map(Arc::new)) .transpose()?, + ground_level: match value.get("horizon:ground_level") { + None => 1, + Some(v) => v + .as_u64() + .and_then(|g| i32::try_from(g).ok()) + .ok_or(DecodeError::Field("horizon:ground_level"))?, + }, } } "minecraft:feature_pool_element" => Self::Feature { @@ -246,7 +256,10 @@ impl PoolElement { } } pub fn ground_level_delta(&self) -> i32 { - 1 + match self { + Self::Single { ground_level, .. } => *ground_level, + _ => 1, + } } /// YUNG's API's rules, on a piece of one of its structures. pub fn yung(&self) -> Option<&super::yung::Rules> { diff --git a/crates/horizon-world/src/worldgen/structure/piece_limited.rs b/crates/horizon-world/src/worldgen/structure/piece_limited.rs index 687c01cd8..12a6e3f17 100644 --- a/crates/horizon-world/src/worldgen/structure/piece_limited.rs +++ b/crates/horizon-world/src/worldgen/structure/piece_limited.rs @@ -1027,6 +1027,7 @@ mod tests { waterlogging: None, yung: None, enhanced_terrain: None, + ground_level: 1, }); let piece = || PoolPiece { bounding_box: BoundingBox::new([0; 3], [4; 3]), diff --git a/crates/horizon-world/src/worldgen/structure/processor.rs b/crates/horizon-world/src/worldgen/structure/processor.rs index dd65ccd56..e77ab5a30 100644 --- a/crates/horizon-world/src/worldgen/structure/processor.rs +++ b/crates/horizon-world/src/worldgen/structure/processor.rs @@ -22,6 +22,8 @@ use serde_json::Value; use std::{collections::BTreeSet, sync::Arc}; mod lithostitched; +mod pillars; +mod sea_level; /// The draws processors make from StructurePlaceSettings' random. pub trait ProcessorRandom { @@ -301,6 +303,28 @@ pub enum Processor { Condition(Box), /// `horizon:set_block` (Lithostitched's `set_block`). SetBlock(Box), + /// `horizon:pillar` (Repurposed Structures' and Moog's pillars): a + /// trigger block starts a column down to the ground. + Pillar(Box), + /// `horizon:bottom_pillar` (Repurposed Structures'): the bottom layer + /// continues down to the ground. + BottomPillar(Box), + /// `horizon:close_off_fluid_sources` (Repurposed Structures' and Moog's): + /// fluid sources beside open blocks are walled off. + CloseOffFluidSources(Box), + /// `horizon:yung_pillar` (YUNG's pillars: Better Fortresses, Better + /// Jungle Temples). + YungPillar(Box), + /// `horizon:stair_pillar` (Better Fortresses' stair supports). + StairPillar(Box), + /// `horizon:flood_air` (Better Ocean Monuments'): air below sea level + /// becomes water. + FloodAir(Box), + /// `horizon:waterlog` (Better Ocean Monuments'): blocks below sea level + /// are waterlogged. + Waterlog, + /// `horizon:keep_world_block` (Better Ocean Monuments' structure void). + KeepWorldBlock(Box), } #[derive(Clone, Debug, Default)] pub struct ProcessorList(pub Vec); @@ -327,6 +351,12 @@ pub struct Pick { block: String, picks: Vec<(f32, Outcome)>, default: Option, + /// Each pick draws its own `nextFloat` (`if (r.nextFloat() < a) ... + /// else if (r.nextFloat() < b)`), Better Ocean Monuments' way. + redraw: bool, + /// The picked block takes the placeholder's properties + /// (Block.withPropertiesOf). + keep_properties: bool, } #[derive(Clone, Debug)] struct Outcome { @@ -412,11 +442,19 @@ impl Pick { .map(|p| Ok((below(p)?, outcome(p)?))) .collect::>()?, default: value.get("default").map(outcome).transpose()?, + redraw: value["redraw"].as_bool().unwrap_or(false), + keep_properties: value["keep_properties"].as_bool().unwrap_or(false), }) } fn apply(&self, info: BlockInfo, random: &mut dyn ProcessorRandom) -> BlockInfo { let outcome = match self.picks.is_empty() { true => self.default.as_ref(), + false if self.redraw => self + .picks + .iter() + .find(|(b, _)| random.float() < *b) + .map(|(_, o)| o) + .or(self.default.as_ref()), false => { let f = random.float(); self.picks @@ -760,6 +798,28 @@ impl Processor { "horizon:set_block" => { Self::SetBlock(Box::new(lithostitched::SetBlock::decode(value, state)?)) } + "horizon:pillar" => Self::Pillar(Box::new(pillars::Pillar::decode( + value, resources, bindings, state, + )?)), + "horizon:bottom_pillar" => Self::BottomPillar(Box::new(pillars::BottomPillar::decode( + value, resources, bindings, + )?)), + "horizon:close_off_fluid_sources" => Self::CloseOffFluidSources(Box::new( + pillars::CloseOffFluidSources::decode(value, resources, bindings)?, + )), + "horizon:yung_pillar" => Self::YungPillar(Box::new(pillars::YungPillar::decode( + value, bindings, state, + )?)), + "horizon:stair_pillar" => Self::StairPillar(Box::new(pillars::StairPillar::decode( + value, resources, bindings, + )?)), + "horizon:flood_air" => { + Self::FloodAir(Box::new(sea_level::FloodAir::decode(resources.registry)?)) + } + "horizon:waterlog" => Self::Waterlog, + "horizon:keep_world_block" => { + Self::KeepWorldBlock(Box::new(sea_level::KeepWorldBlock::decode(value)?)) + } "horizon:condition" => Self::Condition(Box::new(lithostitched::Conditional::decode( value, resources, bindings, )?)), @@ -776,6 +836,23 @@ impl ProcessorList { json: &str, resources: &StructureResources, bindings: &FeatureBlockBindings<'_>, + ) -> Result { + // Lists name lists (a pillar's, Lithostitched's): a cycle of names + // is refused rather than followed. + thread_local!(static DEPTH: std::cell::Cell = const { std::cell::Cell::new(0) }); + let depth = DEPTH.get(); + if depth >= 16 { + return Err(DecodeError::Field("processor lists nest too deep")); + } + DEPTH.set(depth + 1); + let decoded = Self::decode_at(json, resources, bindings); + DEPTH.set(depth); + decoded + } + fn decode_at( + json: &str, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, ) -> Result { let value: Value = serde_json::from_str(json)?; let value = match &value { @@ -1109,8 +1186,32 @@ fn process_block( list, world, resources, position, reference, relative, info, settings, ); } + Processor::Pillar(p) => return p.process(world, resources, position, info, settings), + Processor::BottomPillar(p) => { + return p.process(world, resources, position, relative, info, settings); + } + Processor::CloseOffFluidSources(p) => return p.process(world, info, settings), + Processor::YungPillar(p) => return p.process(world, resources, info, settings), + Processor::StairPillar(p) => return p.process(world, resources, info, settings), + Processor::FloodAir(p) => return p.process(world, info), + Processor::Waterlog => { + return sea_level::Waterlog::process(world, resources.registry, info, settings); + } + Processor::KeepWorldBlock(p) => { + return p.process(world, resources.registry, info, settings); + } Processor::Pick(pick) => match name(info.state) == pick.block { - true => Some(settings.with_random(info.pos, |r| pick.apply(info, r))), + true => { + let mut out = settings.with_random(info.pos, |r| pick.apply(info.clone(), r)); + if pick.keep_properties + && let Some(kept) = registry + .state(out.state) + .and_then(|s| with_properties_of(registry, &s.name, info.state)) + { + out.state = kept; + } + Some(out) + } false => Some(info), }, Processor::SpawnerMobs(spawner) => { @@ -1839,6 +1940,37 @@ mod tests { } } + #[test] + fn redrawn_picks_draw_a_float_each() { + // Better Ocean Monuments' copper: < 0.1 exposed, else a new float + // < 0.3 weathered, else oxidized. + let id = |v: &Value| Ok(BlockStateId(v["Name"].as_str().unwrap().len() as u32)); + let pick = Pick::decode( + &json!({"block": "oxidized_copper", "redraw": true, "keep_properties": true, + "picks": [{"below": 0.1, "state": {"Name": "a"}}, + {"below": 0.3, "state": {"Name": "bb"}}], + "default": {"state": {"Name": "ccc"}}}), + id, + ) + .unwrap(); + assert!(pick.keep_properties); + let run = |f: Vec| { + pick.apply( + BlockInfo { + pos: [0; 3], + state: BlockStateId(0), + nbt: None, + }, + &mut Draws(f, vec![]), + ) + .state + }; + assert_eq!(run(vec![0.05]), BlockStateId(1)); + // One float would give weathered at 0.2; the second draw decides. + assert_eq!(run(vec![0.2, 0.5]), BlockStateId(3)); + assert_eq!(run(vec![0.2, 0.25]), BlockStateId(2)); + } + #[test] fn picks_follow_yungs_cascade() { // States by name: sand 1, sandstone 2, the four stairs 10..13. diff --git a/crates/horizon-world/src/worldgen/structure/processor/pillars.rs b/crates/horizon-world/src/worldgen/structure/processor/pillars.rs new file mode 100644 index 000000000..8896e6fcd --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/processor/pillars.rs @@ -0,0 +1,865 @@ +//! Processors that place blocks outside their template, carried as data from +//! mods' Java processors (docs/modpacks.md): +//! - `horizon:pillar` and `horizon:bottom_pillar`: Repurposed Structures' and +//! Moog's pillar processors, which run a column of blocks from a trigger +//! block (or the template's bottom layer) down to the ground; +//! - `horizon:close_off_fluid_sources`: their fluid fix, which walls off the +//! water and lava sources around a structure's open blocks; +//! - `horizon:yung_pillar` and `horizon:stair_pillar`: YUNG's pillar +//! processor (Better Fortresses, Better Jungle Temples) and Better +//! Fortresses' stair supports. +//! +//! Each runs while the template is processed, before its blocks are placed, +//! and writes the world as the mods do (`ChunkAccess.setBlockState` or a +//! chunk section). As in the mods, only blocks of the chunk being generated +//! write: the placement's bounding box is that chunk. +use super::{PlaceSettings, ProcessResult, ProcessorList, ProcessorRandom, process_list}; +use crate::{ + block_properties::{BoundBlockProperty, BoundOcclusionFaces}, + fluid::{FluidKind, FluidStateTable}, + registry::BlockStateId, + worldgen::{ + DecodeError, + block_feature::FeatureBlockBindings, + placement::{PlacementContext, PlacementQueryError}, + structure::{BlockInfo, StructureResources}, + }, +}; +use horizon_core::geometry::Direction; +use serde_json::Value; +use std::{collections::BTreeSet, sync::Arc}; + +/// Blocks whose `defaultDestroyTime` is negative in 26.3 (unbreakable): +/// forced pillars go through every block but these. +const UNBREAKABLE: [&str; 15] = [ + "minecraft:barrier", + "minecraft:bedrock", + "minecraft:chain_command_block", + "minecraft:command_block", + "minecraft:end_gateway", + "minecraft:end_portal", + "minecraft:end_portal_frame", + "minecraft:jigsaw", + "minecraft:light", + "minecraft:moving_piston", + "minecraft:nether_portal", + "minecraft:repeating_command_block", + "minecraft:structure_block", + "minecraft:test_block", + "minecraft:test_instance_block", +]; + +/// What the processors ask of a block state. +#[derive(Clone, Debug)] +pub struct Blocks { + /// Air, cave air and void air (BlockState.isAir). + air: [BlockStateId; 3], + fluids: Arc, + can_occlude: BoundBlockProperty, + /// BlockState.isSolid (legacy solidity), for blocksMotion. + solid: BoundBlockProperty, + occlusion: BoundOcclusionFaces, + replaceable_by_trees: Arc>, + unbreakable: BTreeSet, + /// Cobweb and bamboo sapling, which never block motion. + no_motion: BTreeSet, + structure_void: BTreeSet, +} +impl Blocks { + fn decode(bindings: &FeatureBlockBindings<'_>) -> Result { + let block_set = |names: &[&str]| -> BTreeSet { + names + .iter() + .flat_map(|n| bindings.blocks.get(*n).into_iter().flat_map(|s| s.iter())) + .copied() + .collect() + }; + let missing = || DecodeError::Field("pillar processor block properties"); + Ok(Self { + air: bindings.air, + fluids: bindings.fluids.table().clone(), + can_occlude: bindings.can_occlude.clone().ok_or_else(missing)?, + solid: bindings.solid()?, + occlusion: bindings.occlusion_faces.clone().ok_or_else(missing)?, + replaceable_by_trees: bindings + .tags + .get("minecraft:replaceable_by_trees") + .cloned() + .unwrap_or_default(), + unbreakable: block_set(&UNBREAKABLE), + no_motion: block_set(&["minecraft:cobweb", "minecraft:bamboo_sapling"]), + structure_void: block_set(&["minecraft:structure_void"]), + }) + } + fn air(&self, state: BlockStateId) -> bool { + self.air.contains(&state) + } + /// `!getFluidState().isEmpty()`. + fn fluid(&self, state: BlockStateId) -> bool { + self.fluids + .get(state) + .is_some_and(|f| f.kind() != FluidKind::Empty) + } + /// What a pillar goes through: blocks that cannot occlude, and when + /// forced every block that can be broken. + fn passable(&self, state: BlockStateId, forced: bool) -> bool { + (forced && !self.unbreakable.contains(&state)) || !self.can_occlude.contains(state) + } + /// GeneralUtils.isReplaceableByStructures. + fn replaceable(&self, state: BlockStateId) -> bool { + self.air(state) || self.fluid(state) || self.replaceable_by_trees.contains(&state) + } + /// GeneralUtils.isFullCube: the occlusion shape is the full block. + fn full_cube(&self, state: BlockStateId) -> bool { + Direction::ALL + .into_iter() + .all(|d| self.occlusion.is_full(state, d).unwrap_or(false)) + } + /// BlockState.blocksMotion. + fn blocks_motion(&self, state: BlockStateId) -> bool { + !self.no_motion.contains(&state) && self.solid.contains(state) + } +} + +/// The world's block at `pos`; void air outside the build height (a chunk's +/// read there). +fn read( + world: &mut W, + blocks: &Blocks, + pos: [i32; 3], +) -> Result { + Ok(world.section_block(pos)?.unwrap_or(blocks.air[2])) +} + +/// Whether `pos` is outside the chunk being generated (WorldGenRegion's +/// centre): the placement's bounding box, by column. +pub(super) fn outside_chunk(settings: &PlaceSettings<'_>, pos: [i32; 3]) -> bool { + settings.bounding_box.is_some_and(|b| { + pos[0] < b.min[0] || pos[0] > b.max[0] || pos[2] < b.min[2] || pos[2] > b.max[2] + }) +} + +/// GeneralUtils.getFirstLandYFromPos: down from `pos` past air, fluids and +/// blocks trees replace. +fn first_land_y( + world: &mut W, + blocks: &Blocks, + pos: [i32; 3], +) -> Result { + let min = world.min_y()?; + let mut y = pos[1]; + while y >= min && blocks.replaceable(read(world, blocks, [pos[0], y, pos[2]])?) { + y -= 1; + } + Ok(y) +} + +/// Vec3i.closerThan: the squared distance under `length` squared. +fn closer_than(a: [i32; 3], b: [i32; 3], length: i32) -> bool { + let d: i64 = (0..3).map(|i| i64::from(a[i] - b[i]).pow(2)).sum(); + (d as f64) < f64::from(length) * f64::from(length) +} + +/// Direction's serialized names, in Direction.values() order. +const DIRECTION_NAMES: [&str; 6] = ["down", "up", "north", "south", "west", "east"]; + +fn direction(name: &str) -> Result { + let i = DIRECTION_NAMES + .iter() + .position(|n| *n == name) + .ok_or(DecodeError::Field("direction"))?; + Ok(Direction::ALL[i]) +} + +fn direction_name(d: Direction) -> &'static str { + DIRECTION_NAMES[Direction::ALL.iter().position(|x| *x == d).unwrap_or(0)] +} + +fn add(pos: [i32; 3], d: Direction) -> [i32; 3] { + let n = d.normal(); + [pos[0] + n[0], pos[1] + n[1], pos[2] + n[2]] +} + +/// The processor list a pillar runs on each of its blocks: a list holder +/// (a name or the processors), none when absent or `minecraft:empty`. +fn nested( + v: Option<&Value>, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, +) -> Result, DecodeError> { + match v { + None => Ok(None), + Some(Value::String(s)) if s == "minecraft:empty" => Ok(None), + Some(v) => Ok(Some(ProcessorList::decode( + &v.to_string(), + resources, + bindings, + )?)), + } +} + +/// Runs a pillar's processor list on one of its blocks, as the mods do: +/// the block's template position is its offset from the trigger plus the +/// piece's position, and it stands for the piece's and pivot's too. +#[allow(clippy::too_many_arguments)] +fn run_nested( + list: Option<&ProcessorList>, + world: &mut W, + resources: &StructureResources, + position: [i32; 3], + origin: [i32; 3], + at: [i32; 3], + state: BlockStateId, + settings: &mut PlaceSettings<'_>, +) -> ProcessResult { + let info = BlockInfo { + pos: at, + state, + nbt: None, + }; + let Some(list) = list else { + return Ok(Some(info)); + }; + let local = std::array::from_fn(|i| at[i] - origin[i] + position[i]); + process_list(list, world, resources, local, at, local, info, settings) +} + +/// Moog's `pillar_state_randomizer`: the first entry whose share of +/// `[0, 1)` holds one `nextFloat` and whose height range holds the block. +#[derive(Clone, Debug)] +struct HeightRandomizer { + entries: Vec<(BlockStateId, f32, Option, Option)>, + default: BlockStateId, +} +impl HeightRandomizer { + fn decode( + v: &Value, + state: &impl Fn(&Value) -> Result, + ) -> Result { + let entries = v["entries"] + .as_array() + .map(Vec::as_slice) + .unwrap_or_default() + .iter() + .map(|e| { + let y = |k: &str| e.get(k).and_then(Value::as_i64).map(|y| y as i32); + let p = e["probability"] + .as_f64() + .ok_or(DecodeError::Field("randomizer probability"))?; + Ok((state(&e["block"])?, p as f32, y("min_y"), y("max_y"))) + }) + .collect::>()?; + Ok(Self { + entries, + default: state(&v["default"])?, + }) + } + fn get(&self, random: &mut dyn ProcessorRandom, y: i32) -> BlockStateId { + let target = random.float(); + let mut bottom = 0f32; + for &(state, p, min, max) in &self.entries { + let in_range = min.is_none_or(|m| y >= m) && max.is_none_or(|m| y <= m); + if bottom <= target && target < bottom + p && in_range { + return state; + } + bottom += p; + } + self.default + } +} + +/// `horizon:pillar`: Repurposed Structures' and Moog's PillarProcessor. A +/// trigger state becomes `original_replaced_block` (or its replacement; +/// structure void removes it) and starts a column of the replacement, or +/// of Moog's randomizer's states, in `direction` through blocks that do not +/// occlude (with `forced_placement`, through all but unbreakable ones), +/// down to the first land, within `pillar_length` of the trigger. +#[derive(Clone, Debug)] +pub struct Pillar { + triggers: Vec<(BlockStateId, BlockStateId)>, + list: Option, + direction: Direction, + original: Option, + length: i32, + forced: bool, + randomizer: Option, + blocks: Blocks, +} +impl Pillar { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + state: impl Fn(&Value) -> Result, + ) -> Result { + let triggers = v["pillar_trigger_and_replacements"] + .as_array() + .ok_or(DecodeError::Field("pillar_trigger_and_replacements"))? + .iter() + .map(|p| Ok((state(&p["trigger"])?, state(&p["replacement"])?))) + .collect::>()?; + Ok(Self { + triggers, + list: nested(v.get("pillar_processor_list"), resources, bindings)?, + direction: direction(v["direction"].as_str().unwrap_or("down"))?, + original: v.get("original_replaced_block").map(&state).transpose()?, + length: v["pillar_length"].as_i64().unwrap_or(1000) as i32, + forced: v["forced_placement"].as_bool().unwrap_or(false), + randomizer: v + .get("pillar_state_randomizer") + .map(|r| HeightRandomizer::decode(r, &state)) + .transpose()?, + blocks: Blocks::decode(bindings)?, + }) + } + pub(super) fn process( + &self, + world: &mut W, + resources: &StructureResources, + position: [i32; 3], + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + ) -> ProcessResult { + let Some(&(_, replacement)) = self.triggers.iter().find(|t| t.0 == info.state) else { + return Ok(Some(info)); + }; + let origin = info.pos; + let kept = self.original.unwrap_or(replacement); + let result = (!self.blocks.structure_void.contains(&kept)).then_some(BlockInfo { + pos: origin, + state: kept, + nbt: None, + }); + if outside_chunk(settings, origin) { + return Ok(result); + } + let mut terrain_y = i32::MIN; + if self.direction == Direction::Down && !self.forced { + terrain_y = first_land_y(world, &self.blocks, origin)?; + let min = world.min_y()?; + if terrain_y <= min && self.length + 2 >= origin[1] - min { + return Ok(result); + } + } + // The column starts at the trigger, tested by the block past it. + let mut at = origin; + let mut block = read(world, &self.blocks, add(origin, self.direction))?; + while self.blocks.passable(block, self.forced) { + if (!self.forced && at[1] < terrain_y) + || world.outside_build_height(at[1])? + || !closer_than(at, origin, self.length) + { + break; + } + let fill = match &self.randomizer { + Some(r) => settings.with_random(at, |random| r.get(random, at[1])), + None => replacement, + }; + let placed = run_nested( + self.list.as_ref(), + world, + resources, + position, + origin, + at, + fill, + settings, + )?; + if let Some(placed) = placed { + world.set_chunk_block(at, placed.state)?; + } + at = add(at, self.direction); + block = read(world, &self.blocks, at)?; + } + Ok(result) + } +} + +/// `horizon:bottom_pillar`: Repurposed Structures' BottomPillarProcessor. +/// Each block of the template's bottom layer continues down as itself (run +/// through `pillar_processor_list`) through blocks that do not occlude, over +/// a first gap of one block, within `pillar_length`. +#[derive(Clone, Debug)] +pub struct BottomPillar { + list: Option, + length: i32, + forced: bool, + blocks: Blocks, +} +impl BottomPillar { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + Ok(Self { + list: nested(v.get("pillar_processor_list"), resources, bindings)?, + length: v["pillar_length"].as_i64().unwrap_or(1000) as i32, + forced: v["forced_placement"].as_bool().unwrap_or(false), + blocks: Blocks::decode(bindings)?, + }) + } + /// `relative` is the block's position in the template. + pub(super) fn process( + &self, + world: &mut W, + resources: &StructureResources, + position: [i32; 3], + relative: [i32; 3], + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + ) -> ProcessResult { + if relative[1] != 0 || outside_chunk(settings, info.pos) { + return Ok(Some(info)); + } + let origin = info.pos; + if !self.forced { + let terrain_y = first_land_y(world, &self.blocks, origin)?; + let min = world.min_y()?; + if terrain_y <= min && self.length + 2 >= origin[1] - min { + return Ok(Some(info)); + } + } + let below = |pos: [i32; 3]| [pos[0], pos[1] - 1, pos[2]]; + let valid = |world: &mut W, at: [i32; 3]| -> Result { + let block = read(world, &self.blocks, at)?; + Ok(self.blocks.passable(block, self.forced) + && !world.outside_build_height(at[1])? + && closer_than(at, origin, self.length)) + }; + let mut at = below(origin); + let mut layer = valid(world, at)?; + // A one-block gap under the bottom layer is filled too. + let mut skip_first = valid(world, below(at))?; + while skip_first || layer { + skip_first = false; + let placed = run_nested( + self.list.as_ref(), + world, + resources, + position, + origin, + at, + info.state, + settings, + )?; + if let Some(placed) = placed { + world.set_chunk_block(at, placed.state)?; + } + at = below(at); + layer = valid(world, at)?; + } + Ok(Some(info)) + } +} + +/// `horizon:close_off_fluid_sources`: Repurposed Structures' and Moog's +/// CloseOffFluidSourcesProcessor. Around each block that is not a full, +/// motion-blocking cube, the fluid sources beside it (not below with +/// `ignore_down`) become a block drawn by weight; with `if_air_in_world` +/// only where the world holds air at the block. +#[derive(Clone, Debug)] +pub struct CloseOffFluidSources { + replacements: Vec<(BlockStateId, i32)>, + ignore_down: bool, + if_air: bool, + blocks: Blocks, +} +impl CloseOffFluidSources { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let replacements = v["weighted_list_of_replacement_blocks"] + .as_array() + .ok_or(DecodeError::Field("weighted_list_of_replacement_blocks"))? + .iter() + .map(|e| { + let name = e["block"].as_str().ok_or(DecodeError::Field("block"))?; + let name = crate::worldgen::tags::identifier(name)?; + let state = resources + .registry + .default_state(&name) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}")))?; + let weight = e["weight"].as_i64().ok_or(DecodeError::Field("weight"))?; + Ok((state, weight as i32)) + }) + .collect::, DecodeError>>()?; + if replacements.is_empty() { + return Err(DecodeError::Field("weighted_list_of_replacement_blocks")); + } + Ok(Self { + replacements, + ignore_down: v["ignore_down"].as_bool().unwrap_or(false), + if_air: v["if_air_in_world"].as_bool().unwrap_or(false), + blocks: Blocks::decode(bindings)?, + }) + } + pub(super) fn process( + &self, + world: &mut W, + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + ) -> ProcessResult { + let state = info.state; + if self.blocks.structure_void.contains(&state) + || self.blocks.fluid(state) + || outside_chunk(settings, info.pos) + || (self.blocks.full_cube(state) && self.blocks.blocks_motion(state)) + { + return Ok(Some(info)); + } + if self.if_air && !self.blocks.air(read(world, &self.blocks, info.pos)?) { + return Ok(Some(info)); + } + // Direction.values(): down, up, north, south, west, east. + for d in Direction::ALL { + if self.ignore_down && d == Direction::Down { + continue; + } + let at = add(info.pos, d); + if world.outside_build_height(at[1])? || !world.fluid_state(at)?.is_source() { + continue; + } + let block = settings.with_random(info.pos, |random| pick(&self.replacements, random)); + world.set_section_block(at, block)?; + } + Ok(Some(info)) + } +} + +/// GeneralUtils.getRandomEntry: `nextFloat() * total` less each weight in +/// turn, the last entry when none takes it. +fn pick(entries: &[(BlockStateId, i32)], random: &mut dyn ProcessorRandom) -> BlockStateId { + let total: f64 = entries.iter().map(|r| f64::from(r.1)).sum(); + let mut picked = f64::from(random.float()) * total; + let mut index = 0; + while index < entries.len() - 1 { + picked -= f64::from(entries[index].1); + if picked <= 0.0 { + break; + } + index += 1; + } + entries[index].0 +} + +/// YUNG's BlockStateRandomizer: the first entry whose share of `[0, 1)` +/// holds one `nextFloat` (and whose altitude condition passes, when asked +/// with a height), else the default. +#[derive(Clone, Debug)] +struct YungRandomizer { + entries: Vec<(BlockStateId, f32, Option, Option)>, + default: BlockStateId, +} +impl YungRandomizer { + fn decode( + v: &Value, + state: &impl Fn(&Value) -> Result, + ) -> Result { + let entries = v["entries"] + .as_array() + .ok_or(DecodeError::Field("randomizer entries"))? + .iter() + .map(|e| { + let p = e["probability"] + .as_f64() + .ok_or(DecodeError::Field("randomizer probability"))?; + // yungsapi:altitude, the one condition the mods' pillars use. + let (bottom, top) = match e.get("condition") { + None => (None, None), + Some(c) if c["type"] == "yungsapi:altitude" => { + (c["bottom_cutoff_y"].as_f64(), c["top_cutoff_y"].as_f64()) + } + Some(_) => return Err(DecodeError::Field("randomizer condition")), + }; + Ok((state(&e["blockState"])?, p as f32, bottom, top)) + }) + .collect::>()?; + Ok(Self { + entries, + default: state(&v["defaultBlockState"])?, + }) + } + /// `get(random)` with no height, `get(random, ctx)` with the block's. + fn get(&self, random: &mut dyn ProcessorRandom, y: Option) -> BlockStateId { + let target = random.float(); + let mut bottom = 0f32; + for &(state, p, low, high) in &self.entries { + let passes = y.is_none_or(|y| { + let y = f64::from(y); + !low.is_some_and(|l| y < l) && !high.is_some_and(|h| y > h) + }); + if bottom <= target && target < bottom + p && passes { + return state; + } + bottom += p; + } + self.default + } +} + +/// `horizon:yung_pillar`: YUNG's PillarProcessor. A block of `target_block` +/// becomes a draw of `target_block_output`, and a column of +/// `pillar_states` runs down from it through air and fluids, all drawn from +/// the placement's random at the block. +#[derive(Clone, Debug)] +pub struct YungPillar { + target: String, + output: YungRandomizer, + pillar: YungRandomizer, + /// The output and the column take the target's properties + /// (Block.withPropertiesOf: Better Witch Huts' fence legs). + keep_properties: bool, + blocks: Blocks, +} +impl YungPillar { + pub(super) fn decode( + v: &Value, + bindings: &FeatureBlockBindings<'_>, + state: impl Fn(&Value) -> Result, + ) -> Result { + let target = state(&v["target_block"])?; + Ok(Self { + target: bindings.registry().state(target).unwrap().name.clone(), + output: YungRandomizer::decode(&v["target_block_output"], &state)?, + pillar: YungRandomizer::decode(&v["pillar_states"], &state)?, + keep_properties: v["keep_properties"].as_bool().unwrap_or(false), + blocks: Blocks::decode(bindings)?, + }) + } + pub(super) fn process( + &self, + world: &mut W, + resources: &StructureResources, + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + ) -> ProcessResult { + let name = resources + .registry + .state(info.state) + .map(|s| s.name.as_str()); + if name != Some(self.target.as_str()) || outside_chunk(settings, info.pos) { + return Ok(Some(info)); + } + let (min, max) = (world.min_y()?, world.max_y()?); + let origin = info.pos; + let registry = &resources.registry; + let kept = |state: BlockStateId| match self.keep_properties { + true => registry + .state(state) + .and_then(|s| super::with_properties_of(registry, &s.name, info.state)) + .unwrap_or(state), + false => state, + }; + settings.with_random(origin, |random| { + let state = kept(self.output.get(random, None)); + let mut at = [origin[0], origin[1] - 1, origin[2]]; + while at[1] > min && at[1] <= max { + let block = read(world, &self.blocks, at)?; + if !(self.blocks.air(block) || self.blocks.fluid(block)) { + break; + } + world.set_chunk_block(at, kept(self.pillar.get(random, Some(at[1]))))?; + at[1] -= 1; + } + Ok(Some(BlockInfo { state, ..info })) + }) + } +} + +/// `horizon:stair_pillar`: Better Fortresses' StairPillarProcessor. A stair +/// block in `blocks` becomes its target (facing, half and shape kept when it +/// is a stair); the block it faces becomes a `front` stair facing back, with +/// a column of `pillar` under it through air and fluids. +#[derive(Clone, Debug)] +pub struct StairPillar { + blocks_to: Vec<(String, String)>, + front: String, + pillar: BlockStateId, + blocks: Blocks, +} +impl StairPillar { + pub(super) fn decode( + v: &Value, + resources: &StructureResources, + bindings: &FeatureBlockBindings<'_>, + ) -> Result { + let id = |v: &Value| -> Result { + let name = v.as_str().ok_or(DecodeError::Field("stair_pillar block"))?; + Ok(crate::worldgen::tags::identifier(name)?.to_string()) + }; + let blocks_to = v["blocks"] + .as_object() + .ok_or(DecodeError::Field("stair_pillar blocks"))? + .iter() + .map(|(from, to)| Ok((id(&Value::String(from.clone()))?, id(to)?))) + .collect::>()?; + let pillar = id(&v["pillar"])?; + Ok(Self { + blocks_to, + front: id(&v["front"])?, + pillar: resources + .registry + .default_state(&pillar) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {pillar}")))?, + blocks: Blocks::decode(bindings)?, + }) + } + /// `block`'s default state with the stair properties of `from` it has. + fn stair( + resources: &StructureResources, + block: &str, + from: &std::collections::BTreeMap, + facing: Option<&str>, + ) -> Option { + let registry = resources.registry; + let mut state = registry.state(registry.default_state(block)?)?.clone(); + for key in ["facing", "half", "shape"] { + let value = match (key, facing) { + ("facing", Some(f)) => f, + _ => from.get(key)?.as_str(), + }; + if state.properties.contains_key(key) { + state.properties.insert(key.to_owned(), value.to_owned()); + } + } + registry.id(&state) + } + pub(super) fn process( + &self, + world: &mut W, + resources: &StructureResources, + info: BlockInfo, + settings: &mut PlaceSettings<'_>, + ) -> ProcessResult { + let Some(old) = resources.registry.state(info.state) else { + return Ok(Some(info)); + }; + let Some((_, to)) = self.blocks_to.iter().find(|(from, _)| *from == old.name) else { + return Ok(Some(info)); + }; + let props = &old.properties; + let Some(facing) = props.get("facing").and_then(|f| direction(f).ok()) else { + return Ok(Some(info)); + }; + let Some(output) = Self::stair(resources, to, props, None) else { + return Ok(Some(info)); + }; + let info = BlockInfo { + state: output, + ..info + }; + let mut at = add(info.pos, facing); + if outside_chunk(settings, at) { + return Ok(Some(info)); + } + let back = direction_name(facing.opposite()); + if let Some(front) = Self::stair(resources, &self.front, props, Some(back)) { + world.set_chunk_block(at, front)?; + } + let (min, max) = (world.min_y()?, world.max_y()?); + at[1] -= 1; + while at[1] > min && at[1] <= max { + let block = read(world, &self.blocks, at)?; + if !(self.blocks.air(block) || self.blocks.fluid(block)) { + break; + } + world.set_chunk_block(at, self.pillar)?; + at[1] -= 1; + } + Ok(Some(info)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// Scripted floats. + struct Floats(Vec); + impl ProcessorRandom for Floats { + fn float(&mut self) -> f32 { + self.0.remove(0) + } + fn int(&mut self, _: i32) -> i32 { + unreachable!() + } + fn long(&mut self) -> i64 { + unreachable!() + } + } + + fn id(v: &Value) -> Result { + let v = v.get("Name").unwrap_or(v); + Ok(BlockStateId(v.as_str().unwrap().len() as u32)) + } + + #[test] + fn height_randomizer_takes_the_share_in_range() { + let r = HeightRandomizer::decode( + &json!({"default": "d", "entries": [ + {"block": "aa", "probability": 0.25, "max_y": 10}, + {"block": "bbb", "probability": 0.5}]}), + &id, + ) + .unwrap(); + let (a, b, d) = (BlockStateId(2), BlockStateId(3), BlockStateId(1)); + assert_eq!(r.get(&mut Floats(vec![0.1]), 5), a); + // Out of its height range, a draw in the first share falls through. + assert_eq!(r.get(&mut Floats(vec![0.1]), 11), d); + assert_eq!(r.get(&mut Floats(vec![0.25]), 11), b); + assert_eq!(r.get(&mut Floats(vec![0.75]), 0), d); + } + + #[test] + fn yung_randomizer_checks_altitude_only_with_a_height() { + let r = YungRandomizer::decode( + &json!({"defaultBlockState": "d", "entries": [ + {"blockState": "aa", "probability": 0.5, + "condition": {"type": "yungsapi:altitude", "bottom_cutoff_y": 40}}]}), + &id, + ) + .unwrap(); + let (a, d) = (BlockStateId(2), BlockStateId(1)); + assert_eq!(r.get(&mut Floats(vec![0.2]), None), a); + assert_eq!(r.get(&mut Floats(vec![0.2]), Some(40)), a); + assert_eq!(r.get(&mut Floats(vec![0.2]), Some(39)), d); + assert_eq!(r.get(&mut Floats(vec![0.5]), None), d); + let bad = json!({"defaultBlockState": "d", "entries": [ + {"blockState": "aa", "probability": 1.0, "condition": {"type": "x:y"}}]}); + assert!(YungRandomizer::decode(&bad, &id).is_err()); + } + + #[test] + fn fluid_fix_picks_like_get_random_entry() { + let fix = |weights: &[i32]| -> Vec<(BlockStateId, i32)> { + weights + .iter() + .enumerate() + .map(|(i, w)| (BlockStateId(i as u32), *w)) + .collect() + }; + let three = fix(&[1, 2, 1]); + // nextFloat() * 4 = 0.4, 2.4, 3.0 (the second weight ends at 3), 3.2. + for (f, want) in [(0.1, 0), (0.6, 1), (0.75, 1), (0.8, 2)] { + assert_eq!(pick(&three, &mut Floats(vec![f])), BlockStateId(want)); + } + assert_eq!(pick(&fix(&[5]), &mut Floats(vec![0.9])), BlockStateId(0)); + } + + #[test] + fn directions_and_distances() { + for name in DIRECTION_NAMES { + assert_eq!(direction_name(direction(name).unwrap()), name); + } + assert!(direction("sideways").is_err()); + assert_eq!(add([0, 5, 0], direction("down").unwrap()), [0, 4, 0]); + assert_eq!(add([0, 5, 0], direction("east").unwrap()), [1, 5, 0]); + assert!(closer_than([0, 0, 0], [3, 0, 0], 4)); + assert!(!closer_than([0, 0, 0], [3, 0, 4], 5)); + assert!(closer_than([0, 0, 0], [3, 0, 4], 6)); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/processor/sea_level.rs b/crates/horizon-world/src/worldgen/structure/processor/sea_level.rs new file mode 100644 index 000000000..3b35b3e33 --- /dev/null +++ b/crates/horizon-world/src/worldgen/structure/processor/sea_level.rs @@ -0,0 +1,267 @@ +//! Processors for structures built under the sea, carried as data from +//! Better Ocean Monuments' Java processors (docs/modpacks.md): +//! - `horizon:flood_air`: the template's air below sea level becomes water +//! (its AirProcessor; the monuments' templates are mostly air); +//! - `horizon:waterlog`: below sea level, blocks that can be waterlogged +//! are, and the template's water and lava on the edge of the chunk being +//! generated are marked for postprocessing, so they flow across it (its +//! WaterlogProcessor); +//! - `horizon:keep_world_block`: blocks of `blocks` take the block the world +//! holds there (its StructureVoidProcessor, which, unlike vanilla's +//! structure void, lets the next processors see that block). +use super::{PlaceSettings, ProcessResult, pillars::outside_chunk}; +use crate::{ + registry::{BlockRegistry, BlockStateId}, + worldgen::{DecodeError, placement::PlacementContext, structure::BlockInfo}, +}; +use serde_json::Value; +use std::collections::BTreeSet; + +fn known(registry: &BlockRegistry, name: &str) -> Result { + registry + .default_state(name) + .ok_or_else(|| DecodeError::Registry(format!("unknown block {name}"))) +} + +/// `horizon:flood_air`: plain air (not cave air) under the sea level +/// becomes water, without a block entity. +#[derive(Clone, Debug)] +pub struct FloodAir { + air: BlockStateId, + water: BlockStateId, +} +impl FloodAir { + pub(super) fn decode(registry: &BlockRegistry) -> Result { + Ok(Self { + air: known(registry, "minecraft:air")?, + water: known(registry, "minecraft:water")?, + }) + } + pub(super) fn process( + &self, + world: &mut W, + info: BlockInfo, + ) -> ProcessResult { + if info.state != self.air || info.pos[1] >= world.sea_level()? { + return Ok(Some(info)); + } + Ok(Some(BlockInfo { + state: self.water, + nbt: None, + ..info + })) + } +} + +/// `horizon:waterlog`: WaterlogProcessor. +#[derive(Clone, Debug, Default)] +pub struct Waterlog; +impl Waterlog { + pub(super) fn process( + world: &mut W, + registry: &BlockRegistry, + info: BlockInfo, + settings: &PlaceSettings<'_>, + ) -> ProcessResult { + let Some(state) = registry.state(info.state) else { + return Ok(Some(info)); + }; + if info.pos[1] >= world.sea_level()? { + return Ok(Some(info)); + } + // BlockState.liquid(): a liquid block, not a waterlogged one. Java's + // `%` keeps the sign, as Rust's does: x = -1 is no edge for it. + let liquid = matches!(state.name.as_str(), "minecraft:water" | "minecraft:lava"); + let [x, _, z] = info.pos; + let edge = [x % 16, z % 16].iter().any(|v| *v == 0 || *v == 15); + if liquid && edge && !outside_chunk(settings, info.pos) { + world.mark_postprocessing(info.pos)?; + } + if state.properties.contains_key("waterlogged") { + let mut wet = state.clone(); + wet.properties.insert("waterlogged".into(), "true".into()); + if let Some(id) = registry.id(&wet) { + return Ok(Some(BlockInfo { state: id, ..info })); + } + } + Ok(Some(info)) + } +} + +/// `horizon:keep_world_block`: StructureVoidProcessor. The block entity +/// stays the template's, as the mod's does. +#[derive(Clone, Debug)] +pub struct KeepWorldBlock { + blocks: BTreeSet, +} +impl KeepWorldBlock { + pub(super) fn decode(value: &Value) -> Result { + let blocks = value["blocks"] + .as_array() + .ok_or(DecodeError::Field("keep_world_block blocks"))? + .iter() + .map(|b| { + let b = b + .as_str() + .ok_or(DecodeError::Field("keep_world_block blocks"))?; + Ok(crate::worldgen::tags::identifier(b)?.to_string()) + }) + .collect::>()?; + Ok(Self { blocks }) + } + pub(super) fn process( + &self, + world: &mut W, + registry: &BlockRegistry, + info: BlockInfo, + settings: &PlaceSettings<'_>, + ) -> ProcessResult { + let name = registry.state(info.state).map(|s| s.name.as_str()); + // A block outside the chunk is not placed, and the world there may + // not be readable. + if !name.is_some_and(|n| self.blocks.contains(n)) || outside_chunk(settings, info.pos) { + return Ok(Some(info)); + } + let state = world.block_state(info.pos)?; + Ok(Some(BlockInfo { state, ..info })) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + heightmap::HeightmapType, + worldgen::{ + anchor::WorldGenerationContext, + placement::PlacementQueryError, + structure::{BoundingBox, Rotation}, + }, + }; + use serde_json::json; + + /// Sea level 63; every block of the world is `world`; marks recorded. + struct Sea { + world: BlockStateId, + marked: Vec<[i32; 3]>, + } + impl PlacementContext for Sea { + fn generation(&self) -> WorldGenerationContext { + WorldGenerationContext::new(-64, 384, 63) + } + fn min_y(&mut self) -> Result { + Ok(-64) + } + fn height(&mut self, _: HeightmapType, _: i32, _: i32) -> Result { + Err(PlacementQueryError::Unavailable) + } + fn sea_level(&mut self) -> Result { + Ok(63) + } + fn mark_postprocessing(&mut self, pos: [i32; 3]) -> Result<(), PlacementQueryError> { + self.marked.push(pos); + Ok(()) + } + fn block_state(&mut self, _: [i32; 3]) -> Result { + Ok(self.world) + } + } + + // 0 air, 1 cave air, 2 water, 3/4 slab dry/wet, 5 purpur slab, 6 stone. + fn registry() -> BlockRegistry { + let row = |name: &str, props: Value| json!([name, false, false, "", {"id": name, "properties": props}]); + let facts = json!({"defaults": {"minecraft:air": 0, "minecraft:cave_air": 1, + "minecraft:water": 2, "minecraft:prismarine_slab": 3, "minecraft:purpur_slab": 5, + "minecraft:stone": 6}, + "states": [ + ["minecraft:air", false, false, "", "minecraft:air"], + ["minecraft:cave_air", false, false, "", "minecraft:cave_air"], + row("minecraft:water", json!({"level": "0"})), + row("minecraft:prismarine_slab", json!({"waterlogged": "false"})), + row("minecraft:prismarine_slab", json!({"waterlogged": "true"})), + ["minecraft:purpur_slab", false, false, "", "minecraft:purpur_slab"], + ["minecraft:stone", false, false, "", "minecraft:stone"]]}); + BlockRegistry::from_facts_json(facts.to_string().as_bytes()).unwrap() + } + + fn info(state: u32, pos: [i32; 3]) -> BlockInfo { + BlockInfo { + pos, + state: BlockStateId(state), + nbt: None, + } + } + + fn chunk(x: i32, z: i32) -> PlaceSettings<'static> { + let mut settings = PlaceSettings::new(Rotation::None); + settings.bounding_box = Some(BoundingBox::new([x, -64, z], [x + 15, 319, z + 15])); + settings + } + + #[test] + fn air_floods_below_the_sea_only() { + let registry = registry(); + let flood = FloodAir::decode(®istry).unwrap(); + let mut sea = Sea { + world: BlockStateId(6), + marked: vec![], + }; + let state = |i: BlockInfo, sea: &mut Sea| flood.process(sea, i).unwrap().unwrap().state; + assert_eq!(state(info(0, [0, 62, 0]), &mut sea), BlockStateId(2)); + assert_eq!(state(info(0, [0, 63, 0]), &mut sea), BlockStateId(0)); + // Cave air is not Blocks.AIR. + assert_eq!(state(info(1, [0, 10, 0]), &mut sea), BlockStateId(1)); + } + + #[test] + fn waterlog_wets_and_marks_the_chunk_edges() { + let registry = registry(); + let mut sea = Sea { + world: BlockStateId(6), + marked: vec![], + }; + let settings = chunk(-16, 0); + let mut run = |i: BlockInfo| { + Waterlog::process(&mut sea, ®istry, i, &settings) + .unwrap() + .unwrap() + .state + }; + assert_eq!(run(info(3, [-10, 40, 5])), BlockStateId(4)); + assert_eq!(run(info(3, [-10, 63, 5])), BlockStateId(3)); + assert_eq!(run(info(6, [-10, 40, 5])), BlockStateId(6)); + // Water on x = -16 (x % 16 == 0) and z = 15 is marked; x = -1 + // (x % 16 == -1), the middle and other chunks are not. + for pos in [ + [-16, 40, 5], + [-10, 40, 15], + [-1, 40, 5], + [-8, 40, 8], + [0, 40, 0], + ] { + run(info(2, pos)); + } + assert_eq!(sea.marked, vec![[-16, 40, 5], [-10, 40, 15]]); + } + + #[test] + fn kept_blocks_take_the_worlds() { + let registry = registry(); + let keep = KeepWorldBlock::decode(&json!({"blocks": ["purpur_slab"]})).unwrap(); + let mut sea = Sea { + world: BlockStateId(1), + marked: vec![], + }; + let settings = chunk(0, 0); + let mut run = |i: BlockInfo| { + keep.process(&mut sea, ®istry, i, &settings) + .unwrap() + .unwrap() + .state + }; + assert_eq!(run(info(5, [3, 40, 3])), BlockStateId(1)); + assert_eq!(run(info(6, [3, 40, 3])), BlockStateId(6)); + assert_eq!(run(info(5, [16, 40, 3])), BlockStateId(5)); + assert!(KeepWorldBlock::decode(&json!({})).is_err()); + } +} diff --git a/crates/horizon-world/src/worldgen/structure/start.rs b/crates/horizon-world/src/worldgen/structure/start.rs index ef360372e..b3dbe363f 100644 --- a/crates/horizon-world/src/worldgen/structure/start.rs +++ b/crates/horizon-world/src/worldgen/structure/start.rs @@ -92,6 +92,8 @@ pub enum StructureKind { Fortress, NetherFossil(HeightProvider), EndCity, + /// `horizon:formations`: Formations' SimpleStructure. + Formations(super::formations::Def), /// A structure type whose generator is not implemented yet. Unsupported(String), } @@ -367,6 +369,10 @@ impl StructureRegistry { "minecraft:nether_fossil" => StructureKind::NetherFossil( HeightProvider::from_json(&v["height"].to_string())?, ), + "horizon:formations" => match super::formations::Def::decode(&v) { + Ok(def) => StructureKind::Formations(def), + Err(_) => StructureKind::Unsupported("horizon:formations".into()), + }, other => StructureKind::Unsupported(other.to_owned()), }; defs.push(StructureDef { @@ -701,6 +707,41 @@ pub struct StructureStart { pub bounding_box: BoundingBox, } +/// A block of a noise column (ChunkGenerator.getBaseColumn), by what +/// structures ask of it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum NoiseBlock { + Air, + /// The water block (`is(Blocks.WATER)`), as the aquifers and the sea + /// fill it. + Water, + Lava, + /// BlockState.isSolid: the noise's own blocks (stone, deepslate, ore + /// veins, netherrack...). + Solid, + Other, +} +impl NoiseBlock { + pub fn is_solid(self) -> bool { + self == Self::Solid + } +} +/// ChunkGenerator.getBaseColumn's blocks from `min` up; past its ends a +/// NoiseColumn reads air. +#[derive(Clone, Debug, Default)] +pub struct NoiseColumn { + pub min: i32, + pub blocks: Vec, +} +impl NoiseColumn { + pub fn get(&self, y: i32) -> NoiseBlock { + usize::try_from(y - self.min) + .ok() + .and_then(|i| self.blocks.get(i).copied()) + .unwrap_or(NoiseBlock::Air) + } +} + /// Biome and height queries for one structure generation attempt. pub trait StartContext: JigsawContext { fn seed(&self) -> i64; @@ -709,6 +750,9 @@ pub trait StartContext: JigsawContext { fn base_column(&mut self, x: i32, z: i32, kind: HeightmapType) -> Vec; /// base_column for several heightmap kinds from one noise-column pass. fn base_columns(&mut self, x: i32, z: i32, kinds: &[HeightmapType]) -> Vec>; + /// ChunkGenerator.getBaseColumn's blocks: the noise column's states, as + /// mods' placements test them (Formations'). + fn noise_column(&mut self, x: i32, z: i32) -> NoiseColumn; /// Biome.coldEnoughToSnow at a position. fn cold_enough_to_snow(&mut self, biome: BiomeId, pos: [i32; 3]) -> bool; fn generation(&self) -> WorldGenerationContext; @@ -1099,6 +1143,18 @@ fn try_generate( let piece = super::nether_fossil::piece(resources, &mut random, position)?; (position, legacy(vec![piece])) } + StructureKind::Formations(formations) => { + let (position, piece) = super::formations::generate( + formations, + context, + ®istry.pools, + resources, + bindings, + &mut random, + chunk, + )?; + (position, vec![Piece::Pool(piece)]) + } StructureKind::Unsupported(_) => return None, }; let quart = position.map(|v| v >> 2); diff --git a/crates/horizon-world/src/worldgen/structure/yung.rs b/crates/horizon-world/src/worldgen/structure/yung.rs index 861266253..efd66fdc3 100644 --- a/crates/horizon-world/src/worldgen/structure/yung.rs +++ b/crates/horizon-world/src/worldgen/structure/yung.rs @@ -916,6 +916,7 @@ mod tests { waterlogging: None, yung: rules.map(Box::new), enhanced_terrain: None, + ground_level: 1, }) } diff --git a/docs/hosting.md b/docs/hosting.md index 255b473a2..963083b16 100644 --- a/docs/hosting.md +++ b/docs/hosting.md @@ -13,7 +13,10 @@ plan are in [docs/server.md](https://github.com/ludovic111/horizon/blob/main/doc - **Names you add are accounts** (release v2026.10.17.14 and newer). `init --player`, `horizon-server whitelist add` and `op`, and the console's `whitelist add`, `op` and `ban` look a name up the way vanilla does: players already seen (kept in `usercache.json`), then Mojang's profile service. In online mode a name - with no account is refused. So you can whitelist friends before they first join. + with no account is refused. So you can whitelist friends before they first join. On an offline server, + `horizon-server whitelist add` always writes the offline UUID, the one the player joins with, also while + the server runs (it writes the entry and the game reloads the list): the console's own `whitelist add` + takes the account's UUID when someone owns that name, as vanilla does, and that player is then refused. - **Horizon's own client can't sign in to a Microsoft account yet.** That needs an Azure app registration and Mojang's approval, which the project doesn't have ([docs/microsoft-account.md](https://github.com/ludovic111/horizon/blob/main/docs/microsoft-account.md)). @@ -199,11 +202,13 @@ horizon-server op|deop NAME horizon-server whitelist on|off|list horizon-server whitelist add|remove NAME horizon-server backup [NAME] back up now -horizon-server backups list the backups +horizon-server backups [--json] list the backups horizon-server restore BACKUP [--yes] horizon-server service install|uninstall|print [--system] horizon-server panel a one-time login link for the web panel horizon-server import FILE server.toml from a vanilla server.properties +horizon-server config [--json] the settings in server.toml +horizon-server config set KEY=VALUE... change settings, checked first (below) horizon-server update [--check] install the newest release and restart on it (below) horizon-server rollback back to the release before ``` @@ -212,6 +217,13 @@ While the server runs, `op`, `whitelist` and `cmd` go to the game's console, so console commands do. While it's stopped, they edit vanilla's files directly. Any console command works through `cmd`: `horizon-server cmd ban Griefer`, `horizon-server cmd say Restarting in 5 minutes`. +`config set` changes `server.toml` without opening it: `horizon-server config set world.difficulty=hard +server.max_players=10`. Each key is a section and a name from the file (`properties.spawn-protection=0` for any +other vanilla key). The values are checked as the server checks them, and nothing is written if one is wrong. +A running server takes the difficulty, the default game mode, the whitelist and the backup settings at once; +the rest applies at its next start, and `config set` says which. `--json` prints that as `saved`, `applied` +and `restart`. + The server restarts the game by itself if it crashes: after 5 s, then waiting longer each time, up to 5 minutes. It keeps the crash report and gives up after 5 crashes in 10 minutes, and `status` says why. diff --git a/docs/media/accessibility-settings-horizon.png b/docs/media/accessibility-settings-horizon.png new file mode 100644 index 000000000..7b1722129 Binary files /dev/null and b/docs/media/accessibility-settings-horizon.png differ diff --git a/docs/media/accessibility-settings.png b/docs/media/accessibility-settings.png new file mode 100644 index 000000000..6e5a6a810 Binary files /dev/null and b/docs/media/accessibility-settings.png differ diff --git a/docs/modpacks.md b/docs/modpacks.md index 814950597..0a3f12230 100644 --- a/docs/modpacks.md +++ b/docs/modpacks.md @@ -236,6 +236,10 @@ How the game loads them, without touching vanilla's path: so the same mod set gives the same ids. Saves store block names, so ids never reach the disk. - Loaders that read only `data/minecraft/` (recipes, loot, tags) read every namespace, as vanilla does. With no mods there is only `minecraft`, so nothing changes. +- **Namespaces.** A mod's files go under its id, and under the namespaces its manifest lists + when its Java original ships them so (`namespaces = ["kaisyn", "towns_and_towers"]` for Towns + and Towers, mod id `t_and_t`; docs/mods.md). No namespace has two owners: a mod whose id or + listed namespace another mod that is on already owns is left out, with both named in the log. - The overlay is built on the first start with a set of mods and kept for later starts. A stamp (`horizon-mod-content.stamp`) hashes the game executable, the base tables and every mod file's size and mtime. Adding, removing or editing a mod, or a new build of Horizon, rebuilds it. For @@ -326,7 +330,10 @@ A byte-order mark is dropped. For ATM10's 42 mods that is 19 files in 7 mods, an carried. No class file is copied. It upgrades from 1.21.1 to 26.3: vanilla-type recipes (ingredients), loot tables (`conditions` lists become one `condition`, `functions` become `modifier`, kinds move to `type`, tool matches on silk touch or shears become `minecraft:tool/can_silk_touch` and -`minecraft:tool/can_shear`), and the `items/` definitions 1.21.4 introduced. +`minecraft:tool/can_shear`, and number providers written as a bare `{"min", "max"}` get +`"type": "minecraft:uniform"`), and the `items/` definitions 1.21.4 introduced. 1.21.1 read such +a bare range as uniform and 26.3 refuses it: 304 of ATM10's carried tables have them (rolls, +counts, enchantment levels), and before the carry typed them their chests came out empty or short. Blocks and items come from the NeoForge oracle when `/oracle/facts.json` exists (step 6): every block the mod registers gets the vanilla template of the same vanilla class and states @@ -339,7 +346,9 @@ same states (Macaw's garage doors, multi-part gates). Recipes get the convention (`c:dyes/red`), filled from the oracle with vanilla's and the mod's own members. Without the oracle, templates are guessed from the blockstate's properties: the template whose properties include them with the fewest left over (models often ignore `powered` or `waterlogged`), the -block's name breaking ties (`_pane`, `_gate`, `_trapdoor`). +block's name breaking ties (`_pane`, `_gate`, `_trapdoor`). Walls and vines have the same +property names; sides tested as `true` / `false` make a vine (Chipped's 11 vines, which the game +refused as walls: their blockstates did not load). ### 1. Import @@ -472,24 +481,78 @@ Two cases the oracle fills in: 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. + The processors that build outside their template are carried too: Repurposed's and + Moog's pillar processors become the game's `horizon:pillar` (a column from a placeholder + block down to the ground, with the processor list they run on each of its blocks written + in), Repurposed's bottom pillars `horizon:bottom_pillar`, their fluid fix (a wall of the + structure's block over water and lava sources next to its open blocks) + `horizon:close_off_fluid_sources`, and YUNG's pillars (Better Fortresses, Better Jungle + Temples) and Better Fortresses' stair supports `horizon:yung_pillar` and + `horizon:stair_pillar`. They write only in the chunk being generated, as the mods do. + Dropped processors went from 570 to 456 in Repurposed Structures (its pillars, bottom + pillars and fluid fixes: 242 lists), 14 to 1 in Moog's, 10 to 5 in Better Fortresses and + 52 to 50 in Better Jungle Temples; the structure starts are the same (382 starts, 37,451 + pieces in chunks -64..63, seed 1234). Around spawn at seed 1234, 1,515 blocks change: the + 382 red glass placeholders under Repurposed's ocean outpost and pyramids become prismarine + columns, and their gravel and prismarine pillars reach the sea floor. In the Nether, the + Better Fortresses fortress at chunk (-23, 9) stands on its pillars: its terracotta + placeholders become nether bricks and 41,487 blocks of air (and 2,163 of lava) under it + become brick and magma columns down to the netherrack, 64,568 blocks changed in its 180 + chunks (the huge fungi there grow around the columns). + Better Ocean Monuments' ten processors are carried as well, so its monuments are no longer + dry: its templates are mostly air, which its air processor turns to water below the sea + level (the game's `horizon:flood_air`); its waterlog processor (`horizon:waterlog`) + waterlogs what can be and marks the water on the chunk's edges for postprocessing, its + structure void keeps the world's block (`horizon:keep_world_block`), its placeholder + blocks become slabs, sponges, seagrass, gravel and aged copper (vanilla's `rule`, and + `horizon:pick` with a new `nextFloat` for each chance, as the mod draws), and its legs and + Better Witch Huts' log and fence legs are `horizon:yung_pillar`. In the monument at chunk + (2, 8) (seed 1234), 318,512 blocks of air become water and none is left between y 30 and + 60 (227,034 before); its 5,142 placeholder blocks are gone. + Still taken out: Formations' biome replacements, Repurposed's air fix + (`close_off_air_sources`), 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. + and 1,405 with a loot table. The game read loot tables from `data/minecraft/` only, so every one of + those chests naming a mod's table opened empty; it now reads every namespace, and an + integer field written as a float (`"rolls": {"min": 3.0, ...}`, as Towns and Towers + writes them) counts as vanilla's int codecs count it. Of the 675 chest and other + non-block tables in ATM10's carried mods, 534 now fill a chest (seed 1; none before). + Repurposed's structure voids keep the world's block, as vanilla's `minecraft:block_ignore` + does (its 82 lists: mineshafts, the ocean and swamp villages, the ocean and taiga temples, + the jungle pyramid's hidden room). Before, the game placed them like any template block: + around the ocean mineshaft at chunk (-18, -54), seed 1234, 974 structure voids took the + place of 464 prismarine blocks of its walls, 225 of water (dry holes in the sea), 279 of + air and cave air and 6 rails and walls. - **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). + - **Namespaces besides the mod id.** Towns and Towers (mod id `t_and_t`) ships all 60 of its + structures under `kaisyn` and `towns_and_towers`, which carry used to leave in `outside/`. + Carry now claims a namespace for the mod when the mod's own files (its id's, its tag + additions and the namespaces already claimed) name ids in it, and no mod of the pack has + it as its id; it lists them in the manifest's `namespaces` (docs/mods.md). Files for mods + it supports (CTOV's `wares` and `monobank`, YUNG's `morevillagers` tags) and configs of + pack mods (`cristellib`) stay outside: of ATM10's 42 jars only T&T claims any. A tag of a + mod's own namespace that `replace`s is carried as an addition (no pack before it defines + it). In the 128×128-chunk square T&T has 7 starts at seed 1234 (its ocean wreckages, an + ocean village and outpost) and 7 at seed 2 (forest and snowy taiga villages, snowy + outposts), from none. - **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. + - **Advancements.** An `enter_block` criterion names its block as `blocks` in 26.3; 26.3 + skips 1.21.1's `block`, so the criterion matched any block the player entered. Carry renames + it (20 advancements in Regions Unexplored: "Downer", "From the Tree Tops" and "Light as a + Frog" were granted on the first dive into the sea, and its boat recipes' "in water" + criteria). - **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 @@ -543,19 +606,25 @@ Two cases the oracle fills in: (unchanged), and no pool that fails to decode (65 before #816 in the 64×64 centre). - 1,061 files were mapped (MVS 413, MNS 210, MSS 157, MES 110, Repurposed Structures 104, ChoiceTheorem's Overhauled Village 66), and 103 convention biome tags written. - - When Dungeons Arise and Structory use vanilla's types already. Towns and Towers does too, - but its 1,198 worldgen files sit under the `kaisyn` and `towns_and_towers` namespaces, not - its mod id `t_and_t`, and a mod's content may only use its own namespace (docs/mods.md), so - carry leaves them out and its 60 structures are missing. + - When Dungeons Arise, Structory and Towns and Towers use vanilla's types already (T&T's + namespaces are carried since the namespaces rule above). - Still lost, written in Java: - - 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; + - Formations' pieced structure (1, its one jigsaw-like type); - Repurposed's mineshafts, mansions and monuments, Better Mineshafts and two Better Dungeons types: Java structure types; - the block processors written in Java - (YUNG's banners, legs and decorations, Repurposed's pillars and fluid fixes, - Lithostitched's block swaps); + (YUNG's banners and decorations, Better Strongholds' legs, Lithostitched's block swaps); - MO Structures (38; its library is only on CurseForge). + - **Formations** (Overworld and Nether: 50 structures, 128 pool elements) places one + template per start at a height found in the noise columns under its corners and centre: on + the surface, on water or lava, or in a cave (on its floor, under its ceiling, buried in + stone, on a lava lake). Carry writes its `formations:simple` as the game's + `horizon:formations` (`horizon-world`'s `structure/formations.rs`, which reads the blocks + of ChunkGenerator.getBaseColumn through the structure context) and its pool element as + vanilla's with its `ground_level` under `horizon:ground_level`. In chunks -64..63 that adds + 39 Overworld and 672 Nether starts at seed 1234 (51 and 643 at seed 2), and leaves every + other start as it was. Its processors (biome replacements, aged blocks, bed colours, + plants) are still dropped, so its structures keep their templates' blocks. 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 diff --git a/docs/mods.md b/docs/mods.md index 97abb36aa..c5f181bd0 100644 --- a/docs/mods.md +++ b/docs/mods.md @@ -11,7 +11,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | Part | Where | State | |---|---|---| -| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud; tick, frame, chat and command hooks | +| The contract (WIT) | `crates/horizon-mod-sdk/wit/horizon.wit` | 0.1: log, game-read, chat, hud, storage; tick, frame, chat and command hooks | | SDK for mod authors | `crates/horizon-mod-sdk` | 0.1 | | Example mod | `crates/horizon-mod-sdk/examples/coords-hud` | coordinates, facing and time HUD, `/where`, `/coords` | | Runtime | `crates/horizon-mods` | wasmtime 36 LTS, component model | @@ -82,6 +82,7 @@ folder, loads no runtime and plays exactly like vanilla 26.3. | `game` | `game-read` | `get-player()`: x y z, yaw, pitch, health, food, dimension; `get-clock()`: game time, day time | | `chat` | `chat` | `show(text)`: a line only the local player sees, after the mod's name (8 per call) | | `hud` | `hud` | `set-panel(corner, lines)`, `clear()`: up to 16 lines of 256 characters | +| `storage` | `storage` | `get(key)`, `set(key, value)`, `delete(key)`: a per-mod folder of up to 64 files, 4 MiB total, at most 1 MiB written per call | | Hook (export) | When | |---|---| @@ -111,7 +112,6 @@ loading. Ordered by what the first native ports need ([research](research/java-m | `ui` | widgets: text, item icons, lists, a screen the mod owns, a settings page in Options > Mods | built on `ui_theme` so it matches the menus | | `world-read` | blocks and biomes around the player, within the render distance | minimaps, schematics | | `render` | world-space lines, boxes and ghost blocks in a per-frame budget | Litematica-style placement, waypoints | -| `storage` | a per-mod folder of key/value files, quota'd | settings, waypoints | | `registries` | new blocks, items, entities and recipes, mostly data: JSON models, textures, loot and recipes in the `.hmod`'s `assets/` and `data/` | server side; see [Multiplayer](#multiplayer) | | `server` | world events (block break/place, entity spawn/death, player join), game rules, server commands | runs where the world is simulated | | `net` | a mod's own client↔server channel (custom payloads) | only between the two halves of the same mod | @@ -192,6 +192,10 @@ allocation, next to a healthy mod). (`mod.:true`). 3. A mod that failed to load or stopped shows why, in red, on its row. +Two turned-on mods never share an `id` while running (it is also capability +`storage`'s directory): the one `find` lists first starts, the other stays +off with the reason on its row. + Benchmarks (`--benchmark`) never load mods. ## Making a mod @@ -208,8 +212,8 @@ cargo horizon-mod build # again after an edit: the running game relo `run` starts `horizon-client` (on `PATH`, or `--game PATH`, or `HORIZON_CLIENT`) with `--dev-mod target/horizon-mod/.hmod`. A dev mod is always on, and the game checks its file once a second: rebuild and it restarts -with "Mods reloaded" in chat. Its state starts over (persisted state comes with -`storage`). +with "Mods reloaded" in chat. Its in-memory state starts over; whatever it +saved with capability `storage` survives the reload. ### Template layout @@ -276,10 +280,30 @@ blocks and items by declaring them in `data//horizon/block/*.json` and "item": true } ``` -The fence: files go in the mod's own namespace (`assets//`, -`data//`), plus additions to vanilla tags (`data/minecraft/tags/`) and -to the convention tags NeoForge and Fabric mods share (`data/c/tags/`). -Templates and `sounds` name vanilla blocks; unknown keys are refused. Paths +The fence: files go in the mod's own namespaces (`assets//`, +`data//`, and those its manifest lists), plus additions to vanilla tags +(`data/minecraft/tags/`) and to the convention tags NeoForge and Fabric mods +share (`data/c/tags/`). +Templates and `sounds` name vanilla blocks; unknown keys are refused. + +Some Java mods ship their files under other names than their mod id (Towns +and Towers, mod id `t_and_t`, under `kaisyn` and `towns_and_towers`). A +content mod lists those in its manifest: + +```toml +id = "t_and_t" +api = "0.2" +capabilities = ["registries"] +namespaces = ["kaisyn", "towns_and_towers"] +``` + +A listed namespace is the mod's as its id is: its `assets/` and `data/` +files load, and the game reads its tags, recipes, names and loot. Blocks and +items are still declared under `data//horizon/` only. `minecraft`, `c` +and `horizon` cannot be listed. Two mods that are on may not own the same +namespace (one's id or listed namespace being the other's): the game keeps +the first in load order and leaves the other's content out, with +"mods A and B both use the namespace N; turn one of them off" in the log. Paths use vanilla's resource characters, at most 65,536 files, 16 MiB each and 512 MiB in all. A mod whose content is refused stays off, with the reason on its row. The game reads this content into its block and item tables @@ -378,8 +402,9 @@ none. 1. Design (this page) and the Java research. 2. SDK, example mod, runtime, `cargo horizon-mod`, the game's Mods page: API 0.1. -3. `keys`, `target`, `inventory-read`, `storage`, `ui`: enough for the first - native ports (zoom presets, AppleSkin-style food HUD, Jade-style tooltips). +3. `storage` (done), `keys`, `target`, `inventory-read`, `ui`: enough for the + first native ports (zoom presets, AppleSkin-style food HUD, Jade-style + tooltips). 4. Launcher Mods tab, the index, signatures; the Mods page shows cost and update state. 5. `recipes`, `world-read`, `render`: recipe viewer and schematics ports. diff --git a/docs/performance/startup-stage-3.md b/docs/performance/startup-stage-3.md index 28013e87c..b3258aada 100644 --- a/docs/performance/startup-stage-3.md +++ b/docs/performance/startup-stage-3.md @@ -16,6 +16,28 @@ The menu still needs its own artwork and renderer before interaction. The core h 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. +## CPU preparation before handoff + +The resource loader now prepares the game's entity models, item-frame models, +painting variants and creative inventory, plus the block-sprite and world-border +mip chains, before publishing `Loaded`. All startup entity models share one parsed +`entity-models.json` document. Each loader generation owns its prepared data; +restarting after a pack change discards that generation's models and uploads. +Fallible preparation finishes before the world-rest worker starts, so preparation +failure cannot leave a detached tail writing into the next loader generation. + +The event-loop handoff consumes the prepared game data and mip chains. GPU +pipeline creation, texture uploads, surface operations and audio initialization +still run on the main thread. Upload buffers are released after construction. +The handoff uses the current menu settings and title object directly, avoiding +another options-file read, theme-preference load and temporary title construction. +Synchronous harnesses and integrated servers prepare their game data inline. + +Logs now report worker CPU preparation time and the handoff's total, renderer and +`start_game` times separately. The reported 245 ms handoff (103 ms renderer, +118 ms `start_game`) predates this change; the new timings should be compared in +an otherwise identical build and GPU environment. + ## 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. diff --git a/docs/release-flow.md b/docs/release-flow.md index b72d896b8..354f9aff2 100644 --- a/docs/release-flow.md +++ b/docs/release-flow.md @@ -1,22 +1,32 @@ # Release flow How a change gets from a pull request to players: the checks a pull request passes, how it merges, and the -automatic releases that follow. Releases are automatic and frequent so the latest Horizon is always playable; -there is no separate development channel. +automatic releases that follow. Releases are automatic and frequent so the latest Horizon is always playable. +Each one goes out as a **beta** and becomes **stable** 6 hours later unless something holds it back +([Channels](#channels)): launchers and servers install stable builds unless their owner turns betas on. ## Pull request checks -The `checks` workflow (`.github/workflows/ci.yml`) runs two jobs on every pull request: +The `checks` workflow (`.github/workflows/ci.yml`) runs two jobs on every pull request (opened, pushed to or +reopened; labels never start it): | Job | Runs on | What | Time | | --- | --- | --- | --- | | `verify` | GitHub `ubuntu-latest` | Public-tree check, Python tests, rustfmt, clippy with warnings denied, Rust tests. Dependencies and the workspace build come from a cache saved by main's runs | ~4 min cold, less warm | -| `parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness | +| `parity / parity` | The Mac mini's runner (`ludovics-mac-mini`, label `horizon-game`) | The vanilla harnesses the change can affect (`tools/parity.py --changed `) | seconds when nothing is affected; minutes per affected harness | Pushes to main run `verify` only; the nightly audit covers main's harnesses. +`verify` is the check main requires, so it has no condition and runs in every run of `checks`: GitHub counts a +*skipped* required check as passed, and labels used to start runs whose `verify` was skipped, which let +auto-merge merge before the real `verify` finished. A pull request that changes no Rust (docs, tools) runs only its +quick steps and finishes in seconds. + ### The parity job +The job is `.github/workflows/parity.yml`, a reusable workflow: `checks` calls it for pull requests from this +repository, `run-parity.yml` for a fork's pull request a maintainer labels `run-parity`. + Horizon never downloads the game, so harnesses that compare with vanilla run only where the maintainer's own copy is: the Mac mini. Its runner runs as the maintainer's account and keeps its checkout between runs (`clean: false`), so the probes build incrementally into `.local/parity-target` and earlier passes stand. @@ -64,11 +74,11 @@ parallel, and main's own `checks` run catches the rare semantic conflict. `parity` becomes required once it has run green on pull requests for a while (a week without a false failure): ```sh -gh api -X POST repos/ludovic111/horizon/branches/main/protection/required_status_checks/contexts -f 'contexts[]=parity' +gh api -X POST repos/ludovic111/horizon/branches/main/protection/required_status_checks/contexts -f 'contexts[]=parity / parity' ``` -A skipped `parity` (a fork without the label, a run started by a label) counts as passed, so requiring it never -blocks a fork's pull request; the maintainer decides whether to run it. +A skipped `parity` (a fork's pull request without the label) counts as passed, so requiring it never blocks a +fork's pull request; the maintainer decides whether to run it. ## Game releases @@ -90,9 +100,12 @@ flowchart LR windows["Windows x64
GitHub windows-latest"] mac["macOS arm64
Mac mini runner
+ offscreen game run"] end - build --> publish["publish vYYYY.MM.DD[.N]
notes from the merged PRs"] - publish --> launcher(["launchers install it"]) - publish --> kira(["Kira posts it;
pings only with ### New"]) + build --> publish["publish vYYYY.MM.DD[.N] as a beta
notes from the merged PRs"] + publish --> beta(["launchers with Beta builds on install it"]) + publish --> promote{"promote.yml, every 30 min:
6 h old, smoke test, no release-blocker"} + promote --> stable["stable and latest
notes since the last stable"] + stable --> launcher(["every launcher and server installs it"]) + stable --> kira(["Kira posts it;
pings only with ### New"]) ``` ### When it releases @@ -122,6 +135,7 @@ commits) since the last **published** game release: | `skip-release` | Doesn't trigger a release and isn't listed in the notes | | `run-parity` | Runs the parity job once on a fork's pull request | | `parity-regression` | Opened by the nightly audit for a harness that fails on main | +| `release-blocker` | On an issue: holds every beta back from stable while it is open ([Channels](#channels)) | Pull requests without `feature` are listed under **Fixed**. Titles are written for players, since they become the notes. @@ -153,6 +167,82 @@ runs the game: GitHub's runners have neither a GPU worth the name nor the game f Kira posts every published release in #releases and pings the releases role only when the notes have a `### New` section. +### Channels + +Every game release is published as a **beta**, a GitHub pre-release, so GitHub's *latest* release stays the last +**stable** one. Launchers and `horizon-server update` install stable builds by default (the launcher's Settings +has a "Beta builds" switch; `horizon-server update --version ` takes one by name), and Kira announces a release +when it becomes stable: Discord's #releases only ever shows stable ones. + +`.github/workflows/promote.yml` runs `tools/release_channels.py promote` every 30 minutes. It promotes the newest +beta that + +- is newer than the stable release, +- has been out 6 hours, +- passed its release smoke test: the macOS build attaches `smoke-test.json` (the offscreen game run's report) only + when the game drew a world on the Mac mini, so a release built while `MAC_RUNNER` sends macOS to GitHub waits + for a hand, +- and isn't covered by an issue labelled `release-blocker`. An open blocker holds every beta; closed as completed + it still holds the betas published before it closed (they have the bug); closed as not planned it holds + nothing. Only the label and the issue's state count, never its text: whoever opened the issue can edit the + text after a maintainer labels it, so it can't pick which betas go out. + +Nothing older than the stable release is ever promoted, not even with `force`: GitHub's latest release is what +`horizon-server update` and `install.sh` download, so it only moves forward. + +When the oldest beta newer than the stable release has waited 24 hours, promote.yml opens an issue titled +"Promotion to stable has stalled" with the reason from the last check (a blocker left open, smoke tests not +running). It closes itself after the next promotion. + +Promoting marks the beta stable and latest and rewrites its notes to list everything since the previous stable +release (`release_train.py notes --stable`), so players who skipped the betas see all of it. Older betas stay +betas. By hand, from a phone too (GitHub app: Actions, promote, Run workflow): + +```sh +gh workflow run promote -f tag=v2026.10.19.03 # that beta now: no 6-hour wait, still no blocker +gh workflow run promote -f tag=v2026.10.19.03 -f force=true # even blocked or without a smoke test +gh workflow run promote -f dry_run=true # what would be promoted now +``` + +A beta's notes cover only what changed since the release before it (beta or stable), and say it is a beta. +`release_train.py decide` counts pull requests from the newest release of either channel, so betas don't +release the same changes again. + +### Signed checksums + +Every game and launcher release carries `SHA256SUMS` (the archives' SHA-256, `sha256sum`'s format) and +`SHA256SUMS.sig`: one base64 Ed25519 signature per line over `horizon release \n` followed by SHA256SUMS, +so a signed list can't be reused under another tag. + +- A `sign` job of its own makes them: `tools/ci/sign_release.sh` runs the runner's `sha256sum` and OpenSSL and + nothing else. It is the only job that holds the private key, the `RELEASE_SIGNING_KEY` secret of the + repository's `release` environment, which only real releases from main enter (`environment:` is empty in dry + runs, which sign with a throwaway key). No code from the repository runs beside the key, so no pull request + can read it by changing what a build compiles; the key is in no file, no log and no password vault, and nobody + needs to read it. +- The publish job then checks the signature the way launchers do (`horizon-release-sign verify --publishing`, + crates/horizon-release-sign), against the public keys built in from + `crates/horizon-release-sign/release-keys.txt`. While that file lists no key, releases go out with SHA256SUMS + alone and a warning (today's releases keep working). Once it lists one, a missing secret or a key it doesn't + list fails the release before anything is published, instead of publishing something launchers would refuse. +- Making the key: `tools/ci/new_release_key.sh` pipes a new key from `horizon-release-sign keygen` straight into + `gh secret set RELEASE_SIGNING_KEY --env release` and prints only the public key, which then goes into + release-keys.txt by pull request. + +**Rotating the key** (a new key every year, or at once if the old one may have leaked). The publish job signs +with every key the environment holds, `RELEASE_SIGNING_KEY` and `RELEASE_SIGNING_KEY_NEXT`, and the two names take +turns: + +1. `tools/ci/new_release_key.sh ` makes the next key; add its public key to release-keys.txt + beside the old one. From then on every release is signed with both keys (one line each). +2. Wait until launchers and servers built with both keys are in use (a few weeks: launchers update themselves). +3. Delete the old key's secret (`gh secret delete --env release`) and its line in release-keys.txt. + The next rotation makes its new key under the name just freed. + +If the old key may have leaked, skip the wait: remove its public key from release-keys.txt at once and delete +its secret. Launchers built before the new key cannot check releases signed only with it: they refuse to install +them with a clear message, and players download the launcher again from the website once. + ### Starting one by hand ```sh @@ -181,7 +271,8 @@ A bad release is withdrawn by turning it back into a draft: gh release edit v2026.10.15.01 --draft ``` -Launchers list only published releases: the previous version becomes the newest one again, launchers that +A beta that is not promoted yet needs no rollback: label an issue about it `release-blocker`. For a stable +release: launchers list only published releases, so the previous version becomes the newest one again, launchers that didn't install the bad one won't, and players who did can pick the previous version in the launcher's version list (`launcher/src/backend.rs` tests `withdrawn_release_is_never_offered`). The tag stays, so the next release that day takes the next number, and its notes start from the last *published* release, so they list the diff --git a/docs/security.md b/docs/security.md new file mode 100644 index 000000000..7dead0e83 --- /dev/null +++ b/docs/security.md @@ -0,0 +1,110 @@ +# Security + +How Horizon keeps its code and its downloads safe while most of the work is done by AI agents and releases go out +by themselves, including when Ludovic isn't at his computer. In plain words: what someone could have done before, +what stops them now, and what still needs Ludovic. + +## Who does what + +- **Agents** (Claude sessions run by Ludovic) write most pull requests, review them, merge them and answer + reports. Everything an agent posts on GitHub says so ("Opened by Ludovic's AI agent"). +- **Contributors** send pull requests from their forks like on any open-source project. +- **Players** report bugs on Discord and GitHub. Kira, the Discord bot, files their reports as issues. +- **Releases** are automatic: every merged change that players run ships within the hour. + +## What could go wrong before (October 2026) + +1. **Instructions hidden in a report.** Someone could write "ignore your previous instructions and…" in a + Discord message or an issue. Agents read those reports while working with Ludovic's full GitHub account. +2. **A check that counted as passed without running.** Adding a label to a pull request started a second run of + the checks in which `verify` was *skipped*, and GitHub counts a skipped required check as passed. Two pull + requests merged before their real check had finished. +3. **Every release went straight to every player.** A broken or malicious build reached every launcher within + minutes, with nobody looking at it first. +4. **Downloads trusted GitHub alone.** Anyone who got hold of a token that can write to the repository could + replace a release's files, and launchers and servers would install them. +5. **The release machinery was ordinary code.** A pull request could change the workflows that build and publish + releases as easily as it changes a texture. + +## Where things stand (19 October 2026) + +The next section describes the design once every part is in place. Some parts are live, some are waiting to merge, +and some are waiting for Ludovic: + +| Part | Today | +| --- | --- | +| `verify` always runs | **Live** (#1010). | +| Fork pull requests need approval | **Live**: every outside contributor's workflows wait for a maintainer's approval. | +| Private vulnerability reporting | **Live** (see the end of this page). | +| Signed checksums on releases | **Live** for new releases (#1011): the `release` environment holds the key, and its public half is in `release-keys.txt` (#1023). Releases from before then are unsigned. | +| Launchers and servers checking signatures | **Not yet**: #1014 waits as a draft until a signed stable game release and a signed launcher release exist. Until then they trust GitHub's checksum, as before. | +| Beta, then stable | **Not yet** (#1012): every release still goes straight to every player. The launcher's "Beta builds" switch is already there (#1013), and has no betas to offer yet. | +| Reports marked suspicious | **Partly**: the scan of Discord for agents does it. Kira's issues do it once its pull request merges. | +| Code owners' review of the pipeline | **Not yet**: `.github/CODEOWNERS` and its protection (#1015) wait for the App, below. Until then pipeline changes merge like any other once `verify` passes. | +| Agents on their own GitHub App | **Not yet**: prepared, waiting for Ludovic to create it. Agents still use his account. | +| Mac mini releases from a clean checkout | **Waiting to merge** (#1024): see "What this doesn't solve". | + +## What stops it now + +- **Reports are data, never instructions.** Agents receive people's text only inside quoted blocks marked as + untrusted, with attachments as plain links. Text that looks aimed at an AI (talking to "the AI", asking to run + commands, asking for passwords or keys, linking to scripts, hidden characters) is marked **suspicious**, and the + agent coordinating the others sees the mark. +- **`verify` always runs.** Labels no longer start the checks, and the required `verify` job has no condition, so + the only `verify` a change can have is one that ran. Main requires it, from GitHub Actions only, for everyone, + admins included. +- **Beta, then stable.** Every release is first a **beta**. It becomes **stable**, the version launchers and + servers install by themselves, only after it has been out 6 hours and passed its smoke test (the game started and + drew a world on the Mac mini), and only while no issue labelled `release-blocker` is open. If no beta has + become stable for a day, an issue says so. Players who want the + newest builds at once turn on "Beta builds" in the launcher's Settings. Discord announces stable releases only. +- **Signed updates.** Each release carries a list of its files' checksums, signed with Horizon's release key. The + launcher (for the game and for itself) and `horizon-server update` check that signature against the public key + built into them, then check the download against the list. Anything unsigned, signed with another key, signed + for another version, or changed in any way is refused with a message saying why. Releases from before signing + stay installable, for going back to an older version, but only with the exact files they had when signing + began: their checksums are built into the launcher and the server too. The private key exists only as + a secret of GitHub's `release` environment, which only real releases from main can use. The job that signs runs + nothing from the repository but a short script calling OpenSSL, so no pull request can read the key by changing + the code that gets built. Nobody, Ludovic included, ever needs to see it. +- **The release machinery needs Ludovic.** The workflows, the release and signing tools, the update-checking code + and the installers are listed in `.github/CODEOWNERS`. Once main's protection requires code owners' reviews, a + change to any of them waits for Ludovic's approval. Everything else still merges as soon as its checks pass. +- **Agents get their own, smaller identity** (prepared, switched on by Ludovic). The `horizon-agent` GitHub App + can read and write code, pull requests and issues, and read the checks. It cannot change settings, workflows, + secrets or members, and its tokens last an hour. Once agents use it, their pull requests are the app's, and + Ludovic approves the rare pipeline change with one tap. + +## What still needs Ludovic + +- **Approving pipeline changes** (rare): a pull request touching a file in `.github/CODEOWNERS`. +- **Holding a release back or speeding one up**, from his phone if he likes. Label an issue `release-blocker` to + hold every beta until it is closed. Run the `promote` workflow (GitHub app: Actions, + promote, Run workflow) to make a beta stable at once. +- **Creating the GitHub App**: one link, "Create GitHub App", then "Install". His login, his clicks. +- **Fork pull requests**: their checks run only after a maintainer approves them, and they run on the Mac mini only + after a maintainer has read them and added `run-parity`. +- **A leaked key**: rotate it (docs/release-flow.md, "Signed checksums"). Launchers older than the new key then + refuse new versions until players download the launcher again. + +## What this doesn't solve + +- **Code that merges is code that ships.** Signing proves a build came from Horizon's pipeline, not that the code + is good. Against a bad change, the safety nets are the checks and harnesses, review, the 6-hour beta and the + release-blocker label. +- **Until agents switch to the App**, they still work with Ludovic's own account, so nothing technical tells his + actions from theirs. Code owners' reviews are switched on together with the App. +- **The Mac mini** builds the macOS release and also runs pull requests' parity checks: a pull request from this + repository runs its code there before review, and a fork's does once a maintainer adds `run-parity`. Code + running there as the runner's user could tamper with what the next release builds. Releases check out clean + (#1024), which removes anything a pull request left in the work folder by accident, but + not a deliberate attack. The protection is review: only agents and maintainers push to this repository, and a + maintainer reads a fork's change before labelling it. +- **The first install** with `install.sh` / `install.ps1` checks the checksum GitHub publishes, not the + signature: verifying Ed25519 signatures needs OpenSSL 3, which macOS doesn't ship. Every update after that + checks the signature. + +## Reporting a security problem + +Use GitHub's private vulnerability reporting (the repository's **Security** tab, "Report a vulnerability"), not a +public issue or Discord. Say what you found and how to reproduce it; we answer there. diff --git a/docs/server.md b/docs/server.md index 272148d49..4d623b6e8 100644 --- a/docs/server.md +++ b/docs/server.md @@ -289,6 +289,9 @@ restart_on_crash = true [backups] every = "6h" # automatic backups while the server runs: 30m, 6h, 1d...; "0" turns them off keep = 12 # automatic backups kept (backups made by hand are never deleted) + +[updates] +keep = 1 # other releases kept by updates, besides the one in use and the one rollback goes to ``` This is the file `init` writes today (PR 4 adds `[panel] bind = "127.0.0.1:8130"` and `allow_public = @@ -305,9 +308,12 @@ a typed key set again under `[properties]` and values vanilla would refuse. Plan After it stops, the supervisor compares the file with what it wrote and copies any changed keys back into `server.toml`, so an in-game change survives the next start. Edits go through `toml_edit`, so the owner's comments and order are kept. -- **Reload (planned).** The four lists already reload through the engine (`whitelist reload`). `reload` will - send what can change live and say which settings need a restart. A real hot reload (view distance, MOTD) needs engine - support and comes later. +- **Changes without opening the file.** `horizon-server config set KEY=VALUE...` (the launcher's Servers + page uses it) writes through `toml_edit`, checks the result as `server.toml` is checked, and writes nothing + if a value is wrong. On a running server it sends what vanilla changes live through its console: + `difficulty`, `defaultgamemode` and `whitelist on|off`; the backup settings apply at once because the + supervisor reads them each time. Everything else waits for the next start, and the command says which. A + real hot reload (view distance, MOTD) needs engine support and comes later. - `server.properties`, `ops.json`, `whitelist.json`, `banned-*.json` and `world/` keep vanilla's names and formats. A vanilla server folder works as is, and so does going back to vanilla. @@ -324,6 +330,7 @@ horizon-server op|deop horizon-server whitelist on|off|list|add|remove [player] horizon-server backup [NAME] backups restore [--yes] horizon-server import +horizon-server config [--json] config set KEY=VALUE... [--json] horizon-server service install|uninstall|print [--system] horizon-server panel the panel's address and a one-time login link horizon-server update [--check] [--version vX.Y.Z] [--timeout S] rollback [--timeout S] @@ -419,8 +426,11 @@ runtime or new dependency. Server-sent events can replace the polling later if a and kept as it is). The supervisor keeps running as it was: the new `horizon-server` itself takes over the next time the server starts (`stop` and `start`, or the service's restart). A stopped server is switched and its new game checked to load; it starts on the new release next time. One install serves - every server folder on the machine, so each one runs the new release from its next start. Old releases - stay in `/releases/` until they are deleted by hand (keep `current` and `previous`). + every server folder on the machine, so each one runs the new release from its next start. Once the new + game is up (or a stopped server is switched), old releases are deleted from `/releases/`: the one in + use, the one `previous` names (where `rollback` goes), the one the running `horizon-server` itself came + from, and the `updates.keep` newest of the others (1 by default) stay. A release that can't be deleted (a + program still running from it on Windows) is left for the next update. ## 8. Control API and MCP diff --git a/docs/shader-packs.md b/docs/shader-packs.md index 5f8e88c20..3cd068f2d 100644 --- a/docs/shader-packs.md +++ b/docs/shader-packs.md @@ -21,6 +21,7 @@ Both are off by default. With no pack selected the renderer draws exactly what i | Java shader packs: `shaders.properties` (`horizon_shaderpack::properties`: screens, sliders, profiles, `program.*.enabled`, image formats, blend modes) | done, no screen yet: read like Iris for the three test packs | | Java shader packs: full-screen pass plan (`horizon_shaderpack::pipeline`: `DRAWBUFFERS`/`RENDERTARGETS`, `colortexN` formats and clearing, buffer flips) | done: planned for the three test packs | | Java shader packs: full-screen passes drawn (`java_pack.rs`, `gfx/java_stages.rs`: `begin`, `prepare`, `deferred*`, `composite*`, `final` over Horizon's world) | first slice: BSL and Complementary run (below) | +| Java shader packs: custom uniforms (`horizon_shaderpack::uniforms`), `sunPathRotation`, `clouds`/`sun`/`moon`, eye light | done for the full-screen passes (below) | | Java shader packs: `gbuffers_*`, `shadow`, custom textures, images, compute, option screen | planned | ## How the renderer draws a frame today @@ -262,7 +263,8 @@ A `shaders/` folder of GLSL programs, named by where Iris (and OptiFine before i Order: preprocessor and legaliser until the three test packs parse; then `composite`/`final`/`deferred` with the uniforms; then `gbuffers_terrain`, `gbuffers_water` and `gbuffers_skybasic`/`skytextured` (the packs' look comes -from these); then entities, hand, weather, clouds; then `shadow`; then custom uniforms, custom textures, compute. +from these); then entities, hand, weather, clouds; then `shadow`; then custom textures, compute. Custom uniforms +are done (below). The test set is Complementary Reimagined, BSL and Sildur's Vibrant. Their licences don't allow redistribution, so they are downloaded for development only, outside the repository (never committed, never shipped, never uploaded); @@ -355,15 +357,26 @@ What makes Horizon look like OpenGL to the pack: `noisetex`, `iris_compare` for shadow lookups) instead of one each. - **`isnan`/`isinf`** test the float's bits: Metal compiles with fast math, which folds `x != x` to false, and a NaN then stays forever in Complementary's TAA history (the picture turns black). -- **Uniforms.** Matrices, camera, view size, time, sun and moon, weather, fog and sky colour, eye state come from the - frame; `eyeBrightness(Smooth)` is `(0, 240)` under the sky; `noisetex` is a fixed 256² noise. +- **Uniforms.** Matrices, camera, view size, time, weather, fog and sky colour, eye state come from the frame; + `eyeBrightness` is the block and sky light (× 16) of the camera entity's eye block, and `eyeBrightnessSmooth` follows + it with the pack's `eyeBrightnessHalflife` (Iris's `SmoothedFloat`); `sunPosition`, `moonPosition`, + `shadowLightPosition`, `sunAngle` and `shadowAngle` are `CelestialUniforms`' (the sky's `sun_angle` and `moon_angle` + turned by Y -90, the pack's `sunPathRotation` about Z, then the angle about X); `noisetex` is a fixed 256² noise. +- **Custom uniforms.** `uniform..` and `variable..` in `shaders.properties` are evaluated + each frame (`horizon-shaderpack`'s `uniforms.rs`: Iris's operators and priorities, its functions, `smooth` with + `SmoothFloat`'s half-lives). A definition naming something Horizon doesn't provide (`biome`, `blindness`...) is left + out with everything that uses it, as Iris leaves out the ones it can't resolve: the uniform stays 0. +- **The vanilla sky.** While the pack runs, `sunPathRotation` tilts Horizon's sun, moon and stars as Iris tilts + vanilla's, `clouds = off | fast | fancy` replaces the cloud option, and `sun = false` / `moon = false` hide those. + Complementary and Sildur's turn the vanilla clouds off: drawn anyway, they wrote depth the packs' light shafts and + fog took for terrain. Measured on the Mac mini (M4 Pro) with the packs' default options: BSL v10.1.8 and Complementary Reimagined r5.9.3 grade and light Horizon's world as their post-processing would. Sildur's Vibrant v2.02 draws only its sky: its `deferred` reads the albedo `gbuffers_*` write to `colortex4`. Without `gbuffers_*` and `shadow`, no pack has its shadows, water or sky look yet; Distant Horizons' and Voxy's depth read as far. Not supported yet: images and compute (`.csh`; a pack that needs them doesn't load), mipmapped targets (`colortexNMipmapEnabled` is read but -ignored), custom textures, custom uniforms, the option screen; shadow matrices are identity. +ignored), custom textures, the option screen; shadow matrices are identity. ### Order to implement @@ -381,5 +394,5 @@ ignored), custom textures, custom uniforms, the option screen; shadow matrices a 5. **Entities, block entities, hand, weather, clouds, particles** `gbuffers_*`. 6. **Shadow pass**: terrain and entities from the sun into `shadowtex0/1` and `shadowcolor0/1`, culled from the light's view, with the pack's distortion. -7. **The rest**: custom uniforms (`uniform.*` expressions), custom textures, compute programs and images, per-dimension +7. **The rest**: custom textures, compute programs and images, per-dimension folders, `entity.properties`/`item.properties`. diff --git a/launcher/Cargo.lock b/launcher/Cargo.lock index bde1037b3..5503e0471 100644 --- a/launcher/Cargo.lock +++ b/launcher/Cargo.lock @@ -2668,6 +2668,7 @@ dependencies = [ "horizon-prepare", "horizon-telemetry", "horizon-theme", + "image", "keyring", "oo7", "pulldown-cmark", diff --git a/launcher/Cargo.toml b/launcher/Cargo.toml index 34af6e2a1..09458b766 100644 --- a/launcher/Cargo.toml +++ b/launcher/Cargo.toml @@ -32,6 +32,9 @@ horizon-port-pack = { path = "../crates/horizon-port-pack" } horizon-telemetry = { path = "../crates/horizon-telemetry" } # The session file's random name. getrandom = "0.3" +# Players' heads on the Servers page, from the default skins in the player's own game files (already +# in the lockfile through gpui). +image = { version = "0.25", default-features = false, features = ["png"] } # Microsoft account secrets in the OS keychain: the Secret Service on Linux through oo7 (the same # build gpui uses), Keychain and Credential Manager through keyring. diff --git a/launcher/README.md b/launcher/README.md index b111113f2..2f0bf35f5 100644 --- a/launcher/README.md +++ b/launcher/README.md @@ -17,8 +17,7 @@ The opening, then Play ([clip](docs/opening.webm)): - **Play**: prepares resources as `PLAY.txt` describes (your launcher's 26.3 install, the 26.3 server jar from that version's own json, and Java 25) and copies its sounds from your launcher's asset store (`horizon-prepare sounds`; a launcher install without them only - leaves the game silent), then starts the client, or a - server (`--dedicated --nogui`) in a folder you choose, with a live console. Preparing is + leaves the game silent), then starts the client. Preparing is horizon-prepare: linked into the launcher, used in-process when a version ships the same preparer sources, else that version's own `horizon-prepare`; versions released before it still prepare with their Python script and need Python 3.10+. Before importing, @@ -35,11 +34,42 @@ The opening, then Play ([clip](docs/opening.webm)): **Play** starts the game as the pack's own profile (`ports//home/` in the game's home: its own saves and options) with those mods. Nothing is uploaded or shared: mod jars and ports stay on this computer. +- **Servers**: host a world for friends with buttons. **Create a server** asks for a name, a world + (a new one, with an optional seed, or a copy of one of your single-player worlds), the game mode, + difficulty, most players, who can join (friends only, the default, or anyone with the address) + and your agreement to the Minecraft EULA; with the defaults (tick the EULA, press Create) you get + a friends-only survival world with you as its operator. Each server then has **Start**, **Stop** and **Restart**, its state (also + when it crashed and was restarted), players online with their heads, TPS, MSPT and RAM, the + address friends on your network type with **Copy**, a console that takes commands, **Open the + web panel**, and four tabs: **Overview**; **Players** (online players with Make operator, Kick + and Ban; who may join, with Friends only, Let in and Remove; Unban); **Settings** (the message + in the server list, game mode, difficulty, PvP, most players, view and simulation distance, + port, account checks, **Run in the background and at login**); **Backups** (Back up now, the + list with dates and sizes, Restore with a confirmation, Back up automatically, and **Updates**: + Check for updates, Update now with its automatic rollback, and how many older versions to + keep). Changes the running game can take apply at once, the others say "Restart to apply". + Everything goes through `horizon-server` itself ([docs/hosting.md](../docs/hosting.md)): + the launcher copies a prepared version's programs and game files into `server-runtime/` laid + out as `install.sh` does, runs `horizon-server init`, `config`, `start`, `backup`, `restore`, + `update` and `service` there, and talks to a running server through its control API. Problems + are said in plain words, with a button when there's a fix (another port, the game files, the + EULA). + **Friends over the internet** (on Overview) uses Tailscale: it says whether Tailscale is + installed and signed in (with Install, Sign in and Check again; signing in is always yours, in + Tailscale's own app or page), shows this computer's Tailscale name and address with **Copy**, + and invites a friend to this one computer: in the admin console, or here with an access token + you make there (kept in the system keychain), which also lists invitations with Withdraw / + Stop sharing and offers **Limit them to Minecraft**: when your tailnet has Tailscale's default + access controls, one click changes them so friends you share with reach only the server's + port (Remove the limit undoes it); custom access controls are never rewritten, the page gives + the rule to add instead. Horizon never turns on Funnel. - **Patch notes**: each release's notes, newest first, with a link to GitHub Sponsors. Quiet "Discord" and "Website" links sit in the footer. Data lives in the platform's data directory (`~/.local/share/horizon-launcher` on Linux, `~/Library/Application Support/horizon-launcher` on macOS, `%APPDATA%\horizon-launcher` on -Windows): `versions//`, `server-jars/`, `server/` and `settings.json`. +Windows): `versions//`, `server-jars/`, `server/`, `settings.json`, and for the Servers +page `servers.json` (the list), `servers//` (the servers created there) and +`server-runtime/` (the programs and game files they run). - **Settings**: install new Horizon versions automatically (on unless you turn it off; the selected version only moves to the new one if you were on the newest), the opening animation, @@ -58,6 +88,9 @@ Windows): `versions//`, `server-jars/`, `server/` and `settings.json`. (`{"discord": "...", "sponsor": "...", "website": "..."}`), so they change without a launcher release. Offline, the launcher uses the same values built in; an empty address hides its button. +Long pages, dialogs, the server console and data previews have a visible scrollbar when +their content overflows. Drag the thumb or click the track to navigate without a mouse wheel. + ## Updates The launcher looks for a newer Horizon release when it starts and every four hours while it @@ -105,6 +138,12 @@ The same binary is a command-line tool; without a subcommand it opens the window horizon-launcher modpack port [--from ] [--version ] get the jars and carry them over horizon-launcher modpack play [--version ] play it as its own profile horizon-launcher modpack remove + horizon-launcher servers [list] the servers hosted from the launcher, and whether they run + horizon-launcher servers create [--name N] [--seed S | --copy-world DIR] [--mode M] [--difficulty D] + [--max-players N] [--open] [--check-accounts] [--player NAME]... --accept-eula + horizon-launcher servers set-up [--version ] copy a prepared version's programs and game files for servers + horizon-launcher servers run -- for example: servers run "My server" -- start + horizon-launcher servers forget take it off the list (its folder stays) horizon-launcher benchmark [--repeats N] measure the launcher (see Performance log) horizon-launcher data [status] what data collection is allowed, the install ID, what waits horizon-launcher data allow|deny performance, crashes, bugs, benchmarks @@ -213,7 +252,8 @@ bundled so the type is the same on every platform. ## Screenshots -![Server](docs/server.png) +![Servers](docs/servers.png) +![Friends over the internet](docs/servers-tailscale.png) ![Modpacks](docs/modpacks.png) ![Versions](docs/versions.png) ![Patch notes](docs/patch-notes.png) diff --git a/launcher/docs/server.png b/launcher/docs/server.png deleted file mode 100644 index d292411fd..000000000 Binary files a/launcher/docs/server.png and /dev/null differ diff --git a/launcher/docs/servers-tailscale.png b/launcher/docs/servers-tailscale.png new file mode 100644 index 000000000..ce040f1e9 Binary files /dev/null and b/launcher/docs/servers-tailscale.png differ diff --git a/launcher/docs/servers.png b/launcher/docs/servers.png new file mode 100644 index 000000000..bb644f4c0 Binary files /dev/null and b/launcher/docs/servers.png differ diff --git a/launcher/src/backend.rs b/launcher/src/backend.rs index 8d1036d22..ee33942b2 100644 --- a/launcher/src/backend.rs +++ b/launcher/src/backend.rs @@ -31,6 +31,8 @@ pub struct Release { pub body: String, pub date: String, pub asset: Option<(String, u64)>, + /// A beta: a game release not promoted to stable yet (a GitHub pre-release, docs/release-flow.md). + pub beta: bool, } #[cfg(all(target_os = "linux", target_arch = "x86_64"))] @@ -169,6 +171,7 @@ fn parse_releases( .take(10) .collect(), asset: found, + beta: r["prerelease"].as_bool().unwrap_or(false), }); } out.sort_by(|a, b| compare_versions(&b.tag, &a.tag)); @@ -247,6 +250,16 @@ pub fn latest(releases: &[Release]) -> Option<&Release> { releases.iter().find(|r| r.asset.is_some()) } +/// The releases a launcher installs by itself: stable ones, and betas too when the player turned +/// "Beta builds" on in Settings. +pub fn channel(releases: &[Release], beta: bool) -> Vec { + releases + .iter() + .filter(|r| beta || !r.beta) + .cloned() + .collect() +} + /// The community, sponsor and website links, from `launcher/links.json` on main, so they can change /// without a launcher release. An empty address hides its button. #[derive(Clone, Debug, PartialEq, serde::Serialize)] @@ -1300,7 +1313,8 @@ pub fn server_dir(requested: Option) -> PathBuf { .unwrap_or_else(|| data_dir().join("server")) } -fn need_prepared(tag: &str) -> Result<(), String> { +/// Whether `tag` is prepared, with the run-time reports it needs completed when another copy has them. +pub fn need_prepared(tag: &str) -> Result<(), String> { if is_prepared(tag) { complete_reports(&versions_dir(), tag); Ok(()) @@ -1462,10 +1476,17 @@ pub fn launcher_update(releases: &[Release]) -> Option { pub fn releases_and_updates( on_releases: impl FnOnce(Result, String>), ) -> Result { - releases_and_updates_with(release_list, installed, launcher_releases_in, on_releases) + releases_and_updates_with( + Settings::load().beta_builds, + release_list, + installed, + launcher_releases_in, + on_releases, + ) } fn releases_and_updates_with( + beta: bool, load: impl FnOnce() -> Result, installed: impl FnOnce() -> Vec, launchers: impl FnOnce(&serde_json::Value) -> Vec, @@ -1479,7 +1500,7 @@ fn releases_and_updates_with( } }; let releases = parse_releases(&list, ASSET, is_game_tag); - let horizon = horizon_update(&releases, &installed()); + let horizon = horizon_update(&channel(&releases, beta), &installed()); on_releases(Ok(releases)); Ok(Updates { horizon, @@ -1501,12 +1522,16 @@ pub fn select_after_update(selected: Option<&str>, installed_before: &[String]) } } -/// Installs `tag` (or the newest release with "latest"), then updates the selection as +/// Installs `tag` (or with "latest" the newest release of the player's channel), then updates the selection as /// `select_after_update` says when `as_update`, or always selects it otherwise. pub fn install_tag(tag: &str, as_update: bool, progress: impl Fn(f32)) -> Result { let releases = releases()?; let release = if tag == "latest" { - latest(&releases).ok_or("No release has a build for this platform yet.")? + let beta = Settings::load().beta_builds; + releases + .iter() + .find(|r| r.asset.is_some() && (beta || !r.beta)) + .ok_or("No release has a build for this platform yet.")? } else { releases .iter() @@ -1926,6 +1951,9 @@ pub struct Settings { /// default. Appended after the launcher's own arguments, so they can add to or override them. #[serde(default, skip_serializing_if = "String::is_empty")] pub game_args: String, + /// Whether new versions include betas (releases not promoted to stable yet). Off by default. + #[serde(default)] + pub beta_builds: bool, } impl Settings { @@ -2117,6 +2145,36 @@ mod tests { assert_eq!(offered(&["v2026.10.15.1", "v2026.10.14"]), None); } + /// Betas (GitHub pre-releases) install by themselves only with "Beta builds" on; the stable + /// channel waits for promote.yml (docs/release-flow.md, "Channels"). + #[test] + fn updates_follow_the_stable_channel_unless_betas_are_on() { + let asset = ASSET.unwrap_or("horizon-linux-x86_64.tar.gz"); + let list = serde_json::json!([ + {"tag_name": "v2026.10.19.02", "prerelease": true, "assets": [{"name": asset, "browser_download_url": "b", "size": 1}]}, + {"tag_name": "v2026.10.19.01", "assets": [{"name": asset, "browser_download_url": "s", "size": 1}]}, + ]); + let releases = parse_releases(&list, Some(asset), is_game_tag); + assert_eq!( + releases.iter().map(|r| r.beta).collect::>(), + [true, false] + ); + let offered = |beta: bool, installed: &[&str]| { + let installed: Vec = installed.iter().map(|t| t.to_string()).collect(); + horizon_update(&channel(&releases, beta), &installed).map(|r| r.tag) + }; + assert_eq!(offered(false, &[]), Some("v2026.10.19.01".into())); + assert_eq!( + offered(true, &["v2026.10.19.01"]), + Some("v2026.10.19.02".into()) + ); + assert_eq!(offered(false, &["v2026.10.19.01"]), None); + // A beta installed earlier is never "updated" to an older stable build. + assert_eq!(offered(false, &["v2026.10.19.02"]), None); + assert!(!Settings::parse("{}").beta_builds); + assert!(Settings::parse(r#"{"beta_builds": true}"#).beta_builds); + } + #[test] fn the_version_is_the_one_the_release_workflow_injects() { assert_eq!(version_or(Some("0.4.2")), "0.4.2"); @@ -2135,6 +2193,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), + beta: false, }; assert!(launcher_update(&[r(format!("{LAUNCHER_TAG_PREFIX}{VERSION}"))]).is_none()); assert_eq!( @@ -2176,6 +2235,7 @@ mod tests { body: String::new(), date: String::new(), asset: Some(("u".into(), 1)), + beta: false, }; let releases = [r("v2026.10.13"), r("v2026.10.12")]; assert_eq!( diff --git a/launcher/src/backend/release_loading_tests.rs b/launcher/src/backend/release_loading_tests.rs index befef2279..ab01ab437 100644 --- a/launcher/src/backend/release_loading_tests.rs +++ b/launcher/src/backend/release_loading_tests.rs @@ -45,6 +45,7 @@ fn baseline(load: impl Fn() -> Result) -> (Vec Result) -> (Vec, Updates) { let mut releases = None; let updates = releases_and_updates_with( + false, load, installed_fixture, |list| parse_releases(list, LAUNCHER_ASSET, is_launcher_tag), @@ -81,6 +82,7 @@ fn errors_reach_releases_and_updates_without_fallback() { ] { let mut published = None; let result = releases_and_updates_with( + false, || Err(error.into()), || panic!("no installed scan after failure"), |_| panic!("no fallback after failure"), @@ -95,6 +97,7 @@ fn errors_reach_releases_and_updates_without_fallback() { fn publish_games_before_older_launcher_fallback() { let events = RefCell::new(Vec::new()); let result = releases_and_updates_with( + false, || Ok(serde_json::json!([{"tag_name": "v2026.10.14", "assets": []}])), Vec::new, |list| { @@ -129,6 +132,7 @@ fn failed_launcher_fallback_keeps_game_result_and_checks_stay_fresh() { for day in [14, 15] { let mut published = None; let updates = releases_and_updates_with( + false, || { requests.fetch_add(1, Ordering::Relaxed); Ok(serde_json::json!([{"tag_name": format!("v2026.10.{day}")}])) diff --git a/launcher/src/cli.rs b/launcher/src/cli.rs index d18a60dac..a43529db0 100644 --- a/launcher/src/cli.rs +++ b/launcher/src/cli.rs @@ -21,6 +21,58 @@ struct Cli { command: Option, } +#[derive(Subcommand)] +enum ServersCmd { + /// The servers, their folder and whether they run + List, + /// Create a server; with no options it is a new world, survival, normal, 10 players, friends only + Create { + #[arg(long, default_value = "My server")] + name: String, + /// The new world's seed (default: random) + #[arg(long, conflicts_with = "copy_world")] + seed: Option, + /// Start from a copy of this world folder (one of your saves) + #[arg(long)] + copy_world: Option, + #[arg(long, default_value = "survival", value_parser = ["survival", "creative", "adventure", "spectator"])] + mode: String, + #[arg(long, default_value = "normal", value_parser = ["peaceful", "easy", "normal", "hard"])] + difficulty: String, + #[arg(long, default_value_t = 10)] + max_players: u32, + /// Let anyone in (no whitelist) + #[arg(long)] + open: bool, + /// Check players' Minecraft accounts (they must sign in with Microsoft) + #[arg(long)] + check_accounts: bool, + /// Who may join (repeatable); the first becomes an operator + #[arg(long = "player")] + players: Vec, + /// The installed version whose programs and game files servers use, if none are set up yet + #[arg(long)] + version: Option, + /// Agree to the Minecraft EULA (https://aka.ms/MinecraftEULA) + #[arg(long)] + accept_eula: bool, + }, + /// Copy an installed, prepared version's programs and game files for the servers (again) + SetUp { + #[arg(long)] + version: Option, + }, + /// Run a horizon-server command on a server, for example: servers run "My server" -- status + Run { + /// The server's name or folder + server: String, + #[arg(last = true, required = true)] + args: Vec, + }, + /// Take a server off the list (its folder stays) + Forget { server: String }, +} + #[derive(Subcommand)] enum AccountCmd { /// The signed-in accounts and which one plays @@ -205,6 +257,12 @@ enum Cmd { #[command(subcommand)] action: Option, }, + /// Servers hosted with horizon-server (the Servers page): list them, create one, or run any + /// horizon-server command on one + Servers { + #[command(subcommand)] + action: Option, + }, /// Serve the Model Context Protocol on stdin and stdout, for AI agents Mcp, /// Measure the launcher: starts (the first is the cold one), page switching, idle CPU and @@ -268,7 +326,7 @@ fn attached(mut cmd: Command) -> Result<(), String> { fn release_json(r: &Release) -> serde_json::Value { serde_json::json!({ - "tag": r.tag, "name": r.name, "date": r.date, + "tag": r.tag, "name": r.name, "date": r.date, "channel": if r.beta { "beta" } else { "stable" }, "available_here": r.asset.is_some(), "installed": backend::installed().contains(&r.tag), }) } @@ -317,7 +375,8 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { (false, true) => "", (false, false) => "no build for this platform", }; - println!("{:<14} {} {}", r.tag, r.date, state); + let channel = if r.beta { "beta" } else { "stable" }; + println!("{:<15} {} {:<6} {}", r.tag, r.date, channel, state); } } Cmd::Install { tag } => { @@ -464,6 +523,7 @@ fn execute(command: Cmd, as_json: bool) -> Result<(), String> { } } Cmd::Modpack { action } => modpack(action.unwrap_or(ModpackCmd::List), as_json)?, + Cmd::Servers { action } => servers(action.unwrap_or(ServersCmd::List), as_json)?, Cmd::Mcp => unreachable!(), } Ok(()) @@ -656,6 +716,111 @@ fn data(action: DataCmd, as_json: bool) -> Result<(), String> { Ok(()) } +fn servers(action: ServersCmd, as_json: bool) -> Result<(), String> { + use horizon_launcher::servers::{self, NewServer, World}; + let find = |which: &str| { + servers::list() + .into_iter() + .find(|e| e.name == which || e.dir == std::path::Path::new(which)) + .ok_or_else(|| { + format!("No server called {which}: `horizon-launcher servers` lists them") + }) + }; + match action { + ServersCmd::List => { + let list = servers::list(); + if as_json { + json(serde_json::Value::Array( + list.iter() + .map(|e| { + serde_json::json!({ + "name": e.name, "dir": e.dir, + "phase": servers::status(&e.dir).phase, + }) + }) + .collect(), + )); + } else if list.is_empty() { + println!("No server yet: horizon-launcher servers create --accept-eula"); + } + for e in list.iter().filter(|_| !as_json) { + println!( + "{} ({}): {}", + e.name, + e.dir.display(), + servers::status(&e.dir).phase + ); + } + } + ServersCmd::Create { + name, + seed, + copy_world, + mode, + difficulty, + max_players, + open, + check_accounts, + players, + version, + accept_eula, + } => { + let spec = NewServer { + name, + world: match copy_world { + Some(dir) => World::Copy(dir), + None => World::New { + seed: seed.unwrap_or_default(), + }, + }, + game_mode: mode, + difficulty, + max_players, + friends_only: !open, + check_accounts, + players, + eula: accept_eula, + }; + let tag = backend::resolve_version(version.as_deref()).ok(); + let entry = servers::create(&spec, tag.as_deref(), &|l| eprintln!("{l}")) + .map_err(|p| p.message)?; + if as_json { + json(serde_json::json!({ "name": entry.name, "dir": entry.dir })); + } else { + println!("Created {} in {}", entry.name, entry.dir.display()); + } + } + ServersCmd::SetUp { version } => { + let tag = backend::resolve_version(version.as_deref())?; + servers::set_up(&tag)?; + println!( + "Servers run Horizon {}", + servers::runtime_release().unwrap_or(tag) + ); + } + ServersCmd::Run { server, args } => { + let entry = find(&server)?; + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + let status = servers::command(&entry.dir, &args)? + .status() + .map_err(|e| e.to_string())?; + if !status.success() { + return Err(format!("horizon-server exited with {status}")); + } + } + ServersCmd::Forget { server } => { + let entry = find(&server)?; + servers::forget(&entry.dir)?; + println!( + "{} is off the list; its folder stays in {}", + entry.name, + entry.dir.display() + ); + } + } + Ok(()) +} + fn modpack(action: ModpackCmd, as_json: bool) -> Result<(), String> { use horizon_launcher::modpacks::{self, Imported}; use horizon_port_pack::report::Status; diff --git a/launcher/src/collection.rs b/launcher/src/collection.rs index a36f88a2f..555726052 100644 --- a/launcher/src/collection.rs +++ b/launcher/src/collection.rs @@ -7,6 +7,8 @@ use horizon_telemetry::{Choices, Consent, Kind as DataKind}; /// What the window keeps about data collection. pub(crate) struct Collection { pub consent: Consent, + body_scroll: Scrollbar, + json_scroll: Scrollbar, /// The question's switches, until the player answers. pub draft: Choices, /// "View what would be sent": a line on what it is, and the JSON. @@ -20,6 +22,8 @@ impl Collection { pub fn load() -> Self { Self { consent: telemetry::consent(), + body_scroll: Scrollbar::default(), + json_scroll: Scrollbar::default(), draft: Choices::NONE, view: None, note: None, @@ -42,7 +46,7 @@ fn kind_id(prefix: &str, kind: DataKind) -> &'static str { } /// The exact JSON, in mono, scrolling inside a plate. -fn json_view(view: &(String, String), t: &Theme) -> Div { +fn json_view(view: &(String, String), t: &Theme, scroll: &Scrollbar) -> Div { div() .flex() .flex_col() @@ -53,20 +57,21 @@ fn json_view(view: &(String, String), t: &Theme) -> Div { .child(view.0.clone()), ) .child( - div() - .id("data-json") - .max_h(px(260.)) - .overflow_y_scroll() - // GPUI lets wheel events reach scroll containers behind this one unless stopped. - .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) - .p(px(16.)) - .rounded(px(theme::RADIUS_PLATE)) - .bg(t.plate) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .line_height(px(18.)) - .text_color(t.ink_soft) - .children(view.1.lines().map(|l| div().child(l.to_string()))), + scroll.wrap( + div() + .id("data-json") + .max_h(px(260.)) + .overflow_y_scroll() + .p(px(16.)) + .rounded(px(theme::RADIUS_PLATE)) + .bg(t.plate) + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .line_height(px(18.)) + .text_color(t.ink_soft) + .children(view.1.lines().map(|l| div().child(l.to_string()))), + t, + ), ) } @@ -160,7 +165,7 @@ impl Launcher { cx.notify(); })), ) - .children(self.collection.view.as_ref().map(|v| json_view(v, &t))); + .children(self.collection.view.as_ref().map(|v| json_view(v, &t, &self.collection.json_scroll))); let answers = div() .flex() .flex_none() @@ -193,7 +198,7 @@ impl Launcher { .bg(t.page) .border_1() .border_color(t.rule) - .child(body) + .child(self.collection.body_scroll.wrap(body, &t)) .child(answers); div() .id("consent") @@ -208,6 +213,7 @@ impl Launcher { .py(px(24.)) .bg(t.page.opacity(0.92)) .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .occlude() .child(card) } @@ -315,6 +321,6 @@ impl Launcher { .child(list) .child(text(theme::CAPTION).text_color(t.muted).child(telemetry::NEVER)) .children(self.collection.note.clone().map(|n| text(theme::UI).text_color(t.ink).child(n))) - .children(self.collection.view.as_ref().map(|v| json_view(v, &t))) + .children(self.collection.view.as_ref().map(|v| json_view(v, &t, &self.collection.json_scroll))) } } diff --git a/launcher/src/heads.rs b/launcher/src/heads.rs new file mode 100644 index 000000000..540cdd1e5 --- /dev/null +++ b/launcher/src/heads.rs @@ -0,0 +1,98 @@ +//! Players' heads for the Servers page: the face of the skin the game shows for them. Without the skin +//! service a player has vanilla's default skin for their UUID (`DefaultPlayerSkin.get`), read from the +//! player's own prepared game files. +use std::path::Path; + +/// `DefaultPlayerSkin.get(UUID)`: the default skin by `UUID.hashCode` (as the game's tab list picks it). +pub fn default_skin(uuid: u128) -> &'static str { + const SKINS: [&str; 18] = [ + "slim/alex", + "slim/ari", + "slim/efe", + "slim/kai", + "slim/makena", + "slim/noor", + "slim/steve", + "slim/sunny", + "slim/zuri", + "wide/alex", + "wide/ari", + "wide/efe", + "wide/kai", + "wide/makena", + "wide/noor", + "wide/steve", + "wide/sunny", + "wide/zuri", + ]; + let hilo = ((uuid >> 64) as u64) ^ (uuid as u64); + let hash = ((hilo >> 32) as i32) ^ (hilo as i32); + SKINS[hash.rem_euclid(SKINS.len() as i32) as usize] +} + +/// A UUID written with or without dashes. +pub fn parse_uuid(text: &str) -> Option { + let hex: String = text.chars().filter(|c| *c != '-').collect(); + (hex.len() == 32).then(|| u128::from_str_radix(&hex, 16).ok())? +} + +/// The 8 by 8 face, row by row as RGBA, with the hat layer over it: what the tab list draws. +pub fn face(skin_png: &[u8]) -> Option> { + let skin = image::load_from_memory_with_format(skin_png, image::ImageFormat::Png) + .ok()? + .to_rgba8(); + if skin.width() < 64 || skin.height() < 32 { + return None; + } + let mut out = Vec::with_capacity(64); + for y in 0..8 { + for x in 0..8 { + let base = skin.get_pixel(8 + x, 8 + y).0; + let hat = skin.get_pixel(40 + x, 8 + y).0; + out.push(if hat[3] > 0 { hat } else { base }); + } + } + Some(out) +} + +/// The face of a player with a default skin, from the prepared game files in `resources`. +pub fn default_face(resources: &Path, uuid: &str) -> Option> { + let skin = default_skin(parse_uuid(uuid)?); + let path = resources + .join("assets/minecraft/textures/entity/player") + .join(format!("{skin}.png")); + face(&std::fs::read(path).ok()?) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_skins_follow_the_uuid_hash() { + // OfflinePlayer:Alex and OfflinePlayer:Steve, as vanilla's server makes them. + assert_eq!( + parse_uuid("36532b5e-c442-3dbb-a24c-c7e55d0f979a"), + Some(0x36532b5ec4423dbba24cc7e55d0f979a) + ); + assert_eq!(default_skin(0), "slim/alex"); + assert_eq!(default_skin(1), "slim/ari"); + assert_eq!(default_skin(u128::MAX), "slim/alex"); + assert!(parse_uuid("not-a-uuid").is_none()); + } + + #[test] + fn the_face_wears_its_hat() { + let mut skin = image::RgbaImage::new(64, 64); + skin.put_pixel(8, 8, image::Rgba([1, 2, 3, 255])); + skin.put_pixel(9, 8, image::Rgba([4, 5, 6, 255])); + skin.put_pixel(41, 8, image::Rgba([7, 8, 9, 255])); + let mut png = Vec::new(); + skin.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + let face = face(&png).unwrap(); + assert_eq!(face.len(), 64); + assert_eq!(face[0], [1, 2, 3, 255]); + assert_eq!(face[1], [7, 8, 9, 255]); + } +} diff --git a/launcher/src/internet.rs b/launcher/src/internet.rs new file mode 100644 index 000000000..76ab8dab8 --- /dev/null +++ b/launcher/src/internet.rs @@ -0,0 +1,714 @@ +//! The Servers page's "Friends over the internet" panel: Tailscale on this computer, the address friends +//! type, inviting a friend to this one computer, and keeping shared friends to the server's port +//! (`horizon_launcher::tailscale`). Signing in is always the player's, in Tailscale's own app or page; +//! the launcher reads `tailscale status` and, with the player's own access token, calls the API. +use super::servers_page::Field; +use super::*; +use horizon_launcher::tailscale::{self, Api, Invite, Reach, State}; +use serde_json::Value; + +/// How often Tailscale's state is read while the panel shows. +const POLL: Duration = Duration::from_secs(10); +/// How often the invitations and access controls are read again while the panel shows, so an +/// accepted invitation appears without a click. +const RELOAD: Duration = Duration::from_secs(30); + +pub(super) enum Event { + State(State), + Token(Option), + Invites(Result, String>), + Policy(Result<(Value, Option), String>), + /// An action finished: what to tell the player, and whether to read invites and policy again. + Done(Result), + Invited(Result), +} + +pub(super) struct Internet { + state: Option, + reading: bool, + read: Option, + /// The access token, once read from the keychain (None: not read yet; Some(None): none). + token: Option>, + asking_token: bool, + invites: Option, String>>, + policy: Option), String>>, + loaded: Option, + busy: bool, + message: Option>, + /// The invitation just made, its link shown to copy. + fresh: Option, + confirm_limit: bool, + copied: Option<(String, Instant)>, + tx: Sender, + rx: Receiver, +} + +impl Internet { + pub(super) fn new() -> Self { + let (tx, rx) = channel(); + Self { + state: None, + reading: false, + read: None, + token: None, + asking_token: false, + invites: None, + policy: None, + loaded: None, + busy: false, + message: None, + fresh: None, + confirm_limit: false, + copied: None, + tx, + rx, + } + } + + fn node(&self) -> Option<&tailscale::Node> { + match &self.state { + Some(State::Running(n)) => Some(n), + _ => None, + } + } + + fn token(&self) -> Option { + self.token.clone().flatten() + } +} + +impl Launcher { + /// What the background sent, and the next look at Tailscale while the panel shows. + pub(super) fn internet_tick(&mut self, showing: bool) -> bool { + let mut changed = false; + while let Ok(event) = self.internet.rx.try_recv() { + changed = true; + self.internet_event(event); + } + let i = &mut self.internet; + if showing && !i.reading && i.read.is_none_or(|at| at.elapsed() >= POLL) { + self.internet_refresh(); + } + changed + } + + fn internet_refresh(&mut self) { + let i = &mut self.internet; + i.reading = true; + i.read = Some(Instant::now()); + let tx = i.tx.clone(); + let want_token = i.token.is_none(); + std::thread::spawn(move || { + let _ = tx.send(Event::State(tailscale::status())); + if want_token { + let token = account::store().get(tailscale::TOKEN_KEY).ok().flatten(); + let _ = tx.send(Event::Token(token)); + } + }); + } + + fn internet_event(&mut self, event: Event) { + let i = &mut self.internet; + match event { + Event::State(state) => { + i.reading = false; + let was_running = i.node().map(|n| n.id.clone()); + i.state = Some(state); + let now = i.node().map(|n| n.id.clone()); + let stale = i.loaded.is_none_or(|at| at.elapsed() >= RELOAD); + if now.is_some() && (now != was_running || (stale && !i.busy)) { + self.internet_load(); + } + } + Event::Token(token) => { + i.token = Some(token); + self.internet_load(); + } + Event::Invites(r) => i.invites = Some(r), + Event::Policy(r) => i.policy = Some(r), + Event::Done(r) => { + i.busy = false; + i.message = Some(r); + self.internet_load(); + } + Event::Invited(r) => { + i.busy = false; + match r { + Ok(invite) => { + i.message = None; + i.fresh = Some(invite); + self.servers.text(Field::Email).clear(); + } + Err(e) => i.message = Some(Err(e)), + } + self.internet_load(); + } + } + } + + /// Reads the invitations and the access controls (needs the token and a running Tailscale). + fn internet_load(&mut self) { + let i = &mut self.internet; + let (Some(token), Some(node)) = (i.token(), i.node().cloned()) else { + return; + }; + i.loaded = Some(Instant::now()); + let tx = i.tx.clone(); + std::thread::spawn(move || { + let api = Api::new(&token); + let _ = tx.send(Event::Invites(api.invites(&node.id))); + let _ = tx.send(Event::Policy(api.policy())); + }); + } + + pub(super) fn save_token(&mut self) { + let token = self.servers.value(Field::Token).trim().to_string(); + if !token.starts_with("tskey-") { + self.internet.message = Some(Err( + "Paste the access token Tailscale showed (it begins with tskey-).".into(), + )); + return; + } + self.servers.text(Field::Token).clear(); + self.internet.asking_token = false; + self.internet.message = match account::store().set(tailscale::TOKEN_KEY, &token) { + Ok(()) if account::store().persistent() => None, + Ok(()) => Some(Ok( + "No keychain here: the token is kept until the launcher closes.".into(), + )), + Err(e) => Some(Err(e)), + }; + self.internet.token = Some(Some(token)); + self.internet_load(); + } + + fn forget_token(&mut self) { + let _ = account::store().delete(tailscale::TOKEN_KEY); + let i = &mut self.internet; + i.token = Some(None); + i.invites = None; + i.policy = None; + i.fresh = None; + i.message = Some(Ok( + "The access token is forgotten. Delete it in Tailscale's admin \ + console too (Settings, Keys) if you won't use it again." + .into(), + )); + } + + pub(super) fn invite_friend(&mut self) { + let i = &mut self.internet; + let (Some(token), Some(node)) = (i.token(), i.node().cloned()) else { + return; + }; + if i.busy { + return; + } + let email = self.servers.value(Field::Email).trim().to_string(); + if !email.is_empty() && !email.contains('@') { + i.message = Some(Err("That isn't an email address.".into())); + return; + } + i.busy = true; + i.fresh = None; + let tx = i.tx.clone(); + std::thread::spawn(move || { + let email = Some(email.as_str()).filter(|e| !e.is_empty()); + let _ = tx.send(Event::Invited(Api::new(&token).invite(&node.id, email))); + }); + } + + fn internet_action( + &mut self, + job: impl FnOnce(&Api) -> Result + Send + 'static, + ) { + let i = &mut self.internet; + let Some(token) = i.token() else { + return; + }; + if i.busy { + return; + } + i.busy = true; + i.message = None; + let tx = i.tx.clone(); + std::thread::spawn(move || { + let _ = tx.send(Event::Done(job(&Api::new(&token)))); + }); + } + + /// Applies `change` to the access controls read at `etag`, checked by Tailscale first. + fn change_policy(&mut self, new: Value, etag: Option, said: &'static str) { + self.internet.confirm_limit = false; + self.internet_action(move |api| { + api.validate(&new)?; + api.set_policy(&new, etag.as_deref())?; + Ok(said.to_string()) + }); + } + + fn copy_button( + &self, + id: &'static str, + text: String, + kind: Kind, + cx: &mut Context, + ) -> Stateful
{ + let copied = self + .internet + .copied + .as_ref() + .is_some_and(|(what, at)| what == &text && at.elapsed() < Duration::from_secs(2)); + button( + id, + if copied { "Copied" } else { "Copy" }, + kind, + &self.theme, + ) + .bg(self.theme.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string(text.clone())); + this.internet.copied = Some((text.clone(), Instant::now())); + cx.notify(); + })) + } + + pub(super) fn internet_panel(&mut self, port: u16, cx: &mut Context) -> Div { + let t = self.theme; + let mut panel = plate(&t) + .flex() + .flex_col() + .gap(px(12.)) + .p(px(20.)) + .child(caps("Friends over the internet · Tailscale").text_color(t.muted)); + let line = |s: String| text(theme::CAPTION).text_color(t.muted).child(s); + let check = button("ts-check", "Check again", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.internet_refresh(); + cx.notify(); + }, + )); + match self.internet.state.clone() { + None => return panel.child(line("Looking for Tailscale…".into())), + Some(State::Missing) => { + return panel + .child(text(theme::UI).text_color(t.ink).child( + "Tailscale lets friends anywhere join without opening your router to the \ + internet. It's free: install it, sign in, then invite them here.", + )) + .child( + div() + .flex() + .gap(px(8.)) + .child( + button("ts-install", "Install Tailscale", Kind::Secondary, &t) + .bg(t.plate) + .on_click(|_, _, cx| cx.open_url(tailscale::install_url())), + ) + .child(check), + ); + } + Some(State::Off(why)) => { + let open = button("ts-open", "Open Tailscale", Kind::Secondary, &t) + .bg(t.plate) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + if let Err(e) = tailscale::open_app() { + this.internet.message = Some(Err(e)); + } + this.internet.read = None; + cx.notify(); + })); + panel = + panel + .child(text(theme::UI).text_color(t.ink).child( + "Tailscale is installed but not running. Open it and switch it on.", + )) + .when(!why.is_empty(), |d| d.child(line(why))) + .child(div().flex().gap(px(8.)).child(open).child(check)); + return self.internet_message(panel); + } + Some(State::SignedOut { auth_url }) => { + let sign_in = button("ts-login", "Sign in to Tailscale", Kind::Secondary, &t) + .bg(t.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + match &auth_url { + Some(url) => cx.open_url(url), + None => { + if let Err(e) = tailscale::open_app() { + this.internet.message = Some(Err(e)); + } + } + } + this.internet.read = None; + cx.notify(); + })); + panel = panel + .child(text(theme::UI).text_color(t.ink).child( + "Tailscale is installed. Sign in with your own account in Tailscale \ + (Horizon never sees it), then come back here.", + )) + .when(cfg!(target_os = "linux"), |d| { + d.child(line(format!( + "On Linux, run `{}` in a terminal and open the link it prints.", + tailscale::LINUX_LOGIN + ))) + }) + .child(div().flex().gap(px(8.)).child(sign_in).child(check)); + return self.internet_message(panel); + } + Some(State::Running(_)) => {} + } + let node = self.internet.node().cloned().unwrap_or_default(); + let address = node.address(port); + let ip = node.ipv4().unwrap_or_default().to_string(); + let mut where_ = div().flex().flex_col().gap(px(6.)).child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child( + text(theme::TITLE) + .font_family(theme::MONO) + .text_color(t.ink) + .child(address.clone()), + ) + .child(self.copy_button("ts-copy", address, Kind::Secondary, cx)), + ); + if node.magic_dns && !ip.is_empty() { + let ip_port = if port == 25565 { + ip.clone() + } else { + format!("{ip}:{port}") + }; + where_ = where_.child(line(format!( + "Or {ip_port}. Friends type it in Multiplayer, Add Server, once this computer is \ + shared with them and Tailscale runs on theirs." + ))); + } else { + where_ = where_.child(line( + "Friends type it in Multiplayer, Add Server, once this computer is shared with \ + them and Tailscale runs on theirs." + .into(), + )); + } + panel = panel.child(where_); + panel = panel.child( + div() + .border_t_1() + .border_color(t.rule) + .pt(px(12.)) + .flex() + .flex_col() + .gap(px(10.)) + .child(text(theme::UI).text_color(t.ink).child("Invite a friend")) + .child(self.invite_section(&ip, port, cx)), + ); + panel = panel.child(line( + "Horizon never turns on Funnel: the server isn't put on the public internet, only \ + shared with the people you invite." + .into(), + )); + self.internet_message(panel) + } + + fn internet_message(&self, panel: Div) -> Div { + let t = self.theme; + match &self.internet.message { + Some(Ok(m)) => { + panel.child(text(theme::CAPTION).text_color(t.ink_soft).child(m.clone())) + } + Some(Err(e)) => panel.child(text(theme::CAPTION).text_color(t.danger).child(e.clone())), + None => panel, + } + } + + fn invite_section(&mut self, ip: &str, port: u16, cx: &mut Context) -> Div { + let t = self.theme; + let line = |s: String| text(theme::CAPTION).text_color(t.muted).child(s); + let link = |id: &'static str, label: &'static str, url: &'static str| { + button(id, label, Kind::Ghost, &t).on_click(move |_, _, cx| cx.open_url(url)) + }; + let token = self.internet.token(); + if token.is_none() { + let mut d = div().flex().flex_col().gap(px(10.)).child(line( + "Share this computer with a friend: they get it in their own Tailscale, and \ + nothing else of yours. Do it in Tailscale's admin console (Machines, this \ + computer, Share), or here with an access token you make there." + .into(), + )); + let machines = link( + "ts-console", + "Open the admin console", + "https://login.tailscale.com/admin/machines", + ); + if self.internet.asking_token { + let save = button("ts-token-save", "Save", Kind::Secondary, &t) + .bg(t.plate) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.save_token(); + cx.notify(); + })); + d = d + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.field(Field::Token, "tskey-api-…", 300., cx)) + .child(save) + .child(link("ts-keys", "Make a token", tailscale::KEYS)), + ) + .child(line( + "Settings, Keys, Generate access token. It's kept in this computer's \ + keychain and only sent to Tailscale." + .into(), + )); + } else { + d = d.child(div().flex().gap(px(8.)).child(machines).child( + button("ts-token", "Use an access token…", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.internet.asking_token = true; + this.internet.message = None; + cx.notify(); + }), + ), + )); + } + return d; + } + + // Invite. + let busy = self.internet.busy; + let invite = button("ts-invite", "Make an invitation", Kind::Secondary, &t).bg(t.plate); + let invite = if busy { + disabled(invite) + } else { + invite.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.invite_friend(); + cx.notify(); + })) + }; + let mut d = div() + .flex() + .flex_col() + .gap(px(10.)) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.field(Field::Email, "Their email (optional)", 260., cx)) + .child(invite), + ) + .child(line( + "One invitation per friend. With an email Tailscale sends it; without, send them \ + the link. They accept it in their own Tailscale account." + .into(), + )); + if let Some(fresh) = self.internet.fresh.clone() { + d = d.child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child( + text(theme::CAPTION) + .font_family(theme::MONO) + .text_color(t.ink) + .truncate() + .child(fresh.url.clone()), + ) + .child(self.copy_button("ts-fresh-copy", fresh.url, Kind::Secondary, cx)), + ); + } + match self.internet.invites.clone() { + Some(Ok(list)) if !list.is_empty() => { + let mut rows = div().flex().flex_col().border_t_1().border_color(t.rule); + for (n, inv) in list.into_iter().enumerate() { + let who = match (&inv.accepted_by, &inv.email) { + (Some(by), _) => format!("Shared with {by}"), + (None, Some(email)) => format!("Sent to {email}, not accepted yet"), + (None, None) => "Link not used yet".to_string(), + }; + let id = inv.id.clone(); + let withdraw = button( + SharedString::from(format!("ts-revoke-{n}")), + if inv.accepted { + "Stop sharing" + } else { + "Withdraw" + }, + Kind::Ghost, + &t, + ); + let withdraw = if busy { + disabled(withdraw) + } else { + withdraw.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + let id = id.clone(); + this.internet.fresh = None; + this.internet_action(move |api| { + api.revoke(&id)?; + Ok("Withdrawn: that friend can't reach this computer any more." + .into()) + }); + cx.notify(); + })) + }; + let date = inv.created.get(..10).unwrap_or_default().to_string(); + rows = rows.child(index_row( + n + 1, + who, + Some(format!("Made {date}").into_any_element()), + Some(withdraw.into_any_element()), + &t, + )); + } + d = d.child(rows); + } + Some(Err(e)) => d = d.child(text(theme::CAPTION).text_color(t.danger).child(e)), + _ => {} + } + + // What shared friends reach. + let reach = match &self.internet.policy { + Some(Ok((policy, etag))) => Some(( + tailscale::reach(policy, ip, port), + policy.clone(), + etag.clone(), + )), + Some(Err(e)) => { + d = d.child(line(format!("Couldn't read your access controls: {e}"))); + None + } + None => None, + }; + if let Some((reach, policy, etag)) = reach { + let mut safety = div().flex().flex_col().gap(px(8.)).pt(px(4.)); + match reach { + Reach::Everything => { + safety = safety.child(text(theme::UI).text_color(t.ink).child( + "Friends you share this computer with can reach all of it, not only \ + Minecraft (Tailscale's default).", + )); + if self.internet.confirm_limit { + let new = tailscale::limit_shared(&policy, ip, port); + safety = safety + .child(line(format!( + "This changes your tailnet's access controls: the rule that lets \ + everyone reach everything becomes one for your own devices and \ + members, and friends you share with reach only {ip}:{port}." + ))) + .child( + div() + .flex() + .gap(px(8.)) + .child( + button("ts-limit-go", "Change the access controls", Kind::Primary, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(new) = new.clone() { + this.change_policy( + new, + etag.clone(), + "Done: friends you share this computer with reach only the Minecraft server.", + ); + } + cx.notify(); + })), + ) + .child(button("ts-limit-cancel", "Cancel", Kind::Ghost, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.internet.confirm_limit = false; + cx.notify(); + }), + )), + ); + } else { + let b = button("ts-limit", "Limit them to Minecraft", Kind::Secondary, &t) + .bg(t.plate); + safety = safety.child(div().flex().child(if busy { + disabled(b) + } else { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.internet.confirm_limit = true; + cx.notify(); + })) + })); + } + } + Reach::ServerOnly => { + let undo = tailscale::unlimit_shared(&policy, ip, port); + let b = button("ts-unlimit", "Remove the limit", Kind::Ghost, &t); + safety = safety.child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child(div().flex_none().size(px(6.)).rounded_full().bg(t.success)) + .child( + text(theme::UI) + .flex_1() + .text_color(t.ink) + .child(format!( + "Friends you share with reach only the Minecraft server (port {port})." + )), + ) + .child(if busy { + disabled(b) + } else { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(undo) = undo.clone() { + this.change_policy( + undo, + etag.clone(), + "Tailscale's default access controls are back.", + ); + } + cx.notify(); + })) + }), + ); + } + Reach::Custom => { + let snippet = tailscale::snippet(ip, port); + safety = safety + .child(text(theme::UI).text_color(t.ink).child( + "Your access controls are your own, so Horizon leaves them alone. To \ + keep shared friends to Minecraft, add this rule in the admin console:", + )) + .child( + div() + .p(px(12.)) + .rounded(px(theme::RADIUS)) + .bg(t.plate) + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .text_color(t.ink_soft) + .child(snippet.clone()), + ) + .child( + div() + .flex() + .gap(px(8.)) + .child(self.copy_button( + "ts-snippet-copy", + snippet, + Kind::Secondary, + cx, + )) + .child(link("ts-acls", "Open access controls", tailscale::ACCESS)), + ); + } + } + d = d.child(safety); + } + d.child(div().flex().child( + button("ts-forget", "Forget the access token", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.forget_token(); + cx.notify(); + }, + )), + )) + } +} diff --git a/launcher/src/lib.rs b/launcher/src/lib.rs index 11023a46d..a90d8c22f 100644 --- a/launcher/src/lib.rs +++ b/launcher/src/lib.rs @@ -2,7 +2,10 @@ pub mod account; pub mod backend; pub mod desktop; +pub mod heads; pub mod modpacks; pub mod mojang; +pub mod servers; pub mod sources; +pub mod tailscale; pub mod telemetry; diff --git a/launcher/src/main.rs b/launcher/src/main.rs index ca86b5b08..e6f93ae7e 100644 --- a/launcher/src/main.rs +++ b/launcher/src/main.rs @@ -4,23 +4,28 @@ mod cli; mod collection; mod game_tools; +mod internet; mod markdown; mod mcp; mod modpacks_page; mod perf; +mod scrollbar; +mod servers_page; mod theme; use gpui::{ div, ease_out_quint, prelude::*, px, relative, size, Animation, AnimationExt, AnyElement, App, Application, Bounds, ClickEvent, Context, Div, ElementId, FocusHandle, FontWeight, Hsla, - KeyDownEvent, PathPromptOptions, ScrollHandle, SharedString, Stateful, Subscription, - TitlebarOptions, Window, WindowBounds, WindowOptions, + KeyDownEvent, PathPromptOptions, SharedString, Stateful, Subscription, TitlebarOptions, Window, + WindowBounds, WindowOptions, }; use horizon_launcher::account::{self, Accounts, SignIn, SignInState}; use horizon_launcher::backend::{self, Job, Msg, Release, Running, Settings, Updates}; use horizon_launcher::telemetry; +use scrollbar::Scrollbar; use std::borrow::Cow; use std::collections::VecDeque; +use std::sync::atomic::Ordering; use std::sync::mpsc::{channel, Receiver, Sender}; use std::sync::Mutex; use std::time::{Duration, Instant}; @@ -31,15 +36,17 @@ enum Page { Play, Versions, Modpacks, + Servers, Notes, Settings, } impl Page { - const ALL: [(Page, &'static str); 5] = [ + const ALL: [(Page, &'static str); 6] = [ (Page::Play, "Play"), (Page::Versions, "Versions"), (Page::Modpacks, "Modpacks"), + (Page::Servers, "Servers"), (Page::Notes, "Patch notes"), (Page::Settings, "Settings"), ]; @@ -85,12 +92,6 @@ fn ease_out_cubic(x: f32) -> f32 { /// How often the launcher looks for new releases while it is open. const CHECK_EVERY: Duration = Duration::from_secs(4 * 3600); -#[derive(Clone, Copy, PartialEq)] -enum Mode { - Client, - Server, -} - enum Load { Loading, Ready(T), @@ -104,6 +105,7 @@ struct Launcher { page: Page, /// How many times the page changed, for the page transition. switches: usize, + content_scroll: Scrollbar, opening: Option, updates: Updates, checked: Option, @@ -113,7 +115,6 @@ struct Launcher { update_install: Option<(String, bool)>, /// The install bar's previous and current fraction, so it moves rather than jumps. bar: (f32, f32), - mode: Mode, releases: Load>, installed: Vec, installing: Option<(String, f32)>, @@ -134,7 +135,12 @@ struct Launcher { /// The folder the running game keeps its settings in: the game home, or a modpack's. client_home: Option, crash: Option, - server: Option, + /// The Servers page (`servers_page.rs`). + servers: servers_page::Servers, + /// Its Friends over the internet panel (`internet.rs`). + internet: internet::Internet, + /// The window's own focus, so Tab reaches the controls when nothing else has the keyboard. + root_focus: FocusHandle, /// Microsoft accounts (accounts.json), the sign-in under way and what it last showed. accounts: Accounts, sign_in: Option, @@ -142,11 +148,6 @@ struct Launcher { keychain: bool, /// The game is waiting for its session (a token renewal) before it starts. starting_client: Option, - server_log: VecDeque, - server_error: Option, - input: String, - input_focused: bool, - focus: FocusHandle, /// Join a friend: the code typed on the Play page, and the one the game /// starting now joins. friend_code: String, @@ -157,7 +158,6 @@ struct Launcher { args_input: String, args_focused: bool, args_focus: FocusHandle, - console_scroll: ScrollHandle, /// Opt-in data collection: the player's answer and Settings' section (`collection`). collection: collection::Collection, tx: Sender, @@ -203,9 +203,6 @@ impl Launcher { if settings.minecraft_dir.is_none() { settings.minecraft_dir = backend::default_minecraft_dir(); } - if settings.server_dir.is_none() { - settings.server_dir = Some(backend::data_dir().join("server")); - } // Release builds on Linux keep their entry in the applications menu up to date (a moved // binary changes it); `HORIZON_LAUNCHER_DESKTOP_ENTRY=1` does it in a development build. if cfg!(target_os = "linux") @@ -229,6 +226,7 @@ impl Launcher { theme: Theme::for_appearance(window.appearance()), page: Page::Play, switches: 0, + content_scroll: Scrollbar::default(), opening: (!settings.skip_opening).then(|| { let focus = cx.focus_handle(); window.focus(&focus); @@ -244,7 +242,6 @@ impl Launcher { self_update: SelfUpdate::Idle, update_install: None, bar: (0., 0.), - mode: Mode::Client, releases: Load::Loading, installed, installing: None, @@ -265,22 +262,18 @@ impl Launcher { client_started: None, client_home: None, crash: None, - server: None, + servers: servers_page::Servers::new(), + internet: internet::Internet::new(), + root_focus: cx.focus_handle(), accounts: Accounts::load(), sign_in: None, sign_in_state: None, keychain: true, starting_client: None, - server_log: VecDeque::new(), - server_error: None, - input: String::new(), - input_focused: false, - focus: cx.focus_handle(), friend_code: String::new(), friend_focused: false, friend_focus: cx.focus_handle(), joining: None, - console_scroll: ScrollHandle::new(), collection: collection::Collection::load(), tx, rx, @@ -325,6 +318,7 @@ impl Launcher { if page != self.page { self.page = page; self.switches += 1; + self.content_scroll = Scrollbar::default(); } self.picker_open = false; } @@ -529,17 +523,13 @@ impl Launcher { .record_since("launcher.play_to_game_frame_ms", pressed); } } - let log = if job == Job::Server { - &mut self.server_log - } else { - &mut self.prepare_log - }; - log.push_back(line); - if log.len() > LOG_LINES { - log.pop_front(); - } - if job == Job::Server { - self.console_scroll.scroll_to_bottom(); + // The MCP server keeps its own server's log; the launcher's are the preparer's + // and the game's. + if job != Job::Server { + self.prepare_log.push_back(line); + if self.prepare_log.len() > LOG_LINES { + self.prepare_log.pop_front(); + } } } Msg::Exit(job, result) => { @@ -599,27 +589,12 @@ impl Launcher { }); } } - Job::Server => { - self.server = None; - let old = self - .server_log - .iter() - .any(|l| l.contains("unknown option --dedicated")); - self.server_error = error.map(|e| { - if old { - "This version has no dedicated server. Pick a newer one." - .to_string() - } else { - let tail = - self.server_log.iter().rev().find(|l| !l.trim().is_empty()); - tail.map_or(e.clone(), |t| format!("{e}: {t}")) - } - }); - } + Job::Server => {} } } } } + changed |= self.servers_tick(); if let Some(sign_in) = &self.sign_in { let state = sign_in.state(); let changed_state = format!("{state:?}") != format!("{:?}", self.sign_in_state); @@ -744,38 +719,11 @@ impl Launcher { let Some(tag) = self.selected().cloned() else { return; }; - match self.mode { - Mode::Client => { - if self.client.is_some() || self.starting_client.is_some() { - return; - } - self.starting_pack = None; - self.start_client(tag); - } - Mode::Server => { - if let Some(server) = &mut self.server { - server.send("stop"); - return; - } - let Some(folder) = self.settings.server_dir.clone() else { - return; - }; - if let Err(e) = std::fs::create_dir_all(&folder) { - self.server_error = Some(e.to_string()); - return; - } - self.server_error = None; - self.server_log.clear(); - match backend::spawn( - Job::Server, - backend::server_command(&tag, &folder), - self.tx.clone(), - ) { - Ok(r) => self.server = Some(r), - Err(e) => self.server_error = Some(e), - } - } + if self.client.is_some() || self.starting_client.is_some() { + return; } + self.starting_pack = None; + self.start_client(tag); } /// Starts the game: the session first (a network round trip when the token needs @@ -810,7 +758,7 @@ impl Launcher { }); } - fn choose_folder(&mut self, server: bool, cx: &mut Context) { + fn choose_folder(&mut self, cx: &mut Context) { let paths = cx.prompt_for_paths(PathPromptOptions { files: false, directories: true, @@ -821,11 +769,7 @@ impl Launcher { if let Ok(Ok(Some(mut paths))) = paths.await { if let Some(path) = paths.pop() { let _ = this.update(cx, |this, cx| { - if server { - this.settings.server_dir = Some(path); - } else { - this.settings.minecraft_dir = Some(path); - } + this.settings.minecraft_dir = Some(path); this.settings.save(); cx.notify(); }); @@ -834,18 +778,6 @@ impl Launcher { }) .detach(); } - - fn submit_command(&mut self) { - let line = std::mem::take(&mut self.input); - if line.trim().is_empty() { - return; - } - if let Some(server) = &mut self.server { - server.send(line.trim_start_matches('/')); - self.server_log.push_back(format!("> {line}")); - self.console_scroll.scroll_to_bottom(); - } - } } // ----- Building blocks --------------------------------------------------------------------------- @@ -978,6 +910,31 @@ fn mark(size: f32, t: &Theme) -> Div { ) } +/// The last thing the player did was press Tab: focused controls show a ring (a click focuses them +/// too, without one). +static KEYBOARD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); + +/// Makes a control reachable with Tab, pressed with Enter or Space, with a ring when the keyboard +/// put it in focus. +fn keyboard(el: Stateful
, t: &Theme) -> Stateful
{ + let (ring, gap) = (t.accent, t.page); + // A ring with a gap of page colour, so it shows around filled buttons too. GPUI draws nothing + // for a shadow without blur: half a pixel keeps it crisp. + let shadow = |color, spread: f32| gpui::BoxShadow { + color, + offset: gpui::point(px(0.), px(0.)), + blur_radius: px(0.5), + spread_radius: px(spread), + }; + el.tab_index(0).focus(move |s| { + if KEYBOARD.load(Ordering::Relaxed) { + s.shadow(vec![shadow(ring, 4.), shadow(gap, 1.5)]) + } else { + s + } + }) +} + fn button( id: impl Into, label: impl Into, @@ -1006,7 +963,7 @@ fn button( .cursor_pointer() .child(hover_layer(&id, hover, theme::RADIUS_PILL, 0.)) .child(div().relative().child(label.into())); - let base = track_hover(base, id); + let base = keyboard(track_hover(base, id), &t); match kind { Kind::Primary => base .bg(t.accent) @@ -1025,8 +982,7 @@ fn button( /// An on/off switch whose knob slides. fn switch(id: &'static str, on: bool, t: &Theme) -> Stateful
{ - div() - .id(id) + keyboard(div().id(id), t) .relative() .flex_none() .w(px(36.)) @@ -1069,8 +1025,7 @@ fn segments( .children(options.iter().map(|&(value, label)| { let active = current == value; let pick = on_pick.clone(); - div() - .id(SharedString::from(format!("{id}-{label}"))) + keyboard(div().id(SharedString::from(format!("{id}-{label}"))), &t) .flex() .items_center() .h(px(theme::SEGMENT)) @@ -1089,7 +1044,7 @@ fn segments( } fn disabled(b: Stateful
) -> Stateful
{ - b.opacity(theme::DISABLED).cursor_default() + b.opacity(theme::DISABLED).cursor_default().tab_stop(false) } /// A page's title in display type and one line on what it is for. @@ -1309,22 +1264,6 @@ impl Launcher { .child(links) } - fn segmented(&self, cx: &mut Context) -> Stateful
{ - let this = cx.entity().downgrade(); - segments( - "mode", - &[(Mode::Client, "Client"), (Mode::Server, "Server")], - self.mode, - &self.theme, - move |mode, _, cx| { - let _ = this.update(cx, |this, cx| { - this.mode = mode; - cx.notify(); - }); - }, - ) - } - fn picker(&self, cx: &mut Context) -> Div { let t = self.theme; let label = self @@ -1443,36 +1382,14 @@ impl Launcher { let prepared = backend::is_prepared(&tag); let version = backend::game_version(&tag); let hero = self.hero(&tag, &version, prepared, cx); - let running = match self.mode { - Mode::Client => self.client.is_some() || self.starting_client.is_some(), - Mode::Server => self.server.is_some(), - }; - let play_label = match (self.mode, running) { - (Mode::Client, false) => "Play", - (Mode::Client, true) => "Running", - (Mode::Server, false) => "Start server", - (Mode::Server, true) => "Stop server", - }; - let kind = if self.mode == Mode::Server && running { - Kind::Secondary - } else { - Kind::Primary - }; - let mut play = button("play", play_label, kind, &t) + let running = self.client.is_some() || self.starting_client.is_some(); + let play_label = if running { "Running" } else { "Play" }; + let mut play = button("play", play_label, Kind::Primary, &t) .min_w(px(132.)) .h(px(theme::CONTROL_LARGE)) .px(px(28.)) .text_size(px(theme::UI.px)); - let eula = self - .settings - .server_dir - .as_ref() - .is_some_and(|d| backend::eula_agreed(d)); - if !prepared - || self.preparing - || (self.mode == Mode::Client && running) - || (self.mode == Mode::Server && !eula) - { + if !prepared || self.preparing || running { play = disabled(play); } else { play = play.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { @@ -1485,7 +1402,14 @@ impl Launcher { .flex() .items_center() .justify_between() - .child(self.segmented(cx)) + .child( + button("host", "Host a server", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.go(Page::Servers); + cx.notify(); + }, + )), + ) .child( div() .flex() @@ -1533,33 +1457,30 @@ impl Launcher { .into_any_element() }, ); - let mut rows = - div() - .flex() - .flex_col() - .border_t_1() - .border_color(t.rule) - .child(index_row( - 1, - "Resources", - Some(div().child(resources_value).into_any_element()), - Some(prepare.into_any_element()), - &t, - )) - .child(index_row( - 2, - "Minecraft folder", - Some(minecraft), - Some( - button("choose-mc", "Choose…", Kind::Ghost, &t) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.choose_folder(false, cx) - })) - .into_any_element(), - ), - &t, - )); - if self.mode == Mode::Client { + let mut rows = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(index_row( + 1, + "Resources", + Some(div().child(resources_value).into_any_element()), + Some(prepare.into_any_element()), + &t, + )) + .child(index_row( + 2, + "Minecraft folder", + Some(minecraft), + Some( + button("choose-mc", "Choose…", Kind::Ghost, &t) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(cx))) + .into_any_element(), + ), + &t, + )); + { let who = match self.accounts.selected() { Some(a) => format!("{} (Microsoft account)", a.name), None => "Offline: online servers need a Microsoft account.".to_string(), @@ -1580,62 +1501,6 @@ impl Launcher { &t, )); } - if self.mode == Mode::Server { - let folder = self - .settings - .server_dir - .as_deref() - .map(short) - .unwrap_or_default(); - rows = rows.child(index_row( - 3, - "Server folder", - Some( - div() - .font_family(theme::MONO) - .child(folder) - .into_any_element(), - ), - Some( - button("choose-server", "Choose…", Kind::Ghost, &t) - .on_click( - cx.listener(|this, _: &ClickEvent, _, cx| this.choose_folder(true, cx)), - ) - .into_any_element(), - ), - &t, - )); - let value = if eula { - "Agreed" - } else { - "Running a server needs your agreement to the Minecraft EULA." - }; - let mut actions = div().flex().gap(px(4.)).child( - button("eula-read", "Read", Kind::Ghost, &t).on_click(cx.listener( - |_, _: &ClickEvent, _, cx| cx.open_url("https://aka.ms/MinecraftEULA"), - )), - ); - if !eula { - actions = - actions.child(button("eula-agree", "Agree", Kind::Secondary, &t).on_click( - cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(dir) = &this.settings.server_dir { - if let Err(e) = backend::agree_eula(dir) { - this.server_error = Some(e); - } - } - cx.notify(); - }), - )); - } - rows = rows.child(index_row( - 4, - "Minecraft EULA", - Some(div().child(value).into_any_element()), - Some(actions.into_any_element()), - &t, - )); - } let mut page = div() .flex() @@ -1668,18 +1533,11 @@ impl Launcher { if let Some(e) = self.prepare_error.clone() { page = page.child(notice(e, &t)); } - if self.mode == Mode::Client { - if let Some(e) = self.client_error.clone() { - page = page.child(notice(e, &t)); - } - if let Some(crash) = self.crash.clone() { - page = page.child(self.crash_notice(crash, cx)); - } - } else { - if let Some(e) = self.server_error.clone() { - page = page.child(notice(e, &t)); - } - page = page.child(self.console(cx)); + if let Some(e) = self.client_error.clone() { + page = page.child(notice(e, &t)); + } + if let Some(crash) = self.crash.clone() { + page = page.child(self.crash_notice(crash, cx)); } // The signature: the name, huge and faint, at the foot of the page. page.child( @@ -1819,11 +1677,7 @@ impl Launcher { .and_then(|r| backend::notes_summary(&r.body)), _ => None, }; - let title = if self.mode == Mode::Server { - "Horizon server" - } else { - "Horizon" - }; + let title = "Horizon"; let mut hero = div() .flex() @@ -1898,6 +1752,15 @@ impl Launcher { cx.notify(); }), ); + let betas = switch("beta-builds", self.settings.beta_builds, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.settings.beta_builds = !this.settings.beta_builds; + this.settings.save(); + // What counts as new changed: check again (and install it if that is on). + this.check_updates(); + cx.notify(); + }, + )); let opening = switch("opening", !self.settings.skip_opening, &t).on_click(cx.listener( |this, _: &ClickEvent, _, cx| { this.settings.skip_opening = !this.settings.skip_opening; @@ -2053,13 +1916,22 @@ impl Launcher { )) .child(index_row( n + 2, + "Beta builds", + Some(plain( + "New versions as soon as they are released, before they become stable 6 hours later. Off: only stable versions install by themselves.", + )), + Some(betas.into_any_element()), + &t, + )) + .child(index_row( + n + 3, "Show the opening", Some(plain("The wordmark, while the release list loads.")), Some(opening.into_any_element()), &t, )) .child(index_row( - n + 3, + n + 4, "Game menus", Some(plain( "Classic is vanilla's own screens, with no way back inside the game: switch back here. Applies the next time the game starts.", @@ -2067,24 +1939,24 @@ impl Launcher { Some(menus.into_any_element()), &t, )) - .child(self.game_args_row(n + 4, cx)) - .child(index_row(n + 5, "Horizon", Some(plain(&horizon)), horizon_action, &t)) + .child(self.game_args_row(n + 5, cx)) + .child(index_row(n + 6, "Horizon", Some(plain(&horizon)), horizon_action, &t)) .child(index_row( - n + 6, + n + 7, "Launcher", Some(plain(&launcher)), launcher_action, &t, )) .child(index_row( - n + 7, + n + 8, "Data folder", Some(mono(short(&backend::data_dir()))), None, &t, )) .child(index_row( - n + 8, + n + 9, "Logs", Some(mono(format!( "{} · crash reports beside it", @@ -2103,7 +1975,7 @@ impl Launcher { )) .when(cfg!(target_os = "linux"), |d| { d.child(index_row( - n + 9, + n + 10, "Applications menu", Some(plain(if self.settings.desktop_entry() { "Horizon and its icon are in your desktop's menu." @@ -2449,8 +2321,7 @@ impl Launcher { } fn join_friend(&mut self) { - if self.mode != Mode::Client || horizon_friends::invite::parse(&self.friend_code).is_none() - { + if horizon_friends::invite::parse(&self.friend_code).is_none() { return; } self.joining = Some(self.friend_code.clone()); @@ -2460,121 +2331,6 @@ impl Launcher { } } - fn console(&self, cx: &mut Context) -> Div { - let t = self.theme; - let running = self.server.is_some(); - let focused = self.input_focused; - let lines = self.server_log.iter().map(|l| div().child(l.clone())); - let log = div() - .id("console") - .h(px(260.)) - .px(px(20.)) - .py(px(12.)) - .overflow_y_scroll() - .track_scroll(&self.console_scroll) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .line_height(px(19.)) - .text_color(t.ink_soft) - .when(self.server_log.is_empty(), |d| { - d.child(div().text_color(t.muted).child(if running { - "Starting…" - } else { - "The server's output shows here." - })) - }) - .children(lines); - let input = div() - .id("command") - .track_focus(&self.focus) - .flex() - .items_center() - .h(px(theme::FIELD + 8.)) - .px(px(20.)) - .border_t_1() - .border_color(t.rule) - .font_family(theme::MONO) - .text_size(px(theme::CAPTION.px)) - .cursor_text() - .child(div().text_color(t.accent).mr(px(10.)).child("›")) - .child(if self.input.is_empty() && !focused { - div().text_color(t.muted).child(if running { - "Type a command, e.g. list" - } else { - "Start the server to send commands" - }) - } else { - div().text_color(t.ink).child(self.input.clone()) - }) - .when(focused, |d| d.child(div().w(px(1.)).h(px(14.)).bg(t.ink))) - .on_click(cx.listener(|this, _: &ClickEvent, window, cx| { - window.focus(&this.focus); - cx.notify(); - })) - .on_key_down(cx.listener(|this, ev: &KeyDownEvent, _, cx| { - let k = &ev.keystroke; - match k.key.as_str() { - "enter" => this.submit_command(), - "backspace" => { - this.input.pop(); - } - _ if !k.modifiers.control && !k.modifiers.platform => { - if let Some(ch) = &k.key_char { - this.input.push_str(ch); - } - } - _ => return, - } - cx.stop_propagation(); - cx.notify(); - })); - plate(&t) - .flex() - .flex_col() - .overflow_hidden() - .child( - div() - .flex() - .items_center() - .justify_between() - .h(px(44.)) - .px(px(20.)) - .border_b_1() - .border_color(t.rule) - .child( - div() - .flex() - .items_center() - .gap(px(10.)) - .child(div().size(px(6.)).rounded_full().bg(if running { - t.success - } else { - t.muted - })) - .child( - caps(if running { "Running" } else { "Stopped" }) - .text_color(t.muted), - ), - ) - .when(running, |d| { - d.child( - button("kill", "Force stop", Kind::Ghost, &t) - .h(px(26.)) - .px(px(10.)) - .text_size(px(theme::CAPTION.px)) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(s) = &this.server { - s.kill(); - } - cx.notify(); - })), - ) - }), - ) - .child(log) - .child(input) - } - fn versions_page(&mut self, cx: &mut Context) -> Div { let t = self.theme; let header = page_header( @@ -2603,7 +2359,8 @@ impl Launcher { let tag = release.tag.clone(); let installed = self.installed.contains(&tag); let selected = self.selected() == Some(&tag); - let mut meta = vec![release.date.clone()]; + let channel = if release.beta { "Beta" } else { "Stable" }; + let mut meta = vec![channel.to_string(), release.date.clone()]; if let Some((_, size)) = release.asset { meta.push(megabytes(size)); } @@ -2925,13 +2682,14 @@ impl Render for Launcher { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = self.theme; self.perf.frame(); - self.input_focused = self.focus.is_focused(window); + self.servers.note_focus(window); self.friend_focused = self.friend_focus.is_focused(window); self.args_focused = self.args_focus.is_focused(window); let content = match self.page { Page::Play => self.play_page(cx), Page::Versions => self.versions_page(cx), Page::Modpacks => self.modpacks_page(cx), + Page::Servers => self.servers_page(cx), Page::Notes => self.notes_page(cx), Page::Settings => self.settings_page(cx), }; @@ -2950,7 +2708,30 @@ impl Render for Launcher { ); let (reveal, held) = self.opening_phase(window); let ui = ease_out_cubic((reveal - 0.3) / 0.7); + if self.opening.is_none() && window.focused(cx).is_none() { + window.focus(&self.root_focus); + } let mut root = div() + .id("root") + .track_focus(&self.root_focus) + .on_key_down(cx.listener(|this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + match k.key.as_str() { + "tab" => { + KEYBOARD.store(true, Ordering::Relaxed); + if k.modifiers.shift { + window.focus_prev(); + } else { + window.focus_next(); + } + } + "escape" if this.servers_escape() => {} + _ => return, + } + cx.stop_propagation(); + cx.notify(); + })) + .capture_any_mouse_down(|_, _, _| KEYBOARD.store(false, Ordering::Relaxed)) .relative() .flex() .flex_col() @@ -2969,23 +2750,33 @@ impl Render for Launcher { .top(px(theme::RISE * (1. - ui))) .child(self.topbar(cx)) .child( - div() - .id("content") - .relative() - .flex_1() - .min_h_0() - .overflow_y_scroll() - .child( + self.content_scroll + .wrap( div() - .flex() - .px(px(theme::GUTTER)) - .pt(px(24.)) - .pb(px(48.)) - .child(content), - ), + .id("content") + .relative() + .flex_1() + .min_h_0() + .overflow_y_scroll() + .child( + div() + .flex() + .px(px(theme::GUTTER)) + .pt(px(24.)) + .pb(px(48.)) + .child(content), + ), + &t, + ) + .flex_1(), ) .child(self.footer(cx)), ); + if self.page == Page::Servers { + if let Some(dialog) = self.create_dialog(cx) { + root = root.child(dialog); + } + } if self.asking_consent() { root = root.child(self.consent_screen(cx)); } @@ -3107,6 +2898,7 @@ fn main() { ) .expect("window"); cx.on_window_closed(|cx| { + servers_page::stop_on_quit(); telemetry::send_before_exit(); cx.quit() }) diff --git a/launcher/src/mcp.rs b/launcher/src/mcp.rs index 2dd2aa5cb..906cd089f 100644 --- a/launcher/src/mcp.rs +++ b/launcher/src/mcp.rs @@ -95,7 +95,7 @@ impl Session { { out["releases"] = backend::releases()? .iter() - .map(|r| json!({ "tag": r.tag, "name": r.name, "date": r.date, "available_here": r.asset.is_some() })) + .map(|r| json!({ "tag": r.tag, "name": r.name, "date": r.date, "channel": if r.beta { "beta" } else { "stable" }, "available_here": r.asset.is_some() })) .collect(); } Ok(serde_json::to_string_pretty(&out).unwrap()) diff --git a/launcher/src/scrollbar.rs b/launcher/src/scrollbar.rs new file mode 100644 index 000000000..87cdbee77 --- /dev/null +++ b/launcher/src/scrollbar.rs @@ -0,0 +1,193 @@ +//! Pointer-operated scrollbars for the launcher's vertical scroll areas. +use crate::theme::Theme; +use gpui::{ + canvas, div, fill, point, prelude::*, px, size, Bounds, Div, HitboxBehavior, MouseButton, + MouseDownEvent, MouseMoveEvent, MouseUpEvent, ScrollHandle, Stateful, +}; +use std::{cell::Cell, rc::Rc}; + +#[derive(Clone, Default)] +pub(crate) struct Scrollbar { + pub handle: ScrollHandle, + /// Distance from the top of the thumb to the point grabbed by the pointer. + grabbed: Rc>>, +} + +/// Geometry in logical pixels. A minimum thumb size keeps long lists easy to grab. +#[derive(Clone, Copy, Debug)] +struct Geometry { + thumb: f32, + travel: f32, + top: f32, + max: f32, +} + +impl Geometry { + fn new(height: f32, viewport: f32, max: f32, offset: f32) -> Option { + if height <= 0. || viewport <= 0. || max <= 0. { + return None; + } + let thumb = (height * viewport / (viewport + max)).max(32_f32.min(height / 2.)); + let travel = height - thumb; + Some(Self { + thumb, + travel, + top: (-offset / max).clamp(0., 1.) * travel, + max, + }) + } + + fn offset(self, thumb_top: f32) -> f32 { + if self.travel <= 0. { + return 0.; + } + -(thumb_top / self.travel).clamp(0., 1.) * self.max + } +} + +impl Scrollbar { + /// Wrap the scroll container, reserving a narrow gutter so the bar never covers controls. + pub fn wrap(&self, content: Stateful
, theme: &Theme) -> Div { + let state = self.clone(); + let track_color = theme.rule; + let thumb_color = theme.muted; + div() + .relative() + .flex() + .flex_col() + .min_h_0() + .min_w_0() + .child( + content + .track_scroll(&self.handle) + .mr(px(16.)) + // Nested scroll areas must not also move the page behind them. + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()), + ) + .child( + canvas( + move |bounds, window, _| { + let geometry = Geometry::new( + bounds.size.height.into(), + state.handle.bounds().size.height.into(), + state.handle.max_offset().height.into(), + state.handle.offset().y.into(), + ); + let hitbox = + geometry.map(|_| window.insert_hitbox(bounds, HitboxBehavior::Normal)); + (state, geometry, hitbox) + }, + move |bounds, (state, geometry, hitbox), window, _| { + let Some(g) = geometry else { + state.grabbed.set(None); + return; + }; + let hitbox = hitbox.unwrap(); + window.paint_quad(fill(bounds, track_color).corner_radii(px(3.))); + window.paint_quad( + fill( + Bounds::new( + point(bounds.left() + px(3.), bounds.top() + px(g.top)), + size(bounds.size.width - px(6.), px(g.thumb)), + ), + thumb_color, + ) + .corner_radii(px(3.)), + ); + window.on_mouse_event({ + let state = state.clone(); + move |ev: &MouseDownEvent, phase, window, cx| { + if !phase.bubble() + || ev.button != MouseButton::Left + || !hitbox.is_hovered(window) + { + return; + } + let y = f32::from(ev.position.y - bounds.top()); + let grab = if (g.top..=g.top + g.thumb).contains(&y) { + y - g.top + } else { + // Clicking the track centers the thumb at the pointer. + let grab = g.thumb / 2.; + let mut offset = state.handle.offset(); + offset.y = px(g.offset(y - grab)); + state.handle.set_offset(offset); + grab + }; + state.grabbed.set(Some(grab)); + cx.stop_propagation(); + window.refresh(); + } + }); + window.on_mouse_event({ + let state = state.clone(); + move |ev: &MouseMoveEvent, phase, window, cx| { + if !phase.capture() { + return; + } + let Some(grab) = state.grabbed.get() else { + return; + }; + if ev.pressed_button != Some(MouseButton::Left) { + state.grabbed.set(None); + return; + } + let mut offset = state.handle.offset(); + offset.y = + px(g.offset(f32::from(ev.position.y - bounds.top()) - grab)); + state.handle.set_offset(offset); + cx.stop_propagation(); + window.refresh(); + } + }); + window.on_mouse_event(move |ev: &MouseUpEvent, phase, window, cx| { + if phase.capture() + && ev.button == MouseButton::Left + && state.grabbed.take().is_some() + { + cx.stop_propagation(); + window.refresh(); + } + }); + }, + ) + .absolute() + .right(px(2.)) + .top_0() + .bottom_0() + .w(px(12.)), + ) + } +} + +#[cfg(test)] +mod tests { + use super::Geometry; + + #[test] + fn hides_without_overflow() { + assert!(Geometry::new(200., 200., 0., 0.).is_none()); + assert!(Geometry::new(0., 200., 100., 0.).is_none()); + } + + #[test] + fn thumb_tracks_wheel_offsets_and_pointer_reaches_both_ends() { + let g = Geometry::new(200., 200., 600., -300.).unwrap(); + assert_eq!(g.thumb, 50.); + assert_eq!(g.top, 75.); + assert_eq!(g.offset(g.top), -300.); + assert_eq!(g.offset(-100.), 0.); + assert_eq!(g.offset(1000.), -600.); + } + + #[test] + fn long_lists_and_small_viewports_keep_geometry_bounded() { + let g = Geometry::new(200., 200., 20000., -20000.).unwrap(); + assert_eq!(g.thumb, 32.); + assert_eq!(g.top, g.travel); + assert_eq!(g.offset(g.travel), -20000.); + let tiny = Geometry::new(20., 20., 1000., -500.).unwrap(); + assert_eq!(tiny.thumb, 10.); + assert_eq!(tiny.offset(10.), -1000.); + } +} diff --git a/launcher/src/servers.rs b/launcher/src/servers.rs new file mode 100644 index 000000000..87dccbf35 --- /dev/null +++ b/launcher/src/servers.rs @@ -0,0 +1,968 @@ +//! Servers hosted from the launcher. Every server is a `horizon-server` folder and the launcher drives +//! `horizon-server` (docs/server.md in the repository) rather than its own copy of the logic: `init`, +//! `start`, `stop`, `config set`, `backup`, `restore`, `update`, `service`, and the control API the running +//! supervisor serves on 127.0.0.1 for the live status, the log and console commands. +//! +//! The programs come from an installed Horizon version, laid out as `install.sh` lays them out +//! (`server-runtime/releases/`, `current`, `game-files/`), so `horizon-server update` and its +//! rollback work on them unchanged. The game files are the player's own, copied from the version the +//! launcher prepared: nothing of Mojang's is downloaded or shipped. + +use crate::backend; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::time::Duration; + +const PROGRAM: &str = if cfg!(windows) { + "horizon-server.exe" +} else { + "horizon-server" +}; + +/// The Minecraft EULA a server owner agrees to. +pub const EULA_URL: &str = "https://aka.ms/MinecraftEULA"; + +// ----- The list of servers ----------------------------------------------------------------------- + +/// One server the launcher knows: its name and its folder. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Entry { + pub name: String, + pub dir: PathBuf, +} + +fn list_file() -> PathBuf { + backend::data_dir().join("servers.json") +} + +/// The servers, in the order they were added; folders that are gone are left out. +pub fn list() -> Vec { + let entries: Vec = fs::read_to_string(list_file()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + entries.into_iter().filter(|e| e.dir.is_dir()).collect() +} + +fn save_list(entries: &[Entry]) -> Result<(), String> { + fs::create_dir_all(backend::data_dir()).map_err(|e| e.to_string())?; + let text = serde_json::to_string_pretty(entries).map_err(|e| e.to_string())?; + fs::write(list_file(), text).map_err(|e| e.to_string()) +} + +/// Adds a server folder to the list (once). +pub fn add(entry: Entry) -> Result<(), String> { + let mut all = list(); + all.retain(|e| e.dir != entry.dir); + all.push(entry); + save_list(&all) +} + +/// Takes a server off the list; its folder stays. +pub fn forget(dir: &Path) -> Result<(), String> { + let mut all = list(); + all.retain(|e| e.dir != dir); + save_list(&all) +} + +/// A folder name for a server name: lower case letters, digits and dashes. +pub fn slug(name: &str) -> String { + let mut out = String::new(); + for c in name.trim().chars() { + if c.is_ascii_alphanumeric() { + out.push(c.to_ascii_lowercase()); + } else if !out.ends_with('-') { + out.push('-'); + } + } + let out = out.trim_matches('-').to_string(); + if out.is_empty() { + "server".into() + } else { + out + } +} + +/// A new folder for a server called `name`, under `servers/` in the data folder. +pub fn new_folder(name: &str) -> PathBuf { + let root = backend::data_dir().join("servers"); + let base = slug(name); + let mut dir = root.join(&base); + let mut n = 2; + while dir.exists() { + dir = root.join(format!("{base}-{n}")); + n += 1; + } + dir +} + +// ----- The programs: an installed Horizon version, laid out as install.sh does --------------------- + +pub fn runtime_root() -> PathBuf { + backend::data_dir().join("server-runtime") +} + +/// `horizon-server` of the release in use, once one is set up. +pub fn program() -> Option { + Some(runtime_root().join("current").join(PROGRAM)).filter(|p| p.is_file()) +} + +/// The release the servers run. +pub fn runtime_release() -> Option { + let target = fs::canonicalize(runtime_root().join("current")).ok()?; + Some(target.file_name()?.to_string_lossy().into_owned()) +} + +/// Where `horizon-server` finds the game files: the folder install.sh keeps across updates. +pub fn game_files(root: &Path, game_version: &str) -> PathBuf { + root.join("game-files/horizon-client").join(game_version) +} + +/// Whether the servers' game files are there. +pub fn game_files_ready() -> bool { + game_files(&runtime_root(), "26.3") + .join("horizon-resources.json") + .is_file() +} + +/// Whether an installed version can host: it ships `horizon-server` and is prepared. +pub fn can_host(tag: &str) -> Result<(), String> { + if !backend::version_dir(tag).join(PROGRAM).is_file() { + return Err(format!( + "Horizon {tag} has no server program. Install a newer version on the Versions page." + )); + } + if !backend::is_prepared(tag) { + return Err(format!( + "Horizon {tag} isn't prepared yet: press Prepare on the Play page (it uses your own Minecraft {})", + backend::game_version(tag) + )); + } + Ok(()) +} + +/// Sets up the servers' programs from the installed version `tag` (if none are yet) and copies its +/// prepared game files for them. Safe to run again: it only refreshes the game files. +pub fn set_up(tag: &str) -> Result<(), String> { + can_host(tag)?; + // The data generator's reports the game reads at run time, as Play checks them. + backend::need_prepared(tag)?; + set_up_in( + &runtime_root(), + &backend::version_dir(tag), + tag, + &backend::game_version(tag), + ) +} + +/// [`set_up`] with its folders given (for tests). +pub fn set_up_in(root: &Path, version: &Path, tag: &str, game_version: &str) -> Result<(), String> { + let releases = root.join("releases"); + fs::create_dir_all(&releases).map_err(|e| format!("{}: {e}", releases.display()))?; + let release = releases.join(tag); + if !root.join("current").exists() { + if !release.join(PROGRAM).is_file() { + let scratch = releases.join(format!(".{tag}.copying")); + let _ = fs::remove_dir_all(&scratch); + copy_release(version, &scratch).map_err(|e| format!("copying {tag}: {e}"))?; + let _ = fs::remove_dir_all(&release); + fs::rename(&scratch, &release).map_err(|e| e.to_string())?; + } + let local = release.join(".local"); + fs::create_dir_all(&local).map_err(|e| e.to_string())?; + let link = local.join("horizon-client"); + if link.symlink_metadata().is_err() { + fs::create_dir_all(root.join("game-files/horizon-client")) + .map_err(|e| e.to_string())?; + point(&link, &root.join("game-files/horizon-client")).map_err(|e| e.to_string())?; + } + point(&root.join("current"), &release).map_err(|e| e.to_string())?; + } + // The game files: a copy (preparing again rewrites files in place), swapped in whole. + let from = version.join(".local/horizon-client").join(game_version); + let to = game_files(root, game_version); + let fresh = to.with_extension("copying"); + let _ = fs::remove_dir_all(&fresh); + copy_dir(&from, &fresh).map_err(|e| format!("copying the game files: {e}"))?; + let old = to.with_extension("old"); + let _ = fs::remove_dir_all(&old); + if to.exists() { + fs::rename(&to, &old).map_err(|e| e.to_string())?; + } + fs::rename(&fresh, &to).map_err(|e| e.to_string())?; + let _ = fs::remove_dir_all(&old); + Ok(()) +} + +/// A release folder without the launcher's own files (its prepared copy and install marker). +fn copy_release(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let name = entry.file_name(); + if name == ".local" || name == ".installed" { + continue; + } + let target = to.join(&name); + if entry.file_type()?.is_dir() { + copy_dir(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), &target)?; + } + } + Ok(()) +} + +fn copy_dir(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let target = to.join(entry.file_name()); + let kind = entry.file_type()?; + if kind.is_dir() { + copy_dir(&entry.path(), &target)?; + } else if kind.is_file() { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +/// Makes `link` point at the folder `target`, as install.sh (a symbolic link) and install.ps1 (a +/// junction, which needs no admin rights) do. +fn point(link: &Path, target: &Path) -> std::io::Result<()> { + let fresh = link.with_extension("switching"); + let _ = fs::remove_file(&fresh); + #[cfg(unix)] + { + std::os::unix::fs::symlink(target, &fresh)?; + fs::rename(&fresh, link) + } + #[cfg(windows)] + { + let _ = fs::remove_dir(link); + let status = Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(link) + .arg(target) + .stdout(Stdio::null()) + .status()?; + if status.success() { + Ok(()) + } else { + Err(std::io::Error::other("mklink /J failed")) + } + } +} + +// ----- Running horizon-server ------------------------------------------------------------------- + +/// `horizon-server --dir `. +pub fn command(dir: &Path, args: &[&str]) -> Result { + let program = program().ok_or( + "The server programs aren't set up yet: create a server, or press Prepare on its page.", + )?; + let mut cmd = Command::new(program); + cmd.arg("--dir").arg(dir).args(args); + #[cfg(windows)] + std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW + Ok(cmd) +} + +fn supervisor_log(dir: &Path) -> PathBuf { + dir.join("logs/supervisor.log") +} + +fn log_length(dir: &Path) -> u64 { + fs::metadata(supervisor_log(dir)).map_or(0, |m| m.len()) +} + +/// Runs one `horizon-server` command to its end: what it printed, or the problem in plain words. +pub fn run(dir: &Path, args: &[&str]) -> Result { + let since = log_length(dir); + let output = command(dir, args) + .map_err(Problem::plain)? + .stdin(Stdio::null()) + .output() + .map_err(|e| Problem::plain(format!("Couldn't run horizon-server: {e}")))?; + let out = String::from_utf8_lossy(&output.stdout).into_owned(); + if output.status.success() { + Ok(out) + } else { + let err = String::from_utf8_lossy(&output.stderr); + Err(Problem::explain(&format!("{out}\n{err}"), dir, since)) + } +} + +/// Runs a long `horizon-server` command, passing each line it prints to `line`. +pub fn run_streamed(dir: &Path, args: &[&str], line: &dyn Fn(String)) -> Result<(), Problem> { + use std::io::{BufRead, BufReader, Read}; + let since = log_length(dir); + let mut child = command(dir, args) + .map_err(Problem::plain)? + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| Problem::plain(format!("Couldn't run horizon-server: {e}")))?; + let mut err = child.stderr.take(); + let errors = std::thread::spawn(move || { + let mut text = String::new(); + if let Some(e) = &mut err { + let _ = e.read_to_string(&mut text); + } + text + }); + let mut out = String::new(); + if let Some(stdout) = child.stdout.take() { + // `start` prints a dot every half second on one line: those aren't lines worth showing. + for l in BufReader::new(stdout).lines().map_while(Result::ok) { + let shown = l + .trim_start_matches(['.', ' ']) + .trim_start_matches("Starting"); + let shown = shown.trim_start_matches('.').trim(); + if !shown.is_empty() { + line(shown.to_string()); + } + out.push_str(&l); + out.push('\n'); + } + } + let status = child.wait().map_err(|e| Problem::plain(e.to_string()))?; + let err = errors.join().unwrap_or_default(); + if status.success() { + Ok(()) + } else { + Err(Problem::explain(&format!("{out}\n{err}"), dir, since)) + } +} + +/// What can be done about a problem, with one button. +#[derive(Clone, Debug, PartialEq)] +pub enum Fix { + /// The port is taken: use this free one. + UsePort(u16), + /// The game files are missing: prepare them (Play page) and copy them for the servers. + Prepare, + /// The EULA isn't agreed to. + AgreeEula, + /// The game's own log says more. + ShowLog, +} + +/// A problem, in plain words. +#[derive(Clone, Debug, PartialEq)] +pub struct Problem { + pub message: String, + pub fix: Option, +} + +impl Problem { + pub fn plain(message: impl Into) -> Self { + Self { + message: message.into(), + fix: None, + } + } + + /// Reads what `horizon-server` (and the game log it points at) said. + /// `since` is the background server's log length before the command: only what it logged after counts. + pub fn explain(output: &str, dir: &Path, since: u64) -> Self { + let log = fs::read(supervisor_log(dir)).unwrap_or_default(); + let new = log.get(since as usize..).unwrap_or_default(); + Self::explain_with(output, &String::from_utf8_lossy(new), dir) + } + + fn explain_with(output: &str, log: &str, dir: &Path) -> Self { + let both = format!("{output}\n{log}"); + let has = |s: &str| both.contains(s); + // Vanilla says FAILED TO BIND TO PORT for any failure while starting; only these are a busy port. + let busy = [ + "already in use", + "Address in use", + "Only one usage of each socket address", + ]; + if busy.iter().any(|b| both.contains(b)) { + let port = config(dir) + .and_then(|c| c["server"]["port"].as_u64()) + .unwrap_or(25565) as u16; + return Self { + message: format!( + "Port {port} is already used by another program (maybe another server). Use a free \ + port instead: friends then add it to the address." + ), + fix: Some(Fix::UsePort(free_port(port + 1, &[]))), + }; + } + if has("no prepared game files") || has("not found next to the resources") { + return Self { + message: + "The server needs the game files from your own Minecraft. Prepare them: it \ + takes a few minutes, once." + .into(), + fix: Some(Fix::Prepare), + }; + } + if has("EULA") && !has("eula=true") { + return Self { + message: "Running a server needs your agreement to the Minecraft EULA.".into(), + fix: Some(Fix::AgreeEula), + }; + } + if has("isn't up after") || has("the server stopped") { + return Self { + message: "The game didn't start. Its log below says why.".into(), + fix: Some(Fix::ShowLog), + }; + } + let said = both + .lines() + .rev() + .find_map(|l| l.strip_prefix("horizon-server: ")) + .map(str::to_string) + .or_else(|| { + output + .lines() + .rev() + .find(|l| !l.trim().is_empty()) + .map(str::to_string) + }) + .unwrap_or_else(|| "horizon-server failed without saying why".into()); + Self::plain(capitalised(&said)) + } +} + +fn capitalised(s: &str) -> String { + let mut c = s.chars(); + match c.next() { + Some(f) => f.to_uppercase().chain(c).collect(), + None => String::new(), + } +} + +// ----- Creating a server ------------------------------------------------------------------------ + +/// The world a new server starts with. +#[derive(Clone, Debug, PartialEq)] +pub enum World { + /// A new world; an empty seed is a random one. + New { seed: String }, + /// A copy of one of the player's worlds (its folder). + Copy(PathBuf), +} + +/// What the Create dialog asks; [`NewServer::default`] alone makes a working server. +#[derive(Clone, Debug, PartialEq)] +pub struct NewServer { + pub name: String, + pub world: World, + pub game_mode: String, + pub difficulty: String, + pub max_players: u32, + /// Only listed players (and operators) may join. + pub friends_only: bool, + /// Check players' Minecraft accounts: they must sign in with Microsoft. + pub check_accounts: bool, + /// Who may join first (whitelisted), and the first of them becomes an operator. + pub players: Vec, + pub eula: bool, +} + +impl Default for NewServer { + fn default() -> Self { + Self { + name: "My server".into(), + world: World::New { + seed: String::new(), + }, + game_mode: "survival".into(), + difficulty: "normal".into(), + max_players: 10, + friends_only: true, + check_accounts: false, + players: Vec::new(), + eula: false, + } + } +} + +/// A port nobody listens on, from `from` up, and not one of `taken`. +pub fn free_port(from: u16, taken: &[u16]) -> u16 { + (from..u16::MAX) + .find(|p| !taken.contains(p) && std::net::TcpListener::bind(("0.0.0.0", *p)).is_ok()) + .unwrap_or(from) +} + +/// The ports the launcher's other servers use: their game port and their web panel. +fn ports_taken() -> Vec { + let mut out = Vec::new(); + for e in list() { + if let Some(c) = config(&e.dir) { + out.extend(c["server"]["port"].as_u64().map(|p| p as u16)); + out.extend( + c["panel"]["bind"] + .as_str() + .and_then(|b| b.rsplit_once(':')) + .and_then(|(_, p)| p.parse::().ok()), + ); + } + } + out +} + +/// The player's worlds (the game home's `saves/`), newest first: their name and folder. +pub fn player_worlds() -> Vec<(String, PathBuf)> { + let saves = backend::game_home().join("saves"); + let mut worlds: Vec<(std::time::SystemTime, String, PathBuf)> = fs::read_dir(saves) + .into_iter() + .flatten() + .flatten() + .filter(|e| e.path().join("level.dat").is_file()) + .map(|e| { + let when = e + .path() + .join("level.dat") + .metadata() + .and_then(|m| m.modified()) + .unwrap_or(std::time::UNIX_EPOCH); + (when, e.file_name().to_string_lossy().into_owned(), e.path()) + }) + .collect(); + worlds.sort_by_key(|w| std::cmp::Reverse(w.0)); + worlds.into_iter().map(|(_, n, p)| (n, p)).collect() +} + +/// The `horizon-server init` arguments for a new server. +pub fn init_args(spec: &NewServer, world: &str, port: u16) -> Vec { + let mut args: Vec = vec!["init".into(), "--yes".into()]; + if spec.eula { + args.push("--eula".into()); + } + args.extend(["--world".into(), world.to_string()]); + if let World::New { seed } = &spec.world { + if !seed.trim().is_empty() { + args.extend(["--seed".into(), seed.trim().to_string()]); + } + } + args.extend(["--port".into(), port.to_string()]); + args.push(if spec.friends_only { + "--whitelist".into() + } else { + "--no-whitelist".into() + }); + if !spec.check_accounts { + args.push("--offline".into()); + } + for p in &spec.players { + args.extend(["--player".into(), p.clone()]); + } + if let Some(first) = spec.players.first() { + args.extend(["--op".into(), first.clone()]); + } + args +} + +/// The `horizon-server config set` arguments that finish a new server. +pub fn settings_args(spec: &NewServer, panel_port: u16) -> Vec { + vec![ + "config".into(), + "set".into(), + format!("world.game_mode={}", spec.game_mode), + format!("world.difficulty={}", spec.difficulty), + format!("server.max_players={}", spec.max_players.clamp(1, 1000)), + format!("server.motd={}", spec.name.trim()), + format!("panel.bind=127.0.0.1:{panel_port}"), + ] +} + +/// Creates a server: its folder, the world (a copy when asked), `init` and the settings, then adds it to +/// the list. `tag` is the installed version whose programs and game files it uses when none are set up. +pub fn create(spec: &NewServer, tag: Option<&str>, log: &dyn Fn(String)) -> Result { + if !spec.eula { + return Err(Problem { + message: "Running a server needs your agreement to the Minecraft EULA.".into(), + fix: Some(Fix::AgreeEula), + }); + } + if program().is_none() || !game_files_ready() { + let tag = tag.ok_or_else(|| { + Problem::plain("Install a Horizon version first (Versions page), then prepare it.") + })?; + log(format!("Setting up the server programs from Horizon {tag}")); + set_up(tag).map_err(|e| { + if e.contains("prepared") { + Problem { + message: e, + fix: Some(Fix::Prepare), + } + } else { + Problem::plain(e) + } + })?; + } + let name = if spec.name.trim().is_empty() { + "My server".to_string() + } else { + spec.name.trim().to_string() + }; + let dir = new_folder(&name); + fs::create_dir_all(&dir).map_err(|e| Problem::plain(e.to_string()))?; + let world = match &spec.world { + World::New { .. } => "world".to_string(), + World::Copy(from) => { + let world = from + .file_name() + .map(|n| slug(&n.to_string_lossy())) + .unwrap_or_else(|| "world".into()); + log(format!("Copying the world {}", from.display())); + copy_world(from, &dir.join(&world)).map_err(|e| { + let _ = fs::remove_dir_all(&dir); + Problem::plain(format!("Couldn't copy the world: {e}")) + })?; + world + } + }; + let taken = ports_taken(); + let port = free_port(25565, &taken); + let panel = free_port(8130, &taken); + let undo = |p: Problem| { + let _ = fs::remove_dir_all(&dir); + p + }; + let init = init_args(spec, &world, port); + log("Writing the server's settings".into()); + run(&dir, &init.iter().map(String::as_str).collect::>()).map_err(undo)?; + let settings = settings_args(spec, panel); + run( + &dir, + &settings.iter().map(String::as_str).collect::>(), + ) + .map_err(undo)?; + let entry = Entry { name, dir }; + add(entry.clone()).map_err(Problem::plain)?; + Ok(entry) +} + +/// A copy of a world folder, without the lock a running game holds. +fn copy_world(from: &Path, to: &Path) -> std::io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let name = entry.file_name(); + if name == "session.lock" { + continue; + } + let target = to.join(&name); + if entry.file_type()?.is_dir() { + copy_world(&entry.path(), &target)?; + } else { + fs::copy(entry.path(), target)?; + } + } + Ok(()) +} + +// ----- A server's files -------------------------------------------------------------------------- + +/// The settings, as `horizon-server config --json` prints them (`None` before `init`, or from a +/// `horizon-server` older than the command). +pub fn config(dir: &Path) -> Option { + if !dir.join("server.toml").is_file() { + return None; + } + let out = run(dir, &["config", "--json"]).ok()?; + serde_json::from_str(out.trim()).ok() +} + +/// What `config set` did: the settings applied now, and those waiting for a restart. +#[derive(Clone, Debug, Default, PartialEq, Deserialize)] +pub struct Applied { + #[serde(default)] + pub applied: Vec, + #[serde(default)] + pub restart: Vec, + #[serde(default)] + pub running: bool, +} + +/// Changes settings through `horizon-server config set` (checked there; nothing is written if one is +/// wrong). +pub fn set_config(dir: &Path, changes: &[(&str, String)]) -> Result { + let pairs: Vec = changes.iter().map(|(k, v)| format!("{k}={v}")).collect(); + let mut args = vec!["config", "set"]; + args.extend(pairs.iter().map(String::as_str)); + args.push("--json"); + let out = run(dir, &args)?; + serde_json::from_str(out.trim()).map_err(|e| Problem::plain(e.to_string())) +} + +/// A list file's names (`whitelist.json`, `ops.json`, `banned-players.json`), as vanilla writes them. +pub fn names(dir: &Path, file: &str) -> Vec { + fs::read_to_string(dir.join(file)) + .ok() + .and_then(|t| serde_json::from_str::>(&t).ok()) + .unwrap_or_default() + .iter() + .filter_map(|e| e["name"].as_str().map(str::to_string)) + .collect() +} + +/// A list file's names with their UUIDs (empty when the file has none). +pub fn entries(dir: &Path, file: &str) -> Vec<(String, String)> { + fs::read_to_string(dir.join(file)) + .ok() + .and_then(|t| serde_json::from_str::>(&t).ok()) + .unwrap_or_default() + .iter() + .filter_map(|e| { + let name = e["name"].as_str()?.to_string(); + Some((name, e["uuid"].as_str().unwrap_or_default().to_string())) + }) + .collect() +} + +/// A backup, as `horizon-server backups --json` lists it. +#[derive(Clone, Debug, PartialEq, Deserialize)] +pub struct Backup { + pub name: String, + pub bytes: u64, + #[serde(default)] + pub modified: Option, +} + +pub fn backups(dir: &Path) -> Result, Problem> { + let out = run(dir, &["backups", "--json"])?; + serde_json::from_str(out.trim()).map_err(|e| Problem::plain(e.to_string())) +} + +/// The address friends on the same network type: this computer's LAN address. No packet is sent: the +/// system only picks the interface it would use. +pub fn lan_address() -> Option { + let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; + socket.connect("192.0.2.1:9").ok()?; + let ip = socket.local_addr().ok()?.ip(); + (!ip.is_unspecified() && !ip.is_loopback()).then_some(ip) +} + +/// Whether the server starts at login: the service definition `horizon-server service print` names exists. +pub fn service_installed(dir: &Path) -> bool { + if cfg!(windows) { + let name = format!("horizon-server-{}", service_suffix(dir)); + return Command::new("schtasks") + .args(["/Query", "/TN", &name]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()); + } + run(dir, &["service", "print"]) + .ok() + .and_then(|out| { + out.lines() + .next() + .and_then(|l| l.strip_prefix("# ")) + .map(PathBuf::from) + }) + .is_some_and(|p| p.is_file()) +} + +/// horizon-server's service name for a folder, after `horizon-server-`. +fn service_suffix(dir: &Path) -> String { + let folder = dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let clean: String = folder + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() { + c.to_ascii_lowercase() + } else { + '-' + } + }) + .collect(); + let clean = clean.trim_matches('-'); + if clean.is_empty() { + "server".into() + } else { + clean.into() + } +} + +// ----- The running server: its control API ------------------------------------------------------- + +/// The running supervisor's control API (`.horizon/api.json`: its address and token). +#[derive(Clone, Debug)] +pub struct Api { + address: String, + token: String, +} + +impl Api { + /// The API of the server running in `dir`, if one runs. + pub fn open(dir: &Path) -> Option { + let text = fs::read_to_string(dir.join(".horizon/api.json")).ok()?; + let v: Value = serde_json::from_str(&text).ok()?; + Some(Self { + address: v["address"].as_str()?.to_string(), + token: v["token"].as_str()?.to_string(), + }) + } + + pub fn call(&self, method: &str, path: &str, body: Option) -> Result { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(10)) + .build(); + let request = agent + .request(method, &format!("http://{}{path}", self.address)) + .set("Authorization", &format!("Bearer {}", self.token)); + let response = match body { + Some(b) => request.send_json(b), + None => request.call(), + }; + match response { + Ok(r) => r.into_json().map_err(|e| e.to_string()), + Err(ureq::Error::Status(_, r)) => { + let v: Value = r.into_json().unwrap_or(Value::Null); + Err(v["error"] + .as_str() + .unwrap_or("the server refused") + .to_string()) + } + Err(e) => Err(e.to_string()), + } + } + + pub fn status(&self) -> Option { + self.call("GET", "/api/v1/status", None) + .ok() + .map(|v| Status::parse(&v)) + } + + /// The log lines after `since`, and the number to ask from next time. + pub fn logs(&self, since: u64) -> Option<(u64, Vec)> { + let v = self + .call("GET", &format!("/api/v1/logs?since={since}"), None) + .ok()?; + let lines = v["lines"] + .as_array()? + .iter() + .filter_map(|l| l.as_str().map(str::to_string)) + .collect(); + Some((v["next"].as_u64().unwrap_or(since), lines)) + } + + /// One console command; what the game answered. + pub fn command(&self, line: &str) -> Result, String> { + let v = self.call("POST", "/api/v1/command", Some(json!({ "line": line })))?; + Ok(v["output"] + .as_array() + .into_iter() + .flatten() + .filter_map(|l| l.as_str().map(str::to_string)) + .collect()) + } + + /// A one-time login link for the web panel. + pub fn panel_link(&self) -> Result { + let v = self.call("POST", "/api/v1/panel/login", None)?; + v["url"] + .as_str() + .map(str::to_string) + .ok_or_else(|| "the panel gave no link".into()) + } +} + +/// A player online. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Player { + pub name: String, + pub uuid: String, + pub ping: Option, +} + +/// What the supervisor reports. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Status { + /// starting, running, stopping or restarting (stopped when nothing answers). + pub phase: String, + pub uptime: Option, + pub crashes: u64, + pub last_crash: Option, + pub tps: Option, + pub mspt: Option, + pub players: Vec, + pub max_players: Option, + pub ram_bytes: Option, + pub cpu_percent: Option, + /// Paused because nobody is online (vanilla's pause-when-empty). + pub paused: bool, + /// The release in use and a newer one, when the supervisor found one. + pub release: Option, + pub update_available: Option, + /// An update under way: what it is doing now. + pub update_busy: Option, + /// How the last update went (its message, and whether it worked). + pub update_last: Option<(String, bool)>, +} + +impl Status { + pub fn stopped() -> Self { + Self { + phase: "stopped".into(), + ..Self::default() + } + } + + pub fn parse(v: &Value) -> Self { + let game = &v["sample"]["game"]; + let update = &v["update"]; + Self { + phase: v["phase"].as_str().unwrap_or("stopped").to_string(), + uptime: v["engine_uptime_seconds"].as_u64(), + crashes: v["crashes"].as_u64().unwrap_or(0), + last_crash: v["last_crash"].as_str().map(str::to_string), + tps: game["tps"].as_f64(), + mspt: game["mspt"]["average"].as_f64(), + players: game["players"] + .as_array() + .into_iter() + .flatten() + .map(|p| Player { + name: p["name"].as_str().unwrap_or_default().to_string(), + uuid: p["uuid"].as_str().unwrap_or_default().to_string(), + ping: p["ping"].as_u64(), + }) + .collect(), + max_players: game["max_players"].as_u64(), + ram_bytes: v["sample"]["rss_bytes"].as_u64(), + cpu_percent: v["sample"]["cpu_percent"].as_f64(), + paused: game["paused"] == true, + release: update["installed"].as_str().map(str::to_string), + update_available: update["available"].as_str().map(str::to_string), + update_busy: update["busy"].as_str().map(str::to_string), + update_last: update["last"] + .as_str() + .map(|m| (m.to_string(), update["ok"] != false)), + } + } + + pub fn running(&self) -> bool { + self.phase != "stopped" + } +} + +/// The status of the server in `dir`: what its API says, or stopped. +pub fn status(dir: &Path) -> Status { + Api::open(dir) + .and_then(|api| api.status()) + .unwrap_or_else(Status::stopped) +} + +#[cfg(test)] +#[path = "servers/tests.rs"] +mod tests; diff --git a/launcher/src/servers/tests.rs b/launcher/src/servers/tests.rs new file mode 100644 index 000000000..f096baf3a --- /dev/null +++ b/launcher/src/servers/tests.rs @@ -0,0 +1,225 @@ +use super::*; +use std::io::{BufRead, BufReader, Write}; + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("horizon-servers-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(&dir).unwrap(); + dir +} + +#[test] +fn folder_names_are_plain() { + assert_eq!(slug("Ludo's Survival!"), "ludo-s-survival"); + assert_eq!(slug(" "), "server"); + assert_eq!(slug("Été 2026"), "t-2026"); + assert_eq!(service_suffix(Path::new("/x/My World")), "my-world"); +} + +#[test] +fn create_asks_init_and_config_set() { + let spec = NewServer { + name: "Friends".into(), + world: World::New { + seed: " 12345 ".into(), + }, + players: vec!["Alex".into(), "Steve".into()], + eula: true, + ..NewServer::default() + }; + assert_eq!( + init_args(&spec, "world", 25566).join(" "), + "init --yes --eula --world world --seed 12345 --port 25566 --whitelist --offline \ + --player Alex --player Steve --op Alex" + ); + let open = NewServer { + friends_only: false, + check_accounts: true, + world: World::Copy("/saves/Old".into()), + ..NewServer::default() + }; + assert_eq!( + init_args(&open, "old", 25565).join(" "), + "init --yes --world old --port 25565 --no-whitelist" + ); + assert_eq!( + settings_args(&spec, 8131).join(" "), + "config set world.game_mode=survival world.difficulty=normal server.max_players=10 \ + server.motd=Friends panel.bind=127.0.0.1:8131" + ); +} + +#[cfg(unix)] +#[test] +fn programs_are_laid_out_as_install_sh_does() { + let root = scratch("runtime"); + let version = root.join("versions/v1"); + fs::create_dir_all(version.join(".local/horizon-client/26.3")).unwrap(); + fs::write(version.join(PROGRAM), "server").unwrap(); + fs::write(version.join("horizon-client"), "game").unwrap(); + fs::write(version.join(".installed"), "").unwrap(); + fs::write( + version.join(".local/horizon-client/26.3/horizon-resources.json"), + "{}", + ) + .unwrap(); + let rt = root.join("runtime"); + set_up_in(&rt, &version, "v1", "26.3").unwrap(); + assert_eq!( + fs::read_to_string(rt.join("current").join(PROGRAM)).unwrap(), + "server" + ); + assert!(!rt.join("releases/v1/.installed").exists()); + // The release finds the game files where horizon-server looks: .local beside it. + assert!(rt + .join("current/.local/horizon-client/26.3/horizon-resources.json") + .is_file()); + // Again with newer game files: only they change, swapped in whole. + fs::write( + version.join(".local/horizon-client/26.3/horizon-resources.json"), + "{\"new\":1}", + ) + .unwrap(); + set_up_in(&rt, &version, "v1", "26.3").unwrap(); + assert_eq!( + fs::read_to_string(game_files(&rt, "26.3").join("horizon-resources.json")).unwrap(), + "{\"new\":1}" + ); + assert!(!game_files(&rt, "26.3").with_extension("old").exists()); + fs::remove_dir_all(&root).unwrap(); +} + +#[test] +fn problems_say_what_to_do() { + let dir = scratch("problems"); + let port = Problem::explain_with( + "", + "[Server thread/WARN]: **** FAILED TO BIND TO PORT!\nThe exception was: Address already in use (os error 48)", + &dir, + ); + assert!(port.message.contains("already used"), "{}", port.message); + assert!(matches!(port.fix, Some(Fix::UsePort(p)) if p > 25565)); + let files = Problem::explain_with( + "horizon-server: no prepared game files. Horizon reads them from", + "", + &dir, + ); + assert_eq!(files.fix, Some(Fix::Prepare)); + let reports = Problem::explain_with( + "", + "**** FAILED TO BIND TO PORT!\nThe exception was: registries.json not found next to the resources", + &dir, + ); + assert_eq!(reports.fix, Some(Fix::Prepare)); + let other = Problem::explain_with("horizon-server: a server is already running in x", "", &dir); + assert_eq!(other, Problem::plain("A server is already running in x")); + fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn lists_and_status_read_as_vanilla_and_the_supervisor_write_them() { + let dir = scratch("lists"); + fs::write( + dir.join("whitelist.json"), + r#"[{"uuid": "a", "name": "Alex"}, {"uuid": "b", "name": "Steve"}]"#, + ) + .unwrap(); + assert_eq!(names(&dir, "whitelist.json"), ["Alex", "Steve"]); + assert!(names(&dir, "ops.json").is_empty()); + fs::remove_dir_all(&dir).unwrap(); + + let s = Status::parse(&json!({ + "phase": "running", "engine_uptime_seconds": 61, "crashes": 1, "last_crash": "signal: 9", + "sample": { "rss_bytes": 800_000_000u64, "cpu_percent": 3.5, "game": { + "tps": 20.0, "mspt": { "average": 4.2 }, "max_players": 10, "paused": false, + "players": [{ "name": "Alex", "uuid": "u1", "ping": 12 }] } }, + "update": { "installed": "v1", "available": "v2", "busy": null, "last": "Not updated: x", "ok": false } + })); + assert_eq!(s.phase, "running"); + assert_eq!(s.players[0].name, "Alex"); + assert_eq!(s.players[0].ping, Some(12)); + assert_eq!( + (s.tps, s.mspt, s.max_players), + (Some(20.0), Some(4.2), Some(10)) + ); + assert_eq!(s.update_available.as_deref(), Some("v2")); + assert_eq!(s.update_last, Some(("Not updated: x".into(), false))); + assert!(!Status::stopped().running()); +} + +/// The control API: the token goes with every call, and errors come back as the server words them. +#[test] +fn the_api_sends_the_token() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let server = std::thread::spawn(move || { + let mut seen = Vec::new(); + for reply in [ + r#"{"phase":"running","sample":{"game":{"players":[]}}}"#, + r#"{"error":"the game didn't answer"}"#, + ] { + let (stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut head = String::new(); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + head.push_str(&line); + } + // Read the body too: closing with it unread would reset the connection. + let length = head + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .map(|n| n.trim().parse::().unwrap()) + }) + .unwrap_or(0); + let mut body = vec![0; length]; + std::io::Read::read_exact(&mut reader, &mut body).unwrap(); + seen.push(head); + let code = if reply.contains("error") { + "409 Conflict" + } else { + "200 OK" + }; + let mut stream = stream; + write!( + stream, + "HTTP/1.1 {code}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", + reply.len() + ) + .unwrap(); + } + seen + }); + let dir = scratch("api"); + fs::create_dir_all(dir.join(".horizon")).unwrap(); + fs::write( + dir.join(".horizon/api.json"), + json!({ "address": address, "token": "t0k", "pid": 1 }).to_string(), + ) + .unwrap(); + assert_eq!(status(&dir).phase, "running"); + let api = Api::open(&dir).unwrap(); + assert_eq!( + api.command("list").unwrap_err(), + "the game didn't answer".to_string() + ); + let seen = server.join().unwrap(); + assert!( + seen[0].starts_with("GET /api/v1/status HTTP/1.1"), + "{}", + seen[0] + ); + assert!(seen + .iter() + .all(|h| h.to_ascii_lowercase().contains("authorization: bearer t0k"))); + assert!(seen[1].starts_with("POST /api/v1/command")); + fs::remove_dir_all(&dir).unwrap(); + // Nothing answers: stopped. + assert_eq!(status(Path::new("/nonexistent")).phase, "stopped"); +} diff --git a/launcher/src/servers_page.rs b/launcher/src/servers_page.rs new file mode 100644 index 000000000..625b6ffab --- /dev/null +++ b/launcher/src/servers_page.rs @@ -0,0 +1,3057 @@ +//! The Servers page: create a server in one dialog, then start, stop and watch it, give friends its +//! address, manage who may join, change its settings, back it up and update it, all with buttons. Every +//! action runs `horizon-server` or calls the running server's control API (`horizon_launcher::servers`). +use super::*; +use horizon_launcher::heads; +use horizon_launcher::servers::{ + self, Applied, Backup, Entry, Fix, NewServer, Problem, Status, World, +}; +use serde_json::Value; +use std::collections::{BTreeSet, HashMap}; +use std::path::{Path, PathBuf}; + +/// The servers this launcher started in this session, stopped when it closes unless they run as a +/// service (`stop_on_quit`). +static STARTED_HERE: Mutex> = Mutex::new(Vec::new()); + +/// How often the open server's status and log are read, and the list's. +const POLL_OPEN: Duration = Duration::from_millis(1000); +const POLL_LIST: Duration = Duration::from_secs(3); + +/// Lines of the server's log kept on the page. +const CONSOLE_KEEP: usize = 1000; + +#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)] +pub(super) enum Field { + Name, + Seed, + Players, + Command, + AddPlayer, + Motd, + Port, + Token, + Email, +} + +impl Field { + const ALL: [Field; 9] = [ + Field::Name, + Field::Seed, + Field::Players, + Field::Command, + Field::AddPlayer, + Field::Motd, + Field::Port, + Field::Token, + Field::Email, + ]; +} + +#[derive(Clone, Copy, PartialEq, Debug)] +pub(super) enum Tab { + Overview, + Players, + Settings, + Backups, +} + +const TABS: [(Tab, &str); 4] = [ + (Tab::Overview, "Overview"), + (Tab::Players, "Players"), + (Tab::Settings, "Settings"), + (Tab::Backups, "Backups"), +]; + +const MODES: [(&str, &str); 3] = [ + ("survival", "Survival"), + ("creative", "Creative"), + ("adventure", "Adventure"), +]; + +const DIFFICULTIES: [(&str, &str); 4] = [ + ("peaceful", "Peaceful"), + ("easy", "Easy"), + ("normal", "Normal"), + ("hard", "Hard"), +]; + +/// What the background work reports. +pub(super) enum Event { + Polled { + dir: PathBuf, + status: Box, + logs: Option<(u64, Vec)>, + }, + Statuses(Vec<(PathBuf, Status)>), + Line(String), + Done(Result), + Created(Result), + Details { + dir: PathBuf, + config: Option, + backups: Vec, + service: bool, + }, + Applied(Result), + Pvp(Option), + UpdateCheck(Result), + Failed(String), +} + +/// The Create dialog's answers. +pub(super) struct Create { + new_world: bool, + copy: Option, + worlds: Vec<(String, PathBuf)>, + mode: &'static str, + difficulty: &'static str, + max_players: u32, + friends_only: bool, + check_accounts: bool, + eula: bool, + /// Create was pressed without the EULA ticked. + eula_missing: bool, +} + +pub(super) struct Servers { + list: Vec, + loaded: bool, + pub(super) open: Option, + tab: Tab, + statuses: HashMap, + polling: bool, + polled: Option, + log: VecDeque, + log_next: u64, + log_dir: Option, + console_scroll: Scrollbar, + create_scroll: Scrollbar, + /// The action under way, and what it printed. + busy: Option, + job_log: VecDeque, + problem: Option, + note: Option, + pub(super) create: Option, + creating: bool, + config: Option, + /// Settings waiting for `config set`, and whether one runs. + queued: Vec<(String, String)>, + applying: bool, + /// Settings saved while the server ran that wait for its next start. + restart_needed: BTreeSet, + backups: Vec, + confirm_restore: Option, + service: Option, + update: Option, + /// `update --check` is under way. + checking: bool, + pvp: Option, + texts: HashMap, + focus: HashMap, + focused: Option, + /// The field to put the keyboard in on the next frame. + focus_soon: Option, + /// A suggested value shown selected: the first key typed replaces it. + selected: Option, + /// A field whose value was refused, and why: shown under it until it's edited. + invalid: Option<(Field, &'static str)>, + copied: Option, + faces: HashMap>>, + tx: Sender, + rx: Receiver, +} + +impl Servers { + pub(super) fn new() -> Self { + let (tx, rx) = channel(); + Self { + list: Vec::new(), + loaded: false, + open: None, + tab: Tab::Overview, + statuses: HashMap::new(), + polling: false, + polled: None, + log: VecDeque::new(), + log_next: 0, + log_dir: None, + console_scroll: Scrollbar::default(), + create_scroll: Scrollbar::default(), + busy: None, + job_log: VecDeque::new(), + problem: None, + note: None, + create: None, + creating: false, + config: None, + queued: Vec::new(), + applying: false, + restart_needed: BTreeSet::new(), + backups: Vec::new(), + confirm_restore: None, + service: None, + update: None, + checking: false, + pvp: None, + texts: HashMap::new(), + focus: HashMap::new(), + focused: None, + focus_soon: None, + selected: None, + invalid: None, + copied: None, + faces: HashMap::new(), + tx, + rx, + } + } + + pub(super) fn text(&mut self, f: Field) -> &mut String { + self.texts.entry(f).or_default() + } + + pub(super) fn value(&self, f: Field) -> &str { + self.texts.get(&f).map_or("", String::as_str) + } + + /// Which field has the keyboard, read every frame. + pub(super) fn note_focus(&mut self, window: &mut Window) { + if let Some(h) = self.focus_soon.take().and_then(|f| self.focus.get(&f)) { + window.focus(h); + } + self.focused = Field::ALL + .into_iter() + .find(|f| self.focus.get(f).is_some_and(|h| h.is_focused(window))); + if self.focused.is_some() && self.focused != self.selected { + self.selected = None; + } + } + + fn status(&self) -> Status { + self.open + .as_ref() + .and_then(|d| self.statuses.get(d).cloned()) + .unwrap_or_else(Status::stopped) + } + + /// A setting from server.toml (as `config --json` gave it). + fn setting(&self, section: &str, key: &str) -> Option<&Value> { + self.config + .as_ref() + .map(|c| &c[section][key]) + .filter(|v| !v.is_null()) + } + + /// A setting as shown: what was just asked for, else what server.toml holds. + fn shown(&self, section: &str, key: &str) -> String { + let full = format!("{section}.{key}"); + if let Some((_, v)) = self.queued.iter().rev().find(|(k, _)| *k == full) { + return v.clone(); + } + match self.setting(section, key) { + Some(Value::String(s)) => s.clone(), + None => String::new(), + Some(v) => v.to_string(), + } + } +} + +/// Stops the servers this launcher started, unless they run in the background as a service. +pub(super) fn stop_on_quit() { + for dir in STARTED_HERE.lock().unwrap().drain(..) { + if servers::service_installed(&dir) { + continue; + } + if let Some(api) = servers::Api::open(&dir) { + let _ = api.call("POST", "/api/v1/stop", None); + } + } +} + +/// The player's own name, to let them in on a friends-only server: the Microsoft account that plays, +/// else the name the game made up for them (`horizon-player.txt`). +fn own_name(accounts: &Accounts) -> Option { + accounts.selected().map(|a| a.name.clone()).or_else(|| { + std::fs::read_to_string(backend::game_home().join("horizon-player.txt")) + .ok() + .map(|n| n.trim().to_string()) + .filter(|n| !n.is_empty()) + }) +} + +fn bytes(n: u64) -> String { + match n { + 0..1_000_000 => format!("{} kB", n.div_ceil(1000)), + 1_000_000..1_000_000_000 => format!("{:.1} MB", n as f64 / 1e6), + _ => format!("{:.2} GB", n as f64 / 1e9), + } +} + +/// A backup's date and kind from its name (`2026-10-19_11-28-57-manual.zip`, UTC), for people. +/// What a key did in a one-line field. +#[derive(Debug, PartialEq)] +enum Key { + Enter, + Escape, + /// Command/Ctrl-V: the caller pastes the clipboard's first line. + Paste, + Edited, + /// Not the field's: Tab (focus), arrows, shortcuts. + Pass, +} + +/// Types `key` into `text`. A `selected` suggestion is replaced by what's typed or pasted, and +/// cleared by Backspace. +fn type_key( + text: &mut String, + selected: bool, + key: &str, + key_char: Option<&str>, + command: bool, +) -> Key { + let replace = |text: &mut String| { + if selected { + text.clear(); + } + }; + match key { + "enter" => Key::Enter, + "escape" => Key::Escape, + "v" if command => { + replace(text); + Key::Paste + } + "backspace" => { + if selected { + text.clear(); + } else { + text.pop(); + } + Key::Edited + } + _ if command => Key::Pass, + // Not every platform gives Space a character. + "space" => { + replace(text); + text.push(' '); + Key::Edited + } + _ => match key_char { + Some(ch) if !ch.is_empty() && !ch.chars().any(char::is_control) => { + replace(text); + text.push_str(ch); + Key::Edited + } + _ => Key::Pass, + }, + } +} + +fn backup_label(b: &Backup) -> (String, String) { + let stem = b.name.trim_end_matches(".zip"); + let (when, kind) = match stem.get(..19) { + Some(when) if stem.len() > 20 => (when, &stem[20..]), + _ => return (stem.to_string(), String::new()), + }; + let (date, time) = when.split_once('_').unwrap_or((when, "")); + let label = format!("{date} {} UTC", time.replace('-', ":")); + let kind = match kind { + "auto" => "Automatic".to_string(), + "manual" => "Made by hand".to_string(), + "before-update" => "Before an update".to_string(), + // horizon-server writes the tag with dashes (before-v2026-10-19-10). + k if k.starts_with("before-v") + && k[8..].chars().all(|c| c.is_ascii_digit() || c == '-') => + { + format!("Before updating to {}", k[7..].replace('-', ".")) + } + k if k.starts_with("before-") => format!("Before updating to {}", &k[7..]), + k => k.to_string(), + }; + (label, kind) +} + +fn uptime(secs: u64) -> String { + match secs { + 0..60 => format!("{secs} s"), + 60..3600 => format!("{} min", secs / 60), + 3600..86_400 => format!("{} h {:02} min", secs / 3600, secs / 60 % 60), + _ => format!("{} d {} h", secs / 86_400, secs / 3600 % 24), + } +} + +/// Keeps a field's text to 256 characters. +fn clip(text: &mut String) { + if let Some((at, _)) = text.char_indices().nth(256) { + text.truncate(at); + } +} + +impl Launcher { + // ----- Background work ------------------------------------------------------------------ + + /// Runs `job` on a thread with the page busy; its lines and result arrive as events. + fn server_job( + &mut self, + label: impl Into, + job: impl FnOnce(&dyn Fn(String)) -> Result + Send + 'static, + ) { + if self.servers.busy.is_some() { + return; + } + self.servers.busy = Some(label.into()); + self.servers.job_log.clear(); + self.servers.problem = None; + self.servers.note = None; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |l: String| { + let _ = lines.send(Event::Line(l)); + }; + let _ = tx.send(Event::Done(job(&log))); + }); + } + + /// `horizon-server ` on the open server, as a job. + fn server_command(&mut self, label: &str, args: Vec) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + self.server_job(label.to_string(), move |log| { + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + servers::run_streamed(&dir, &args, log).map(|_| String::new()) + }); + } + + /// Reads the open server's settings, backups and service state again. + fn load_details(&self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let config = servers::config(&dir); + let backups = servers::backups(&dir).unwrap_or_default(); + let service = servers::service_installed(&dir); + let _ = tx.send(Event::Details { + dir, + config, + backups, + service, + }); + }); + } + + fn open_server(&mut self, dir: PathBuf) { + if self.servers.open.as_ref() == Some(&dir) { + return; + } + let s = &mut self.servers; + s.open = Some(dir); + s.tab = Tab::Overview; + s.config = None; + s.backups.clear(); + s.service = None; + s.update = None; + s.pvp = None; + s.problem = None; + s.note = None; + s.confirm_restore = None; + s.restart_needed.clear(); + s.texts.remove(&Field::Motd); + s.texts.remove(&Field::Port); + s.invalid = None; + s.polled = None; + self.load_details(); + } + + /// Called with the launcher's other work: what the background sent, and the next status poll. + pub(super) fn servers_tick(&mut self) -> bool { + let overview = self.page == Page::Servers + && self.servers.open.is_some() + && self.servers.tab == Tab::Overview; + let mut changed = self.internet_tick(overview); + while let Ok(event) = self.servers.rx.try_recv() { + changed = true; + self.servers_event(event); + } + if self.page != Page::Servers || self.servers.polling || !self.servers.loaded { + return changed; + } + let every = if self.servers.open.is_some() { + POLL_OPEN + } else { + POLL_LIST + }; + if self.servers.polled.is_some_and(|at| at.elapsed() < every) { + return changed; + } + self.servers.polled = Some(Instant::now()); + self.servers.polling = true; + let tx = self.servers.tx.clone(); + match self.servers.open.clone() { + Some(dir) => { + let since = if self.servers.log_dir.as_ref() == Some(&dir) { + self.servers.log_next + } else { + 0 + }; + std::thread::spawn(move || { + let api = servers::Api::open(&dir); + let status = api + .as_ref() + .and_then(|a| a.status()) + .unwrap_or_else(Status::stopped); + let logs = api.and_then(|a| a.logs(since)); + let _ = tx.send(Event::Polled { + dir, + status: Box::new(status), + logs, + }); + }); + } + None => { + let dirs: Vec = self.servers.list.iter().map(|e| e.dir.clone()).collect(); + std::thread::spawn(move || { + let all = dirs + .into_iter() + .map(|d| { + let s = servers::status(&d); + (d, s) + }) + .collect(); + let _ = tx.send(Event::Statuses(all)); + }); + } + } + changed + } + + fn servers_event(&mut self, event: Event) { + let s = &mut self.servers; + match event { + Event::Polled { dir, status, logs } => { + s.polling = false; + let was = s.statuses.get(&dir).map(|st| st.phase.clone()); + if was.as_deref() != Some("running") && status.phase == "running" { + // A fresh start took every saved setting. + s.restart_needed.clear(); + s.pvp = None; + } + if let Some((next, lines)) = logs { + if s.log_dir.as_ref() != Some(&dir) { + s.log.clear(); + s.log_dir = Some(dir.clone()); + } + if !lines.is_empty() { + s.log.extend(lines); + while s.log.len() > CONSOLE_KEEP { + s.log.pop_front(); + } + s.console_scroll.handle.scroll_to_bottom(); + } + s.log_next = next; + } + let read_pvp = status.phase == "running" && s.pvp.is_none(); + s.statuses.insert(dir, *status); + if read_pvp { + self.read_pvp(); + } + } + Event::Statuses(all) => { + s.polling = false; + s.statuses.extend(all); + } + Event::Line(line) => { + s.job_log.push_back(line); + while s.job_log.len() > 6 { + s.job_log.pop_front(); + } + } + Event::Done(result) => { + s.busy = None; + s.polled = None; + match result { + Ok(note) if !note.is_empty() => s.note = Some(note), + Ok(_) => {} + Err(p) => s.problem = Some(p), + } + self.load_details(); + } + Event::Created(result) => { + s.creating = false; + match result { + Ok(entry) => { + s.create = None; + s.list = servers::list(); + self.open_server(entry.dir.clone()); + self.servers.note = Some(format!( + "{} is ready. Press Start, then give your friends the address below.", + entry.name + )); + } + Err(p) => s.problem = Some(p), + } + } + Event::Details { + dir, + config, + backups, + service, + } => { + if s.open.as_ref() == Some(&dir) { + s.config = config; + s.backups = backups; + s.service = Some(service); + } + } + Event::Applied(result) => { + s.applying = false; + match result { + Ok(applied) if applied.running => s.restart_needed.extend(applied.restart), + Ok(_) => {} + Err(p) => s.problem = Some(p), + } + if s.queued.is_empty() { + self.load_details(); + } else { + self.apply_settings(); + } + } + Event::Pvp(on) => s.pvp = on, + Event::UpdateCheck(result) => { + s.checking = false; + match result { + Ok(v) => s.update = Some(v), + Err(p) => s.problem = Some(p), + } + } + Event::Failed(e) => s.problem = Some(Problem::plain(e)), + } + } + + /// The `pvp` game rule, asked of the running game (it's a rule of the world, not a setting). + fn read_pvp(&self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let on = servers::Api::open(&dir) + .and_then(|a| a.command("gamerule pvp").ok()) + .and_then(|out| { + let text = out.join(" "); + let text = text.trim_end(); + if text.ends_with("true") { + Some(true) + } else if text.ends_with("false") { + Some(false) + } else { + None + } + }); + let _ = tx.send(Event::Pvp(on)); + }); + } + + /// Queues a setting for `horizon-server config set`; they go one batch at a time. + fn set_setting(&mut self, key: &str, value: String) { + self.servers.queued.retain(|(k, _)| k != key); + self.servers.queued.push((key.to_string(), value)); + self.servers.note = None; + if !self.servers.applying { + self.apply_settings(); + } + } + + fn apply_settings(&mut self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let batch = std::mem::take(&mut self.servers.queued); + if batch.is_empty() { + return; + } + self.servers.applying = true; + // Shown as asked until the file is read back. + if let Some(config) = &mut self.servers.config { + for (key, value) in &batch { + if let Some((section, field)) = key.split_once('.') { + let new = match &config[section][field] { + Value::Bool(_) => Value::Bool(value == "true"), + Value::Number(_) => value.parse::().map_or(Value::Null, Value::from), + _ => Value::String(value.clone()), + }; + config[section][field] = new; + } + } + } + let tx = self.servers.tx.clone(); + std::thread::spawn(move || { + let pairs: Vec<(&str, String)> = + batch.iter().map(|(k, v)| (k.as_str(), v.clone())).collect(); + let _ = tx.send(Event::Applied(servers::set_config(&dir, &pairs))); + }); + } + + /// A command for the running game, through the control API; its answer shows in the console. + fn api_command(&mut self, line: String) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + let tx = self.servers.tx.clone(); + self.servers.log.push_back(format!("> {line}")); + self.servers.console_scroll.handle.scroll_to_bottom(); + std::thread::spawn(move || { + let result = servers::Api::open(&dir) + .ok_or_else(|| "The server isn't running.".to_string()) + .and_then(|a| a.command(&line)); + if let Err(e) = result { + let _ = tx.send(Event::Failed(e)); + } + }); + } + + fn start_server(&mut self) { + let Some(dir) = self.servers.open.clone() else { + return; + }; + STARTED_HERE.lock().unwrap().push(dir.clone()); + self.servers.restart_needed.clear(); + self.server_job("Starting", move |log| { + log("A new world takes a minute the first time".into()); + servers::run_streamed(&dir, &["start"], log).map(|_| String::new()) + }); + } + + fn fix(&mut self, fix: Fix, cx: &mut Context) { + self.servers.problem = None; + match fix { + Fix::UsePort(port) => { + self.set_setting("server.port", port.to_string()); + self.servers.texts.remove(&Field::Port); + self.servers.note = Some(format!( + "The server now uses port {port}. Press Start again." + )); + } + Fix::Prepare => match self.selected().cloned() { + Some(tag) if backend::is_prepared(&tag) => { + self.server_job("Copying the game files", move |log| { + log(format!("Copying the game files prepared for Horizon {tag}")); + servers::set_up(&tag) + .map(|_| "The game files are ready. Press Start again.".to_string()) + .map_err(Problem::plain) + }); + } + _ => { + self.servers.create = None; + self.go(Page::Play); + if !self.preparing { + self.prepare(); + } + } + }, + Fix::AgreeEula => { + if let Some(c) = &mut self.servers.create { + c.eula = true; + c.eula_missing = false; + } else if let Some(dir) = &self.servers.open { + if let Err(e) = backend::agree_eula(dir) { + self.servers.problem = Some(Problem::plain(e)); + } + } + } + Fix::ShowLog => { + self.servers.tab = Tab::Overview; + if let Some(dir) = &self.servers.open { + cx.open_with_system(&dir.join("logs")); + } + } + } + } + + // ----- Creating ------------------------------------------------------------------------- + + fn open_create(&mut self, cx: &mut Context) { + self.focus_handle(Field::Name, cx); + self.servers.focus_soon = Some(Field::Name); + let worlds = servers::player_worlds(); + let name = if self.servers.list.is_empty() { + "My server".to_string() + } else { + format!("Server {}", self.servers.list.len() + 1) + }; + *self.servers.text(Field::Name) = name; + self.servers.selected = Some(Field::Name); + self.servers.text(Field::Seed).clear(); + *self.servers.text(Field::Players) = own_name(&self.accounts).unwrap_or_default(); + self.servers.problem = None; + self.servers.create_scroll = Scrollbar::default(); + self.servers.create = Some(Create { + new_world: true, + copy: worlds.first().map(|w| w.1.clone()), + worlds, + mode: "survival", + difficulty: "normal", + max_players: 10, + friends_only: true, + check_accounts: false, + eula: false, + eula_missing: false, + }); + } + + fn create_server(&mut self) { + if self.servers.creating { + return; + } + let Some(c) = &mut self.servers.create else { + return; + }; + if !c.eula { + c.eula_missing = true; + return; + } + let Some(c) = self.servers.create.as_ref() else { + return; + }; + let world = match (&c.copy, c.new_world) { + (Some(dir), false) => World::Copy(dir.clone()), + _ => World::New { + seed: self.servers.value(Field::Seed).to_string(), + }, + }; + let players: Vec = self + .servers + .value(Field::Players) + .split([',', ' ']) + .filter(|p| !p.is_empty()) + .map(str::to_string) + .collect(); + let name = self.servers.value(Field::Name).trim().to_string(); + let spec = NewServer { + name: if name.is_empty() { + "My server".into() + } else { + name + }, + world, + game_mode: c.mode.into(), + difficulty: c.difficulty.into(), + max_players: c.max_players, + friends_only: c.friends_only, + check_accounts: c.check_accounts, + players, + eula: c.eula, + }; + let tag = self.selected().cloned(); + let tx = self.servers.tx.clone(); + self.servers.creating = true; + self.servers.problem = None; + self.servers.job_log.clear(); + std::thread::spawn(move || { + let lines = tx.clone(); + let log = move |l: String| { + let _ = lines.send(Event::Line(l)); + }; + let _ = tx.send(Event::Created(servers::create(&spec, tag.as_deref(), &log))); + }); + } + + // ----- Building blocks ------------------------------------------------------------------ + + fn focus_handle(&mut self, f: Field, cx: &mut Context) -> FocusHandle { + self.servers + .focus + .entry(f) + .or_insert_with(|| cx.focus_handle().tab_index(0).tab_stop(true)) + .clone() + } + + /// A one-line text field: typing, paste, Backspace, Enter to confirm, Escape, Tab to the next. + pub(super) fn field( + &mut self, + f: Field, + placeholder: &'static str, + width: f32, + cx: &mut Context, + ) -> Stateful
{ + let t = self.theme; + let handle = self.focus_handle(f, cx); + let focused = self.servers.focused == Some(f); + let selected = focused && self.servers.selected == Some(f); + let invalid = self.servers.invalid.is_some_and(|(g, _)| g == f); + let value = self.servers.value(f).to_string(); + let shown: String = { + let chars: Vec = value.chars().collect(); + if f == Field::Token { + "•".repeat(chars.len().min(40)) + } else { + chars[chars.len().saturating_sub(60)..].iter().collect() + } + }; + div() + .id(SharedString::from(format!("field-{f:?}"))) + .track_focus(&handle) + .flex() + .items_center() + .w(px(width)) + .h(px(theme::FIELD)) + .px(px(12.)) + .overflow_hidden() + .rounded(px(theme::RADIUS)) + .border_1() + .border_color(if invalid { + t.danger + } else if focused { + t.accent + } else { + t.rule + }) + .bg(t.surface) + .text_size(px(theme::UI.px)) + .cursor_text() + .child(if value.is_empty() && !focused { + div().text_color(t.muted).child(placeholder) + } else { + div() + .text_color(t.ink) + .when(selected, |d| { + d.rounded(px(2.)).bg(t.accent.opacity(theme::SELECTION)) + }) + .child(shown) + }) + .when(focused, |d| { + d.child(div().flex_none().w(px(1.)).h(px(16.)).bg(t.ink)) + }) + .on_click(cx.listener(move |this, ev: &ClickEvent, window, cx| { + // A click puts the caret in: the suggestion is no longer selected. + if matches!(ev, ClickEvent::Mouse(_)) { + this.servers.selected = None; + } + if let Some(h) = this.servers.focus.get(&f) { + window.focus(h); + } + cx.notify(); + })) + .on_key_down(cx.listener(move |this, ev: &KeyDownEvent, window, cx| { + let k = &ev.keystroke; + let command = k.modifiers.control || k.modifiers.platform; + if k.key != "enter" && this.servers.invalid.is_some_and(|(g, _)| g == f) { + this.servers.invalid = None; + } + let selected = this.servers.selected.take() == Some(f); + let typed = type_key( + this.servers.text(f), + selected, + &k.key, + k.key_char.as_deref(), + command, + ); + match typed { + Key::Enter => this.field_enter(f), + Key::Escape => { + if this.servers.create.is_some() && !this.servers.creating { + this.servers.create = None; + } + window.blur(); + } + Key::Paste => { + if let Some(text) = cx.read_from_clipboard().and_then(|c| c.text()) { + let line = text.lines().next().unwrap_or_default().trim().to_string(); + this.servers.text(f).push_str(&line); + } + } + Key::Edited => {} + // Tab and the rest go on to the window: Tab moves the focus. + Key::Pass => return, + } + clip(this.servers.text(f)); + cx.stop_propagation(); + cx.notify(); + })) + } + + /// Escape closes the Create dialog. Whether it did. + pub(super) fn servers_escape(&mut self) -> bool { + if self.page != Page::Servers || self.servers.create.is_none() || self.servers.creating { + return false; + } + self.servers.create = None; + self.servers.problem = None; + true + } + + fn field_enter(&mut self, f: Field) { + match f { + Field::Name | Field::Seed | Field::Players => self.create_server(), + Field::Command => { + let line = std::mem::take(self.servers.text(Field::Command)); + let line = line.trim().trim_start_matches('/').to_string(); + if !line.is_empty() { + self.api_command(line); + } + } + Field::AddPlayer => self.add_player(), + Field::Motd => { + let motd = self.servers.value(Field::Motd).trim().to_string(); + if motd.is_empty() { + self.servers.problem = + Some(Problem::plain("Type the line players see under the name.")); + } else { + self.set_setting("server.motd", motd); + } + } + Field::Port => self.save_port(), + Field::Token => self.save_token(), + Field::Email => self.invite_friend(), + } + } + + fn save_port(&mut self) { + match self.servers.value(Field::Port).trim().parse::() { + Ok(port) if port >= 1024 => self.set_setting("server.port", port.to_string()), + _ => { + self.servers.invalid = Some(( + Field::Port, + "Use a number from 1024 to 65535 (25565 is Minecraft's own).", + )) + } + } + } + + fn add_player(&mut self) { + let name = self.servers.value(Field::AddPlayer).trim().to_string(); + let valid = (3..=16).contains(&name.len()) + && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'); + if !valid { + self.servers.invalid = Some(( + Field::AddPlayer, + "A Minecraft name has 3 to 16 letters, digits or underscores.", + )); + return; + } + self.servers.text(Field::AddPlayer).clear(); + self.server_command( + &format!("Letting {name} in"), + vec!["whitelist".into(), "add".into(), name], + ); + } + + /// A player's face, from the default skin their UUID picks (the server knows no other). + fn head(&mut self, uuid: &str, size: f32) -> Div { + let resources = servers::game_files(&servers::runtime_root(), "26.3"); + let face = self + .servers + .faces + .entry(uuid.to_string()) + .or_insert_with(|| heads::default_face(&resources, uuid)) + .clone(); + let cell = size / 8.; + let mut d = div() + .flex_none() + .flex() + .flex_col() + .size(px(size)) + .rounded(px(3.)) + .overflow_hidden() + .bg(self.theme.plate); + if let Some(pixels) = face { + for row in pixels.chunks(8) { + d = d.child(div().flex().children(row.iter().map(|p| { + div().size(px(cell)).bg(Hsla::from(gpui::Rgba { + r: p[0] as f32 / 255., + g: p[1] as f32 / 255., + b: p[2] as f32 / 255., + a: 1., + })) + }))); + } + } + d + } + + /// A row's small button. + fn small( + &self, + id: impl Into, + label: &'static str, + enabled: bool, + cx: &mut Context, + action: impl Fn(&mut Self) + 'static, + ) -> Stateful
{ + let b = button(id, label, Kind::Ghost, &self.theme) + .h(px(28.)) + .px(px(10.)) + .text_size(px(theme::CAPTION.px)); + if enabled { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + action(this); + cx.notify(); + })) + } else { + disabled(b) + } + } + + // ----- The page ------------------------------------------------------------------------- + + pub(super) fn servers_page(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + if !self.servers.loaded { + self.servers.list = servers::list(); + self.servers.loaded = true; + if self.servers.open.is_none() && self.servers.list.len() == 1 { + let dir = self.servers.list[0].dir.clone(); + self.open_server(dir); + } + } + if let Some(dir) = self.servers.open.clone() { + if self.servers.list.iter().any(|e| e.dir == dir) { + return self.server_dashboard(&dir, cx); + } + self.servers.open = None; + } + let header = page_header( + "Servers", + "Host a world for your friends on this computer. Create one, press Start, and give them \ + the address.", + &t, + ); + let actions = div() + .flex() + .items_center() + .gap(px(8.)) + .child( + button("server-create", "Create a server", Kind::Primary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.open_create(cx); + cx.notify(); + }), + ), + ) + .child({ + let b = button("server-add", "Add a server folder…", Kind::Ghost, &t); + if self.servers.creating { + disabled(b) + } else { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_server_folder(cx); + cx.notify(); + })) + } + }); + let mut page = div() + .flex() + .flex_col() + .gap(px(32.)) + .child(header) + .child(actions); + if let Some(p) = self + .servers + .problem + .clone() + .filter(|_| self.servers.create.is_none()) + { + page = page.child(self.problem_notice(p, cx)); + } + if self.servers.list.is_empty() { + return page.child(centered( + "No server yet. Create one: it takes a few seconds, and with the defaults (tick \ + the EULA, press Create) you get a friends-only survival world.", + &t, + )); + } + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, e) in self.servers.list.clone().into_iter().enumerate() { + let status = self + .servers + .statuses + .get(&e.dir) + .cloned() + .unwrap_or_else(Status::stopped); + let detail = if status.running() { + format!( + "{} · {} of {} players", + phase_label(&status), + status.players.len(), + status.max_players.unwrap_or(0) + ) + } else { + format!("{} · {}", phase_label(&status), short(&e.dir)) + }; + let dir = e.dir.clone(); + list = list.child(index_row( + i + 1, + e.name.clone(), + Some(detail.into_any_element()), + Some( + button( + SharedString::from(format!("server-open-{i}")), + "Open", + Kind::Secondary, + &t, + ) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.open_server(dir.clone()); + cx.notify(); + })) + .into_any_element(), + ), + &t, + )); + } + page.child(list) + } + + fn add_server_folder(&mut self, cx: &mut Context) { + let paths = cx.prompt_for_paths(PathPromptOptions { + files: false, + directories: true, + multiple: false, + prompt: Some("Add".into()), + }); + cx.spawn(async move |this, cx| { + if let Ok(Ok(Some(mut paths))) = paths.await { + if let Some(dir) = paths.pop() { + let _ = this.update(cx, |this, cx| { + this.add_existing(dir); + cx.notify(); + }); + } + } + }) + .detach(); + } + + /// A folder with a server.toml joins the list; a vanilla server folder is set up first (its + /// server.properties becomes server.toml; its world, lists and EULA stay). + fn add_existing(&mut self, dir: PathBuf) { + let name = dir + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "Server".into()); + let tag = self.selected().cloned(); + let tx = self.servers.tx.clone(); + self.servers.creating = true; + self.servers.problem = None; + std::thread::spawn(move || { + let result = (|| { + if servers::program().is_none() { + let tag = + tag.ok_or_else(|| Problem::plain("Install a Horizon version first."))?; + servers::set_up(&tag).map_err(Problem::plain)?; + } + if !dir.join("server.toml").is_file() { + servers::run(&dir, &["init", "--yes"])?; + } + let entry = Entry { name, dir }; + servers::add(entry.clone()).map_err(Problem::plain)?; + Ok(entry) + })(); + let _ = tx.send(Event::Created(result)); + }); + } + + fn problem_notice(&self, p: Problem, cx: &mut Context) -> Div { + let t = self.theme; + let mut n = notice(p.message.clone(), &t).items_center(); + if let Some(fix) = p.fix { + let label = match &fix { + Fix::UsePort(port) => format!("Use port {port}"), + Fix::Prepare => "Prepare the game files".into(), + Fix::AgreeEula => "I agree to the EULA".into(), + Fix::ShowLog => "Open the logs".into(), + }; + n = n.child( + button("problem-fix", label, Kind::Secondary, &t) + .bg(t.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.fix(fix.clone(), cx); + cx.notify(); + })), + ); + } + n.child( + button("problem-dismiss", "Dismiss", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.servers.problem = None; + cx.notify(); + }, + )), + ) + } + + fn server_dashboard(&mut self, dir: &Path, cx: &mut Context) -> Div { + let t = self.theme; + let status = self.servers.status(); + let name = self + .servers + .list + .iter() + .find(|e| e.dir == dir) + .map(|e| e.name.clone()) + .unwrap_or_default(); + let running = status.running(); + let busy = self.servers.busy.clone(); + let mut top = div().flex().flex_col().gap(px(10.)); + if self.servers.list.len() > 1 || self.servers.create.is_none() { + top = top.child( + div().flex().child( + caps("← All servers") + .id("servers-back") + .text_color(t.muted) + .cursor_pointer() + .hover(move |s| s.text_color(t.ink)) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.open = None; + this.servers.polled = None; + this.servers.problem = None; + this.servers.note = None; + cx.notify(); + })), + ), + ); + } + let dot = match status.phase.as_str() { + "running" if status.crashes > 0 => t.accent, + "running" => t.success, + "stopped" => t.muted, + _ => t.accent, + }; + top = top + .child( + div() + .flex() + .items_center() + .gap(px(10.)) + .child(div().size(px(8.)).rounded_full().bg(dot)) + .child(caps(phase_label(&status)).text_color(t.muted)) + .when_some(status.uptime.filter(|_| running), |d, up| { + d.child(caps(format!("· up {}", uptime(up))).text_color(t.muted)) + }), + ) + .child(text(theme::DISPLAY).text_color(t.ink).child(name)); + if status.crashes > 0 { + top = top.child(text(theme::CAPTION).text_color(t.muted).child(format!( + "The game crashed {} time{} and was restarted by itself{}.", + status.crashes, + if status.crashes == 1 { "" } else { "s" }, + status + .last_crash + .as_ref() + .map(|c| format!(" (last: {c})")) + .unwrap_or_default() + ))); + } + + // The big buttons. + let big = |b: Stateful
| { + b.min_w(px(132.)) + .h(px(theme::CONTROL_LARGE)) + .px(px(28.)) + .text_size(px(theme::UI.px)) + }; + let idle = busy.is_none(); + let start = big(button( + "server-start", + if running { "Stop" } else { "Start" }, + if running { + Kind::Secondary + } else { + Kind::Primary + }, + &t, + )); + let start = if !idle { + disabled(start) + } else if running { + start.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.server_command("Stopping", vec!["stop".into()]); + cx.notify(); + })) + } else { + start.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.start_server(); + cx.notify(); + })) + }; + let restart = big(button("server-restart", "Restart", Kind::Secondary, &t)); + let restart = if idle && running { + restart.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.restart_needed.clear(); + this.server_command("Restarting", vec!["restart".into()]); + cx.notify(); + })) + } else { + disabled(restart) + }; + let panel = button("server-panel", "Open the web panel", Kind::Ghost, &t); + let panel = if running { + let d = dir.to_path_buf(); + panel.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + match servers::Api::open(&d).map(|a| a.panel_link()) { + Some(Ok(url)) => cx.open_url(&url), + Some(Err(e)) => this.servers.problem = Some(Problem::plain(e)), + None => {} + } + cx.notify(); + })) + } else { + disabled(panel) + }; + let folder = dir.to_path_buf(); + let buttons = div() + .flex() + .flex_wrap() + .items_center() + .gap(px(8.)) + .child(start) + .child(restart) + .child(panel) + .child( + button("server-folder", "Open the folder", Kind::Ghost, &t) + .on_click(move |_, _, cx| cx.open_with_system(&folder)), + ); + + let mut page = div() + .flex() + .flex_col() + .gap(px(24.)) + .child(top) + .child(buttons); + if let Some(label) = &busy { + let last = self.servers.job_log.back().cloned().unwrap_or_default(); + page = page.child( + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(progress_bar(None, &t)) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .truncate() + .child(format!("{label}… {last}")), + ), + ); + } + if let Some(p) = self.servers.problem.clone() { + page = page.child(self.problem_notice(p, cx)); + } + if let Some(n) = self.servers.note.clone() { + page = page.child( + plate(&t) + .flex() + .items_center() + .gap(px(12.)) + .p(px(16.)) + .child(div().flex_none().size(px(6.)).rounded_full().bg(t.success)) + .child( + div() + .flex_1() + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(n), + ), + ); + } + if running && !self.servers.restart_needed.is_empty() { + let names: Vec<&str> = self + .servers + .restart_needed + .iter() + .map(|k| setting_name(k)) + .collect(); + page = page.child( + plate(&t) + .flex() + .items_center() + .gap(px(12.)) + .p(px(16.)) + .child(div().flex_none().size(px(6.)).rounded_full().bg(t.accent)) + .child( + div() + .flex_1() + .text_size(px(theme::UI.px)) + .text_color(t.ink) + .child(format!("Saved. Restart to apply: {}.", names.join(", "))), + ) + .child({ + let b = + button("restart-apply", "Restart now", Kind::Secondary, &t).bg(t.plate); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.restart_needed.clear(); + this.server_command("Restarting", vec!["restart".into()]); + cx.notify(); + })) + } else { + disabled(b) + } + }), + ); + } + page = page.child(self.stats(&status)); + let this = cx.entity().downgrade(); + page = page.child(div().flex().child(segments( + "server-tabs", + &TABS, + self.servers.tab, + &t, + move |tab, _, cx| { + let _ = this.update(cx, |this, cx| { + this.servers.tab = tab; + this.servers.confirm_restore = None; + cx.notify(); + }); + }, + ))); + let body = match self.servers.tab { + Tab::Overview => self.overview_tab(&status, cx), + Tab::Players => self.players_tab(dir, &status, cx), + Tab::Settings => self.settings_tab(&status, cx), + Tab::Backups => self.backups_tab(&status, cx), + }; + page.child(body) + } + + fn stats(&self, status: &Status) -> Div { + let t = self.theme; + let tile = |value: String, label: &'static str| { + plate(&t) + .flex() + .flex_col() + .flex_1() + .gap(px(4.)) + .p(px(16.)) + .child(text(theme::TITLE).text_color(t.ink).child(value)) + .child(caps(label).text_color(t.muted)) + }; + let dash = || "–".to_string(); + let on = status.running(); + div() + .flex() + .gap(px(12.)) + .child(tile( + if on { + format!( + "{} / {}", + status.players.len(), + status.max_players.unwrap_or(0) + ) + } else { + dash() + }, + "Players online", + )) + .child(tile( + status + .tps + .filter(|_| on) + .map_or_else(dash, |v| format!("{v:.1}")), + "TPS · 20 is full speed", + )) + .child(tile( + status + .mspt + .filter(|_| on) + .map_or_else(dash, |v| format!("{v:.1} ms")), + "MSPT · tick time", + )) + .child(tile( + status + .ram_bytes + .filter(|_| on) + .map_or_else(dash, |b| format!("{:.2} GB", b as f64 / 1e9)), + "RAM", + )) + } + + fn overview_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let port = self + .servers + .setting("server", "port") + .and_then(Value::as_u64) + .unwrap_or(25565); + let lan = servers::lan_address(); + let address = match lan { + Some(ip) if port == 25565 => ip.to_string(), + Some(ip) => format!("{ip}:{port}"), + None => format!("localhost:{port}"), + }; + let copied = self + .servers + .copied + .is_some_and(|at| at.elapsed() < Duration::from_secs(2)); + let copy_text = address.clone(); + let address_plate = plate(&t) + .flex() + .flex_col() + .gap(px(10.)) + .p(px(20.)) + .child(caps("Address on this network").text_color(t.muted)) + .child( + div() + .flex() + .items_center() + .gap(px(12.)) + .child( + text(theme::TITLE) + .font_family(theme::MONO) + .text_color(t.ink) + .child(address), + ) + .child( + button( + "address-copy", + if copied { "Copied" } else { "Copy" }, + Kind::Secondary, + &t, + ) + .bg(t.plate) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.write_to_clipboard(gpui::ClipboardItem::new_string( + copy_text.clone(), + )); + this.servers.copied = Some(Instant::now()); + cx.notify(); + })), + ), + ) + .child(text(theme::CAPTION).text_color(t.ink_soft).child( + "Friends on the same Wi-Fi: Multiplayer, Add Server, then paste this address.", + )) + .child(text(theme::CAPTION).text_color(t.muted).child(format!( + "Friends elsewhere can't reach it as it is: use Tailscale (free, nothing to change \ + on your router, only people you invite), or forward TCP port {port} on your router \ + to this computer." + ))); + let mut tab = div().flex().flex_col().gap(px(20.)).child(address_plate); + if !status.players.is_empty() { + let mut row = div().flex().flex_wrap().gap(px(16.)); + for p in status.players.clone() { + row = row.child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.head(&p.uuid, 20.)) + .child(text(theme::UI).text_color(t.ink).child(p.name.clone())), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(caps("Online now").text_color(t.muted)) + .child(row), + ); + } + tab.child(self.internet_panel(port as u16, cx)) + .child(self.server_console(status.running(), cx)) + } + + fn server_console(&mut self, running: bool, cx: &mut Context) -> Div { + let t = self.theme; + let lines: Vec
= self + .servers + .log + .iter() + .map(|l| { + div() + .when(l.starts_with("> "), |d| d.text_color(t.accent)) + .child(l.clone()) + }) + .collect(); + let empty = self.servers.log.is_empty(); + let log = div() + .id("server-console") + .h(px(240.)) + .px(px(20.)) + .py(px(12.)) + .overflow_y_scroll() + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .line_height(px(19.)) + .text_color(t.ink_soft) + .when(empty, |d| { + d.child(div().text_color(t.muted).child(if running { + "Waiting for the server's log…" + } else { + "The server's log shows here while it runs." + })) + }) + .children(lines); + let log = self.servers.console_scroll.wrap(log, &t); + let input = if running { + self.field( + Field::Command, + "Type a command: say Hello, time set day, gamemode creative Alex…", + 520., + cx, + ) + .flex_1() + .border_0() + .bg(t.plate_soft) + .font_family(theme::MONO) + .text_size(px(theme::CAPTION.px)) + .into_any_element() + } else { + div() + .px(px(12.)) + .h(px(theme::FIELD)) + .flex() + .items_center() + .text_size(px(theme::CAPTION.px)) + .text_color(t.muted) + .child("Start the server to type commands") + .into_any_element() + }; + plate(&t) + .flex() + .flex_col() + .overflow_hidden() + .child( + div() + .flex() + .items_center() + .h(px(40.)) + .px(px(20.)) + .border_b_1() + .border_color(t.rule) + .child(caps("Console").text_color(t.muted)), + ) + .child(log) + .child( + div() + .flex() + .items_center() + .px(px(8.)) + .py(px(4.)) + .border_t_1() + .border_color(t.rule) + .child(div().text_color(t.accent).ml(px(12.)).child("›")) + .child(input), + ) + } + + fn players_tab(&mut self, dir: &Path, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let running = status.running(); + let idle = self.servers.busy.is_none(); + let ops = servers::names(dir, "ops.json"); + let whitelist = servers::entries(dir, "whitelist.json"); + let banned = servers::names(dir, "banned-players.json"); + let is_op = |n: &str| ops.iter().any(|o| o.eq_ignore_ascii_case(n)); + let mut tab = div().flex().flex_col().gap(px(28.)); + + // Online now. + let mut online = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, p) in status.players.clone().into_iter().enumerate() { + let op = is_op(&p.name); + let (n1, n2, n3) = (p.name.clone(), p.name.clone(), p.name.clone()); + let actions = div() + .flex() + .gap(px(2.)) + .child(self.small( + SharedString::from(format!("online-op-{i}")), + if op { + "Remove operator" + } else { + "Make operator" + }, + idle, + cx, + move |this| { + let verb = if op { "deop" } else { "op" }; + this.server_command("Changing operators", vec![verb.into(), n1.clone()]); + }, + )) + .child(self.small( + SharedString::from(format!("online-kick-{i}")), + "Kick", + running, + cx, + move |this| this.api_command(format!("kick {n2}")), + )) + .child(self.small( + SharedString::from(format!("online-ban-{i}")), + "Ban", + running, + cx, + move |this| this.api_command(format!("ban {n3}")), + )); + let ping = p.ping.map(|ms| format!("{ms} ms ping")); + let about = match (op, ping) { + (true, Some(ping)) => Some(format!("Operator · {ping}")), + (true, None) => Some("Operator".to_string()), + (false, ping) => ping, + }; + online = online.child( + div() + .flex() + .items_center() + .gap(px(14.)) + .min_h(px(theme::ROW)) + .py(px(8.)) + .border_b_1() + .border_color(t.rule) + .child(self.head(&p.uuid, 24.)) + .child( + div() + .flex() + .flex_col() + .flex_1() + .child(text(theme::UI).text_color(t.ink).child(p.name.clone())) + .children( + about.map(|a| text(theme::CAPTION).text_color(t.muted).child(a)), + ), + ) + .child(actions), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child( + text(theme::HEADING) + .text_color(t.ink) + .child(format!("Online now ({})", status.players.len())), + ) + .child(if status.players.is_empty() { + text(theme::UI) + .text_color(t.muted) + .child(if running { + "Nobody is playing right now." + } else { + "The server is stopped." + }) + .into_any_element() + } else { + online.into_any_element() + }), + ); + + // Who may join. + let friends_only = self + .servers + .setting("server", "whitelist") + .and_then(Value::as_bool) + .unwrap_or(true); + let toggle = switch("friends-only", friends_only, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.set_setting("server.whitelist", (!friends_only).to_string()); + cx.notify(); + }, + )); + let add = div() + .flex() + .items_center() + .gap(px(8.)) + .child(self.field(Field::AddPlayer, "A player's name", 240., cx)) + .child({ + let b = button("player-add", "Let in", Kind::Secondary, &t); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_player(); + cx.notify(); + })) + } else { + disabled(b) + } + }); + let mut people: Vec<(String, String)> = whitelist.clone(); + for op in &ops { + if !people.iter().any(|(n, _)| n.eq_ignore_ascii_case(op)) { + people.push((op.clone(), String::new())); + } + } + let mut allowed = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, (name, uuid)) in people.into_iter().enumerate() { + let op = is_op(&name); + let listed = whitelist.iter().any(|(n, _)| n == &name); + let (n1, n2) = (name.clone(), name.clone()); + let mut actions = div().flex().gap(px(2.)).child(self.small( + SharedString::from(format!("allowed-op-{i}")), + if op { + "Remove operator" + } else { + "Make operator" + }, + idle, + cx, + move |this| { + let verb = if op { "deop" } else { "op" }; + this.server_command("Changing operators", vec![verb.into(), n1.clone()]); + }, + )); + if listed { + actions = actions.child(self.small( + SharedString::from(format!("allowed-remove-{i}")), + "Remove", + idle, + cx, + move |this| { + this.server_command( + "Updating the list", + vec!["whitelist".into(), "remove".into(), n2.clone()], + ); + }, + )); + } + let head = if uuid.is_empty() { + div().size(px(24.)).flex_none() + } else { + self.head(&uuid, 24.) + }; + let about = match (op, listed) { + (true, true) => Some("Operator: can run every command"), + (true, false) => Some("Operator (not on the list: can join anyway)"), + _ => None, + }; + allowed = allowed.child( + div() + .flex() + .items_center() + .gap(px(14.)) + .min_h(px(theme::ROW)) + .py(px(8.)) + .border_b_1() + .border_color(t.rule) + .child(head) + .child( + div() + .flex() + .flex_col() + .flex_1() + .child(text(theme::UI).text_color(t.ink).child(name.clone())) + .when_some(about, |d, a| { + d.child(text(theme::CAPTION).text_color(t.muted).child(a)) + }), + ) + .child(actions), + ); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(14.)) + .child(text(theme::HEADING).text_color(t.ink).child("Who may join")) + .child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(toggle) + .child( + div() + .flex() + .flex_col() + .child(text(theme::UI).text_color(t.ink).child("Friends only")) + .child(text(theme::CAPTION).text_color(t.muted).child( + if friends_only { + "On: only the players below can join." + } else { + "Off: anyone who has the address can join." + }, + )), + ), + ) + .child(add) + .children(self.servers.invalid.and_then(|(f, e)| { + (f == Field::AddPlayer) + .then(|| text(theme::CAPTION).text_color(t.danger).child(e)) + })) + .child(allowed), + ); + + // Banned. + if !banned.is_empty() { + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, name) in banned.into_iter().enumerate() { + let n = name.clone(); + list = list.child(index_row( + i + 1, + name, + None, + Some( + self.small( + SharedString::from(format!("unban-{i}")), + "Unban", + running, + cx, + move |this| this.api_command(format!("pardon {n}")), + ) + .into_any_element(), + ), + &t, + )); + } + tab = tab.child( + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(text(theme::HEADING).text_color(t.ink).child("Banned")) + .when(!running, |d| { + d.child( + text(theme::CAPTION) + .text_color(t.muted) + .child("Start the server to unban someone."), + ) + }) + .child(list), + ); + } + tab + } + + /// A row of the settings form: a name, one line on it, and its control. + fn setting_row(&self, name: &str, about: String, control: AnyElement) -> Div { + self.setting_row_checked(name, about, None, control) + } + + /// A setting row whose text gives way to `error` when the value was refused. + fn setting_row_checked( + &self, + name: &str, + about: String, + error: Option<&'static str>, + control: AnyElement, + ) -> Div { + let t = self.theme; + div() + .flex() + .items_center() + .gap(px(16.)) + .min_h(px(theme::ROW)) + .py(px(12.)) + .border_b_1() + .border_color(t.rule) + .child( + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .gap(px(2.)) + .child(text(theme::UI).text_color(t.ink).child(name.to_string())) + .child(match error { + Some(e) => text(theme::CAPTION).text_color(t.danger).child(e), + None => text(theme::CAPTION).text_color(t.muted).child(about), + }), + ) + .child(control) + } + + /// − value + for a number setting within `range`. + fn stepper( + &self, + key: &'static str, + range: std::ops::RangeInclusive, + cx: &mut Context, + ) -> AnyElement { + let t = self.theme; + let (section, field) = key.split_once('.').unwrap_or_default(); + let value: i64 = self.servers.shown(section, field).parse().unwrap_or(0); + let make = |id: &'static str, label: &'static str, to: i64, cx: &mut Context| { + let b = button( + SharedString::from(format!("{key}-{id}")), + label, + Kind::Secondary, + &t, + ) + .w(px(36.)) + .px(px(0.)); + if range.contains(&to) && to != value { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_setting(key, to.to_string()); + cx.notify(); + })) + } else { + disabled(b) + } + }; + div() + .flex() + .items_center() + .gap(px(8.)) + .child(make("less", "−", value - 1, cx)) + .child( + text(theme::UI) + .w(px(44.)) + .flex() + .justify_center() + .text_color(t.ink) + .child(value.to_string()), + ) + .child(make("more", "+", value + 1, cx)) + .into_any_element() + } + + fn choice( + &self, + id: &'static str, + key: &'static str, + options: &[(&'static str, &'static str)], + cx: &mut Context, + ) -> AnyElement { + let (section, field) = key.split_once('.').unwrap_or_default(); + let current = self.servers.shown(section, field); + let current: &'static str = options + .iter() + .find(|(v, _)| *v == current) + .map_or("", |(v, _)| v); + let this = cx.entity().downgrade(); + segments(id, options, current, &self.theme, move |value, _, cx| { + let _ = this.update(cx, |this, cx| { + this.set_setting(key, value.to_string()); + cx.notify(); + }); + }) + .into_any_element() + } + + fn settings_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let running = status.running(); + if self.servers.config.is_none() { + return div().child(centered( + if self.older_horizon() { + "This server's Horizon is too old to show its settings here. Update it on \ + the Backups tab, then they appear." + } else { + "Reading the settings…" + }, + &t, + )); + } + if self.servers.focused != Some(Field::Motd) + && !self.servers.texts.contains_key(&Field::Motd) + { + *self.servers.text(Field::Motd) = self.servers.shown("server", "motd"); + } + if self.servers.focused != Some(Field::Port) + && !self.servers.texts.contains_key(&Field::Port) + { + *self.servers.text(Field::Port) = self.servers.shown("server", "port"); + } + let save = |id: &'static str, f: Field, cx: &mut Context| { + button(id, "Save", Kind::Secondary, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.field_enter(f); + cx.notify(); + }, + )) + }; + let motd = div() + .flex() + .gap(px(8.)) + .child(self.field(Field::Motd, "A Minecraft Server", 260., cx)) + .child(save("motd-save", Field::Motd, cx)) + .into_any_element(); + let port = div() + .flex() + .gap(px(8.)) + .child(self.field(Field::Port, "25565", 100., cx)) + .child(save("port-save", Field::Port, cx)) + .into_any_element(); + let pvp = match (running, self.servers.pvp) { + (true, Some(on)) => switch("pvp", on, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.servers.pvp = Some(!on); + this.api_command(format!("gamerule pvp {}", !on)); + cx.notify(); + })) + .into_any_element(), + _ => disabled(switch("pvp", true, &t)).into_any_element(), + }; + let accounts = self + .servers + .setting("server", "online_mode") + .and_then(Value::as_bool) + .unwrap_or(false); + let accounts_switch = switch("online-mode", accounts, &t) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_setting("server.online_mode", (!accounts).to_string()); + cx.notify(); + })) + .into_any_element(); + let live = if running { + "Applies at once." + } else { + "Used from the next start." + }; + let later = if running { + "Saved now, used after a restart." + } else { + "Used from the next start." + }; + let form = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(self.setting_row( + "Message in the server list", + format!("What players see under the server's name (the MOTD). {later}"), + motd, + )) + .child(self.setting_row( + "Game mode", + format!("For players who join for the first time. {live}"), + self.choice("set-mode", "world.game_mode", &MODES, cx), + )) + .child(self.setting_row( + "Difficulty", + live.into(), + self.choice("set-difficulty", "world.difficulty", &DIFFICULTIES, cx), + )) + .child(self.setting_row( + "Players can hurt each other (PvP)", + if running { + "A rule of the world. Applies at once.".into() + } else { + "A rule of the world: start the server to change it.".into() + }, + pvp, + )) + .child(self.setting_row( + "Most players at once", + format!("Operators can always join. {later}"), + self.stepper("server.max_players", 1..=100, cx), + )) + .child(self.setting_row( + "View distance", + format!("How far players see, in chunks (2 to 32). Lower is lighter. {later}"), + self.stepper("server.view_distance", 2..=32, cx), + )) + .child(self.setting_row( + "Simulation distance", + format!("How far from players crops grow and mobs move, in chunks. {later}"), + self.stepper("server.simulation_distance", 2..=32, cx), + )) + .child( + self.setting_row_checked( + "Port", + format!( + "1024 to 65535. Friends type it after the address unless it's 25565. {later}" + ), + self.servers + .invalid + .and_then(|(f, e)| (f == Field::Port).then_some(e)), + port, + ), + ) + .child(self.setting_row( + "Check Minecraft accounts", + if accounts { + format!("On: players must own Minecraft and sign in with Microsoft. {later}") + } else { + format!("Off: anyone can play under any name, so keep Friends only on. {later}") + }, + accounts_switch, + )) + .child(self.background_row(cx)); + div() + .flex() + .flex_col() + .gap(px(12.)) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Changes save as you make them. Those the game can't take while it runs wait for \ + a restart, and the page says so.", + )) + .child(form) + } + + fn background_row(&mut self, cx: &mut Context) -> Div { + let t = self.theme; + let on = self.servers.service.unwrap_or(false); + let idle = self.servers.busy.is_none() && self.servers.service.is_some(); + let toggle = switch("background", on, &t); + let toggle = if idle { + toggle.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.server_command( + if on { + "Turning off running in the background" + } else { + "Setting it to run in the background" + }, + vec![ + "service".into(), + if on { "uninstall" } else { "install" }.into(), + ], + ); + cx.notify(); + })) + } else { + disabled(toggle) + }; + self.setting_row( + "Run in the background and at login", + if on { + "On: starts when you log in to this computer, keeps running when the launcher \ + closes, and comes back by itself if the computer restarts." + .into() + } else { + "Off: the server stops when you close the launcher.".into() + }, + toggle.into_any_element(), + ) + } + + fn updates_section(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let idle = self.servers.busy.is_none(); + let check = self.servers.update.clone(); + let release = status + .release + .clone() + .or_else(|| { + check + .as_ref() + .and_then(|u| u["installed"].as_str().map(str::to_string)) + }) + .or_else(servers::runtime_release) + .unwrap_or_else(|| "?".into()); + let available = status.update_available.clone().or_else(|| { + check + .as_ref() + .filter(|u| u["available"] == true) + .and_then(|u| u["newest"].as_str().map(str::to_string)) + }); + let about = match (&available, &check, &status.update_last) { + (Some(tag), _, _) => format!( + "Update available: Horizon {tag} (this server runs {release}). Updating backs up \ + the world first, and goes back by itself if the new version doesn't start." + ), + (None, Some(_), _) => format!("Up to date: Horizon {release}."), + (None, None, Some((last, _))) => format!("Horizon {release}. {last}"), + (None, None, None) => format!("Horizon {release}."), + }; + let control = match available { + Some(tag) => { + let b = button("update-now", "Update now", Kind::Primary, &t); + if idle { + b.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.servers.update = None; + if let Some(dir) = this.servers.open.clone() { + let done = format!( + "Updated to Horizon {tag}. The world was backed up first (Backups)." + ); + this.server_job(format!("Updating to {tag}"), move |log| { + servers::run_streamed(&dir, &["update"], log).map(|_| done) + }); + } + cx.notify(); + })) + } else { + disabled(b) + } + } + None if self.servers.checking => { + disabled(button("update-check", "Checking…", Kind::Secondary, &t)) + } + None if !idle => disabled(button( + "update-check", + "Check for updates", + Kind::Secondary, + &t, + )), + None => button("update-check", "Check for updates", Kind::Secondary, &t).on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(dir) = this.servers.open.clone() { + this.servers.checking = true; + let tx = this.servers.tx.clone(); + std::thread::spawn(move || { + let result = servers::run(&dir, &["update", "--check", "--json"]) + .and_then(|out| { + serde_json::from_str(out.trim()) + .map_err(|e| Problem::plain(e.to_string())) + }); + let _ = tx.send(Event::UpdateCheck(result)); + }); + } + cx.notify(); + }), + ), + }; + let mut rows = div() + .flex() + .flex_col() + .border_t_1() + .border_color(t.rule) + .child(self.setting_row("This server's Horizon", about, control.into_any_element())); + if self.servers.setting("updates", "keep").is_some() { + rows = rows.child(self.setting_row( + "Older versions kept", + "Downloaded versions kept besides the one in use and the one an update can go back \ + to." + .into(), + self.stepper("updates.keep", 0..=5, cx), + )); + } + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(text(theme::HEADING).text_color(t.ink).child("Updates")) + .child(rows) + } + + /// The server's details came back without its settings: its horizon-server predates + /// `config` (and `backups --json`). + fn older_horizon(&self) -> bool { + self.servers.service.is_some() && self.servers.config.is_none() + } + + fn backups_tab(&mut self, status: &Status, cx: &mut Context) -> Div { + let t = self.theme; + let idle = self.servers.busy.is_none(); + let every = self.servers.shown("backups", "every"); + let auto = !every.is_empty() && every != "0"; + let keep = self.servers.shown("backups", "keep"); + let now = { + let b = button("backup-now", "Back up now", Kind::Primary, &t); + if idle { + b.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.server_command("Backing up", vec!["backup".into()]); + cx.notify(); + })) + } else { + disabled(b) + } + }; + let toggle = switch("auto-backup", auto, &t).on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + this.set_setting("backups.every", if auto { "0".into() } else { "6h".into() }); + cx.notify(); + }, + )); + let mut list = div().flex().flex_col().border_t_1().border_color(t.rule); + for (i, b) in self.servers.backups.clone().into_iter().enumerate() { + let (when, kind) = backup_label(&b); + let confirming = self.servers.confirm_restore.as_deref() == Some(b.name.as_str()); + let name = b.name.clone(); + let restored = format!( + "The world is back as it was on {when}. The one it replaced is in the backups \ + folder." + ); + let restore = button( + SharedString::from(format!("restore-{i}")), + if confirming { + "Replace the world" + } else { + "Restore" + }, + if confirming { + Kind::Primary + } else { + Kind::Ghost + }, + &t, + ); + let restore = if idle { + restore.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if this.servers.confirm_restore.as_ref() == Some(&name) { + this.servers.confirm_restore = None; + if let Some(dir) = this.servers.open.clone() { + let (name, restored) = (name.clone(), restored.clone()); + this.server_job("Restoring", move |log| { + servers::run_streamed(&dir, &["restore", &name, "--yes"], log) + .map(|_| restored) + }); + } + } else { + this.servers.confirm_restore = Some(name.clone()); + } + cx.notify(); + })) + } else { + disabled(restore) + }; + let mut right = div().flex().items_center().gap(px(8.)); + if confirming { + right = right.child( + button("restore-cancel", "Cancel", Kind::Ghost, &t).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + this.servers.confirm_restore = None; + cx.notify(); + }, + )), + ); + } + right = right.child(restore); + let detail = if kind.is_empty() { + bytes(b.bytes) + } else { + format!("{kind} · {}", bytes(b.bytes)) + }; + list = list.child(index_row( + i + 1, + when, + Some(detail.into_any_element()), + Some(right.into_any_element()), + &t, + )); + } + let mut tab = div().flex().flex_col().gap(px(20.)).child( + div().flex().items_center().gap(px(16.)).child(now).child( + text(theme::CAPTION) + .text_color(t.muted) + .child(if status.running() { + "Players stay online: the world is saved, then zipped." + } else { + "Zips the world and the server's settings into its backups folder." + }), + ), + ); + if self.older_horizon() { + return tab + .child(text(theme::UI).text_color(t.muted).child( + "This server's Horizon is too old to list its backups here: they're in its \ + backups folder. Update it below.", + )) + .child(self.updates_section(status, cx)); + } + tab = tab.child( + div() + .flex() + .items_center() + .gap(px(14.)) + .child(toggle) + .child( + div() + .flex() + .flex_col() + .child( + text(theme::UI) + .text_color(t.ink) + .child("Back up automatically"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child(if auto { + format!( + "On: every {every} while the server runs, keeping the last \ + {keep}. Backups you make yourself are never deleted." + ) + } else { + "Off: only the backups you make.".to_string() + })), + ), + ); + if self.servers.confirm_restore.is_some() { + tab = tab.child(notice( + "Restoring replaces the world with this backup. The world as it is now isn't \ + deleted: it's moved into the backups folder. A running server stops and starts \ + again with the restored world." + .into(), + &t, + )); + } + tab = if self.servers.backups.is_empty() { + tab.child(text(theme::UI).text_color(t.muted).child("No backup yet.")) + } else { + tab.child(list) + }; + tab.child(self.updates_section(status, cx)) + } + + // ----- The Create dialog ---------------------------------------------------------------- + + pub(super) fn create_dialog(&mut self, cx: &mut Context) -> Option> { + let t = self.theme; + let c = self.servers.create.as_ref()?; + let (new_world, copy, worlds) = (c.new_world, c.copy.clone(), c.worlds.clone()); + let (mode, difficulty, max_players) = (c.mode, c.difficulty, c.max_players); + let (friends_only, check_accounts, eula, eula_missing) = + (c.friends_only, c.check_accounts, c.eula, c.eula_missing); + let creating = self.servers.creating; + let row = |label: &'static str, control: AnyElement| { + div() + .flex() + .flex_col() + .gap(px(8.)) + .child(caps(label).text_color(t.muted)) + .child(control) + }; + let weak = cx.entity().downgrade(); + let pick = move |f: fn(&mut Create, &'static str)| { + let weak = weak.clone(); + move |value: &'static str, _: &mut Window, cx: &mut App| { + let _ = weak.update(cx, |this, cx| { + if let Some(c) = &mut this.servers.create { + f(c, value); + } + cx.notify(); + }); + } + }; + let world_kind = segments( + "create-world", + &[("new", "New world"), ("copy", "Copy one of my worlds")], + if new_world { "new" } else { "copy" }, + &t, + pick(|c, v| c.new_world = v == "new"), + ); + let world_detail = if new_world { + self.field( + Field::Seed, + "Seed (optional: leave empty for a random world)", + 400., + cx, + ) + .into_any_element() + } else if worlds.is_empty() { + text(theme::CAPTION) + .text_color(t.muted) + .child("You have no single-player world yet: play one first, or choose New world.") + .into_any_element() + } else { + let mut list = div().flex().flex_col().gap(px(2.)); + for (i, (name, path)) in worlds.into_iter().take(8).enumerate() { + let chosen = copy.as_ref() == Some(&path); + list = list.child( + div() + .id(SharedString::from(format!("create-copy-{i}"))) + .flex() + .items_center() + .gap(px(10.)) + .h(px(32.)) + .px(px(10.)) + .rounded(px(theme::RADIUS)) + .cursor_pointer() + .when(chosen, |d| d.bg(t.plate_soft)) + .hover(move |s| s.bg(t.plate_soft)) + .child( + div() + .size(px(12.)) + .rounded_full() + .border_1() + .border_color(if chosen { t.accent } else { t.muted }) + .when(chosen, |d| d.bg(t.accent)), + ) + .child(text(theme::UI).text_color(t.ink).child(name)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.copy = Some(path.clone()); + } + cx.notify(); + })), + ); + } + div() + .flex() + .flex_col() + .gap(px(6.)) + .child(list) + .child( + text(theme::CAPTION) + .text_color(t.muted) + .child("The server gets a copy: your single-player world stays as it is."), + ) + .into_any_element() + }; + let modes = segments("create-mode", &MODES, mode, &t, pick(|c, v| c.mode = v)); + let difficulties = segments( + "create-difficulty", + &DIFFICULTIES, + difficulty, + &t, + pick(|c, v| c.difficulty = v), + ); + let who = segments( + "create-who", + &[ + ("friends", "Friends only"), + ("anyone", "Anyone with the address"), + ], + if friends_only { "friends" } else { "anyone" }, + &t, + pick(|c, v| c.friends_only = v == "friends"), + ); + let step = |id: &'static str, label: &'static str, delta: i32, cx: &mut Context| { + button(id, label, Kind::Secondary, &t) + .w(px(36.)) + .px(px(0.)) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.max_players = (c.max_players as i32 + delta).clamp(1, 100) as u32; + } + cx.notify(); + })) + }; + let players = div() + .flex() + .items_center() + .gap(px(8.)) + .child(step("create-fewer", "−", -1, cx)) + .child( + text(theme::UI) + .w(px(44.)) + .flex() + .justify_center() + .text_color(t.ink) + .child(max_players.to_string()), + ) + .child(step("create-more", "+", 1, cx)); + let checkbox = |id: &'static str, on: bool| { + div() + .id(id) + .flex_none() + .size(px(18.)) + .rounded(px(4.)) + .border_1() + .border_color(if on { t.accent } else { t.muted }) + .bg(if on { t.accent } else { t.surface }) + .flex() + .items_center() + .justify_center() + .text_color(t.on_accent) + .text_size(px(12.)) + .cursor_pointer() + .when(on, |d| d.child("✓")) + }; + let accounts = div() + .flex() + .items_start() + .gap(px(10.)) + .child( + checkbox("create-accounts", check_accounts).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.check_accounts = !c.check_accounts; + } + cx.notify(); + }, + )), + ) + .child( + div() + .flex_1() + .min_w_0() + .flex() + .flex_col() + .child( + text(theme::UI) + .text_color(t.ink) + .child("Check Minecraft accounts"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Only if every player signs in with Microsoft. Leave it off for Horizon \ + players without an account: Friends only keeps strangers out.", + )), + ); + let eula_line = div() + .flex() + .items_center() + .gap(px(10.)) + .child(checkbox("create-eula", eula).on_click(cx.listener( + |this, _: &ClickEvent, _, cx| { + if let Some(c) = &mut this.servers.create { + c.eula = !c.eula; + c.eula_missing = false; + } + cx.notify(); + }, + ))) + .child( + text(theme::UI) + .text_color(if eula_missing { t.danger } else { t.ink }) + .child("I agree to the Minecraft EULA"), + ) + .child( + div() + .id("create-eula-read") + .text_size(px(theme::UI.px)) + .text_color(t.accent) + .cursor_pointer() + .hover(|s| s.opacity(0.8)) + .child("Read it") + .on_click(|_, _, cx| cx.open_url(servers::EULA_URL)), + ); + let body = div() + .id("create-body") + .flex() + .flex_col() + .min_h_0() + .gap(px(20.)) + .px(px(28.)) + .pt(px(28.)) + .pb(px(20.)) + .overflow_y_scroll() + .child(caps("New server").text_color(t.muted)) + .child( + text(theme::HEADING) + .text_color(t.ink) + .child("Create a server"), + ) + .child(text(theme::CAPTION).text_color(t.muted).child( + "Everything has a default: tick the EULA and Create makes a friends-only survival \ + world. You can change all of it later.", + )) + .child(row( + "Name", + self.field(Field::Name, "My server", 400., cx) + .into_any_element(), + )) + .child(row( + "World", + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(div().flex().child(world_kind)) + .child(world_detail) + .into_any_element(), + )) + .child(row( + "Game mode", + div().flex().child(modes).into_any_element(), + )) + .child(row( + "Difficulty", + div().flex().child(difficulties).into_any_element(), + )) + .child(row("Most players at once", players.into_any_element())) + .child(row( + "Who can join", + div() + .flex() + .flex_col() + .gap(px(10.)) + .child(div().flex().child(who)) + .when(friends_only, |d| { + d.child(self.field( + Field::Players, + "Players allowed in, separated by commas (you first)", + 480., + cx, + )) + .child(text(theme::CAPTION).text_color(t.muted).child( + "The first one becomes an operator. Add more later on the Players tab.", + )) + }) + .child(accounts) + .into_any_element(), + )) + .child(eula_line); + let mut foot = div() + .flex() + .flex_none() + .items_center() + .justify_end() + .gap(px(12.)) + .px(px(28.)) + .pt(px(8.)) + .pb(px(28.)); + if creating { + let last = self.servers.job_log.back().cloned().unwrap_or_default(); + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .min_w_0() + .text_color(t.muted) + .truncate() + .child(format!("Creating… {last}")), + ); + } else if let Some(p) = &self.servers.problem { + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .min_w_0() + .text_color(t.danger) + .child(p.message.clone()), + ); + if let Some(fix @ Fix::Prepare) = p.fix.clone() { + foot = foot.child( + button("create-fix", "Prepare the game files", Kind::Secondary, &t).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + this.fix(fix.clone(), cx); + cx.notify(); + }), + ), + ); + } + } else if eula_missing { + foot = foot.child( + text(theme::CAPTION) + .flex_1() + .text_color(t.danger) + .child("Tick the EULA box to create the server."), + ); + } + let cancel = button("create-cancel", "Cancel", Kind::Secondary, &t); + let create = button("create-go", "Create", Kind::Primary, &t); + foot = if creating { + foot.child(disabled(cancel)).child(disabled(create)) + } else { + foot.child(cancel.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.servers.create = None; + this.servers.problem = None; + cx.notify(); + }))) + .child(create.on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.create_server(); + cx.notify(); + }))) + }; + let card = plate(&t) + .flex() + .flex_col() + .w_full() + .max_w(px(640.)) + .max_h_full() + .bg(t.page) + .border_1() + .border_color(t.rule) + .child(self.servers.create_scroll.wrap(body, &t)) + .child(foot); + Some( + div() + .id("create-dialog") + .absolute() + .top_0() + .left_0() + .size_full() + .flex() + .flex_col() + .items_center() + .px(px(32.)) + .py(px(24.)) + .bg(t.page.opacity(0.92)) + .on_scroll_wheel(|_, _, cx| cx.stop_propagation()) + .occlude() + .child(card), + ) + } +} + +/// The state, in a few words. +fn phase_label(status: &Status) -> String { + if let Some(busy) = &status.update_busy { + return format!("Updating: {busy}"); + } + match status.phase.as_str() { + "running" if status.crashes > 0 => "Running · restarted after a crash".into(), + "running" if status.paused => "Running · paused while nobody plays".into(), + "running" => "Running".into(), + "starting" => "Starting".into(), + "restarting" => "Restarting".into(), + "stopping" => "Stopping".into(), + _ => "Stopped".into(), + } +} + +/// A setting's name for people. +fn setting_name(key: &str) -> &str { + match key { + "server.motd" => "the message in the server list", + "server.port" => "the port", + "server.max_players" => "most players", + "server.view_distance" => "view distance", + "server.simulation_distance" => "simulation distance", + "server.online_mode" => "account checks", + other => other, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn backups_read_for_people() { + let b = |name: &str| Backup { + name: name.into(), + bytes: 1, + modified: None, + }; + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-manual.zip")), + ("2026-10-19 11:28:57 UTC".into(), "Made by hand".into()) + ); + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-before-v2026.10.20.zip")).1, + "Before updating to v2026.10.20" + ); + assert_eq!( + backup_label(&b("2026-10-19_13-35-36-before-v2026-10-19-10.zip")).1, + "Before updating to v2026.10.19.10" + ); + assert_eq!( + backup_label(&b("2026-10-14_17-46-40-before-update.zip")).1, + "Before an update" + ); + assert_eq!( + backup_label(&b("2026-10-19_11-28-57-auto.zip")).1, + "Automatic" + ); + assert_eq!(backup_label(&b("odd.zip")), ("odd".into(), String::new())); + assert_eq!(bytes(5_292_542), "5.3 MB"); + assert_eq!(uptime(3725), "1 h 02 min"); + let mut long = "é".repeat(300); + clip(&mut long); + assert_eq!(long.chars().count(), 256); + } + + /// The keyboard in a one-line field, as the Create dialog, Players, Settings and the console use it. + #[test] + fn fields_type_as_people_expect() { + let mut text = String::from("My server"); + // The suggestion is selected: the first letter replaces it. + assert_eq!( + type_key(&mut text, true, "f", Some("F"), false), + Key::Edited + ); + assert_eq!(text, "F"); + // Space, which some platforms send without a character. + assert_eq!( + type_key(&mut text, false, "space", None, false), + Key::Edited + ); + assert_eq!( + type_key(&mut text, false, "n", Some("N"), false), + Key::Edited + ); + assert_eq!(text, "F N"); + assert_eq!( + type_key(&mut text, false, "backspace", None, false), + Key::Edited + ); + assert_eq!(text, "F "); + // Backspace on a suggestion clears it all. + let mut text = String::from("Server 2"); + type_key(&mut text, true, "backspace", None, false); + assert_eq!(text, ""); + // Paste replaces a suggestion too; the caller adds the clipboard. + let mut text = String::from("Server 2"); + assert_eq!(type_key(&mut text, true, "v", Some("v"), true), Key::Paste); + assert_eq!(text, ""); + // Tab, arrows and shortcuts aren't the field's: Tab moves the focus. + let mut text = String::from("Ludo"); + for (key, ch, command) in [ + ("tab", Some("\t"), false), + ("left", None, false), + ("a", Some("a"), true), + ] { + assert_eq!(type_key(&mut text, false, key, ch, command), Key::Pass); + } + assert_eq!( + type_key(&mut text, true, "enter", Some("\n"), false), + Key::Enter + ); + assert_eq!( + type_key(&mut text, false, "escape", None, false), + Key::Escape + ); + assert_eq!(text, "Ludo"); + } +} diff --git a/launcher/src/tailscale.rs b/launcher/src/tailscale.rs new file mode 100644 index 000000000..683ff0aab --- /dev/null +++ b/launcher/src/tailscale.rs @@ -0,0 +1,509 @@ +//! Friends over the internet through Tailscale: is it installed and signed in, this computer's name and +//! address on the tailnet, and, with the player's own API access token, inviting a friend to this one +//! computer (device sharing) and limiting what shared friends reach to the server's port. +//! +//! The launcher never signs in for anyone and never uses Funnel: signing in happens in Tailscale's own app +//! or page, and the access token is one the player makes in the admin console and pastes here (it is +//! kept in the system keychain). `HORIZON_LAUNCHER_TAILSCALE` (the CLI) and `HORIZON_TAILSCALE_API` (the +//! API's address) point the tests at stand-ins. +use serde_json::{json, Value}; +use std::path::PathBuf; +use std::process::Command; +use std::time::Duration; + +/// The admin console: sign-in, keys, machines, the access controls. +pub const ADMIN: &str = "https://login.tailscale.com/admin"; +/// Where an API access token is made. +pub const KEYS: &str = "https://login.tailscale.com/admin/settings/keys"; +/// The access controls page. +pub const ACCESS: &str = "https://login.tailscale.com/admin/acls/file"; +/// The keychain entry of the player's API access token. +pub const TOKEN_KEY: &str = "tailscale-api-token"; + +/// Where to download Tailscale for this system. +pub fn install_url() -> &'static str { + if cfg!(target_os = "macos") { + "https://tailscale.com/download/mac" + } else if cfg!(windows) { + "https://tailscale.com/download/windows" + } else { + "https://tailscale.com/download/linux" + } +} + +/// The command that signs this computer in on Linux (it opens a link to finish in the browser). +pub const LINUX_LOGIN: &str = "sudo tailscale up --operator=$USER"; + +/// The `tailscale` command, wherever the installer put it. +pub fn cli() -> Option { + if let Some(p) = std::env::var_os("HORIZON_LAUNCHER_TAILSCALE") { + return Some(PathBuf::from(p)).filter(|p| p.is_file()); + } + let mut places: Vec = std::env::var_os("PATH") + .map(|p| { + std::env::split_paths(&p) + .map(|d| { + d.join(if cfg!(windows) { + "tailscale.exe" + } else { + "tailscale" + }) + }) + .collect() + }) + .unwrap_or_default(); + if cfg!(target_os = "macos") { + places.push("/Applications/Tailscale.app/Contents/MacOS/Tailscale".into()); + places.push("/usr/local/bin/tailscale".into()); + places.push("/opt/homebrew/bin/tailscale".into()); + } else if cfg!(windows) { + places.push(r"C:\Program Files\Tailscale\tailscale.exe".into()); + } else { + places.push("/usr/bin/tailscale".into()); + places.push("/usr/local/bin/tailscale".into()); + places.push("/run/current-system/sw/bin/tailscale".into()); + } + places.into_iter().find(|p| p.is_file()) +} + +/// This computer on the tailnet. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Node { + /// The stable node ID (`n…`), which the API takes as the device ID. + pub id: String, + pub host: String, + /// The MagicDNS name (`host.tailnet.ts.net`), without the final dot. + pub dns_name: String, + pub ips: Vec, + pub tailnet: String, + pub magic_dns: bool, +} + +impl Node { + pub fn ipv4(&self) -> Option<&str> { + self.ips + .iter() + .map(String::as_str) + .find(|ip| !ip.contains(':')) + } + + /// What a friend types in Minecraft: the MagicDNS name when it is on, else the address. + pub fn address(&self, port: u16) -> String { + let host = if self.magic_dns && !self.dns_name.is_empty() { + self.dns_name.as_str() + } else { + self.ipv4().unwrap_or_default() + }; + if port == 25565 { + host.to_string() + } else { + format!("{host}:{port}") + } + } +} + +/// Where Tailscale stands on this computer. +#[derive(Clone, Debug, PartialEq)] +pub enum State { + /// No `tailscale` command. + Missing, + /// Installed, but its service doesn't answer (the app isn't open, or it is switched off). + Off(String), + /// Installed and waiting for the player to sign in (with the link to finish it, when there is one). + SignedOut { + auth_url: Option, + }, + Running(Node), +} + +/// Asks `tailscale status --json` (read-only). +pub fn status() -> State { + status_of(cli()) +} + +/// `status` with a given `tailscale` command. +pub fn status_of(cli: Option) -> State { + let Some(cli) = cli else { + return State::Missing; + }; + let mut command = Command::new(&cli); + command.args(["status", "--json"]); + #[cfg(windows)] + { + use std::os::windows::process::CommandExt; + command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW + } + let out = match command.output() { + Ok(out) => out, + Err(e) => return State::Off(e.to_string()), + }; + match serde_json::from_slice::(&out.stdout) { + Ok(v) if v.is_object() => parse_status(&v), + _ => { + let err = String::from_utf8_lossy(&out.stderr); + let line = err.lines().find(|l| !l.trim().is_empty()).unwrap_or(""); + State::Off(line.trim().to_string()) + } + } +} + +pub fn parse_status(v: &Value) -> State { + let backend = v["BackendState"].as_str().unwrap_or_default(); + match backend { + "Running" => { + let me = &v["Self"]; + let ips = me["TailscaleIPs"] + .as_array() + .map(|a| { + a.iter() + .filter_map(|ip| ip.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + let tailnet = &v["CurrentTailnet"]; + State::Running(Node { + id: me["ID"].as_str().unwrap_or_default().to_string(), + host: me["HostName"].as_str().unwrap_or_default().to_string(), + dns_name: me["DNSName"] + .as_str() + .unwrap_or_default() + .trim_end_matches('.') + .to_string(), + ips, + tailnet: tailnet["Name"].as_str().unwrap_or_default().to_string(), + magic_dns: tailnet["MagicDNSEnabled"].as_bool().unwrap_or(false), + }) + } + "NeedsLogin" | "NeedsMachineAuth" | "NoState" => State::SignedOut { + auth_url: v["AuthURL"] + .as_str() + .filter(|u| u.starts_with("https://")) + .map(str::to_string), + }, + "Stopped" => State::Off("Tailscale is switched off.".into()), + other => State::Off(format!("Tailscale is {}.", other.to_lowercase())), + } +} + +/// Opens the Tailscale app, where the player signs in (macOS and Windows; Linux has no app). +pub fn open_app() -> Result<(), String> { + let result = if cfg!(target_os = "macos") { + Command::new("open").args(["-a", "Tailscale"]).status() + } else if cfg!(windows) { + Command::new(r"C:\Program Files\Tailscale\tailscale-ipn.exe").status() + } else { + return Err(format!( + "Run `{LINUX_LOGIN}` in a terminal and open the link it prints." + )); + }; + match result { + Ok(s) if s.success() => Ok(()), + Ok(_) | Err(_) => { + Err("Tailscale's app didn't open: start it from your applications.".into()) + } + } +} + +// ----- The API -------------------------------------------------------------------------------------- + +/// An invitation to use this computer, as the API lists it. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Invite { + pub id: String, + pub url: String, + pub email: Option, + pub created: String, + pub accepted: bool, + /// Who accepted it (their login name). + pub accepted_by: Option, +} + +impl Invite { + fn parse(v: &Value) -> Self { + Self { + id: match &v["id"] { + Value::String(s) => s.clone(), + other => other.to_string(), + }, + url: v["inviteUrl"].as_str().unwrap_or_default().to_string(), + email: v["email"] + .as_str() + .filter(|e| !e.is_empty()) + .map(str::to_string), + created: v["created"].as_str().unwrap_or_default().to_string(), + accepted: v["accepted"].as_bool().unwrap_or(false), + accepted_by: v["acceptedBy"]["loginName"].as_str().map(str::to_string), + } + } +} + +/// Tailscale's API with the player's access token. +pub struct Api { + base: String, + token: String, +} + +impl Api { + pub fn new(token: &str) -> Self { + let base = std::env::var("HORIZON_TAILSCALE_API") + .unwrap_or_else(|_| "https://api.tailscale.com".into()); + Self::at(&base, token) + } + + /// The API at another address (a stand-in in tests). + pub fn at(base: &str, token: &str) -> Self { + Self { + base: base.trim_end_matches('/').to_string(), + token: token.trim().to_string(), + } + } + + fn send( + &self, + method: &str, + path: &str, + body: Option<&Value>, + if_match: Option<&str>, + ) -> Result<(Value, Option), String> { + let agent = ureq::AgentBuilder::new() + .timeout(Duration::from_secs(20)) + .build(); + let mut request = agent + .request(method, &format!("{}/api/v2{path}", self.base)) + .set("Authorization", &format!("Bearer {}", self.token)) + .set("Accept", "application/json"); + if let Some(etag) = if_match { + request = request.set("If-Match", etag); + } + let response = match body { + Some(b) => request.send_json(b.clone()), + None => request.call(), + }; + match response { + Ok(r) => { + let etag = r.header("ETag").map(str::to_string); + let text = r.into_string().map_err(|e| e.to_string())?; + let v = if text.trim().is_empty() { + Value::Null + } else { + serde_json::from_str(&text).map_err(|e| e.to_string())? + }; + Ok((v, etag)) + } + Err(ureq::Error::Status(code, r)) => { + let v: Value = r.into_json().unwrap_or(Value::Null); + let said = v["message"].as_str().unwrap_or_default(); + Err(match code { + 401 => "Tailscale didn't accept the access token: it may have expired. Make a \ + new one and paste it again." + .to_string(), + 403 => format!( + "This access token may not do that{}. Make one as an admin of your tailnet.", + if said.is_empty() { + String::new() + } else { + format!(" ({said})") + } + ), + 412 => "The access controls changed meanwhile: look again before changing them." + .to_string(), + _ if !said.is_empty() => format!("Tailscale says: {said}"), + _ => format!("Tailscale answered {code}."), + }) + } + Err(e) => Err(format!("Tailscale's API didn't answer: {e}")), + } + } + + /// The invitations to this computer. + pub fn invites(&self, device: &str) -> Result, String> { + let (v, _) = self.send( + "GET", + &format!("/device/{device}/device-invites"), + None, + None, + )?; + Ok(v.as_array() + .map(|a| a.iter().map(Invite::parse).collect()) + .unwrap_or_default()) + } + + /// A new invitation to this computer only: a link to send, or sent by email by Tailscale. One + /// friend each (not reusable), never as an exit node. + pub fn invite(&self, device: &str, email: Option<&str>) -> Result { + let mut one = json!({ "multiUse": false, "allowExitNode": false }); + if let Some(email) = email.filter(|e| !e.trim().is_empty()) { + one["email"] = json!(email.trim()); + } + let (v, _) = self.send( + "POST", + &format!("/device/{device}/device-invites"), + Some(&json!([one])), + None, + )?; + v.as_array() + .and_then(|a| a.first()) + .map(Invite::parse) + .ok_or_else(|| "Tailscale made no invitation.".to_string()) + } + + /// Withdraws an invitation (an accepted one stops sharing the computer with that friend). + pub fn revoke(&self, invite: &str) -> Result<(), String> { + self.send("DELETE", &format!("/device-invites/{invite}"), None, None) + .map(|_| ()) + } + + /// The tailnet's access controls (as JSON) and their version. + pub fn policy(&self) -> Result<(Value, Option), String> { + self.send("GET", "/tailnet/-/acl", None, None) + } + + /// Checks new access controls without applying them. + pub fn validate(&self, policy: &Value) -> Result<(), String> { + let (v, _) = self.send("POST", "/tailnet/-/acl/validate", Some(policy), None)?; + match v["message"].as_str() { + Some(m) if !m.is_empty() => Err(format!("Tailscale wouldn't take the change: {m}")), + _ => Ok(()), + } + } + + /// Applies new access controls, only if nobody changed them since `etag`. + pub fn set_policy(&self, policy: &Value, etag: Option<&str>) -> Result<(), String> { + self.send("POST", "/tailnet/-/acl", Some(policy), etag) + .map(|_| ()) + } +} + +// ----- Limiting what shared friends reach ------------------------------------------------------------- + +/// What the tailnet's access controls let shared friends reach. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Reach { + /// Tailscale's default: everyone, shared friends included, reaches every port of this computer. + Everything, + /// Shared friends reach only the server's port (the rule this launcher adds). + ServerOnly, + /// Access controls someone wrote: the launcher doesn't touch them. + Custom, +} + +const MEMBERS: [&str; 2] = ["autogroup:member", "autogroup:tagged"]; +const SHARED: &str = "autogroup:shared"; + +fn is_star(v: &Value) -> bool { + v.as_array().is_some_and(|a| a.len() == 1 && a[0] == "*") +} + +fn is_members(v: &Value) -> bool { + v.as_array().is_some_and(|a| { + a.len() == MEMBERS.len() && MEMBERS.iter().all(|m| a.iter().any(|x| x == m)) + }) +} + +/// The allow-all rule, in either of its forms: `acls` (`src`/`dst` or the older `users`/`ports`) or +/// `grants`. +fn allow_all(rule: &Value, grant: bool) -> bool { + if grant { + is_star(&rule["src"]) && is_star(&rule["dst"]) && is_star(&rule["ip"]) + } else { + rule["action"] == "accept" + && (is_star(&rule["src"]) || is_star(&rule["users"])) + && [&rule["dst"], &rule["ports"]] + .iter() + .any(|d| d.as_array().is_some_and(|a| a.len() == 1 && a[0] == "*:*")) + } +} + +fn members_all(rule: &Value, grant: bool) -> bool { + if grant { + is_members(&rule["src"]) && is_star(&rule["dst"]) && is_star(&rule["ip"]) + } else { + rule["action"] == "accept" + && is_members(&rule["src"]) + && rule["dst"] + .as_array() + .is_some_and(|a| a.len() == 1 && a[0] == "*:*") + } +} + +fn shared_rule(ip: &str, port: u16, grant: bool) -> Value { + if grant { + json!({ "src": [SHARED], "dst": [ip], "ip": [format!("tcp:{port}")] }) + } else { + json!({ "action": "accept", "src": [SHARED], "dst": [format!("{ip}:{port}")] }) + } +} + +/// The rules (`acls` or `grants`) when the policy is one of the two shapes this launcher knows: the +/// default allow-all alone, or that limited by `limit_shared` (with only shared rules beside it). +fn known(policy: &Value) -> Option<(&'static str, &Vec)> { + let acls = policy["acls"].as_array().filter(|a| !a.is_empty()); + let grants = policy["grants"].as_array().filter(|a| !a.is_empty()); + match (acls, grants) { + (Some(a), None) => Some(("acls", a)), + (None, Some(g)) => Some(("grants", g)), + _ => None, + } +} + +/// What shared friends reach under `policy`, for this computer's address and the server's port. +pub fn reach(policy: &Value, ip: &str, port: u16) -> Reach { + let Some((key, rules)) = known(policy) else { + return Reach::Custom; + }; + let grant = key == "grants"; + if rules.len() == 1 && allow_all(&rules[0], grant) { + return Reach::Everything; + } + let ours = shared_rule(ip, port, grant); + if rules.len() == 2 && members_all(&rules[0], grant) && rules[1] == ours { + return Reach::ServerOnly; + } + Reach::Custom +} + +/// The default policy changed so shared friends reach only `ip:port`, everyone else as before; None +/// when the policy isn't the default (then the player adds `snippet` by hand). +pub fn limit_shared(policy: &Value, ip: &str, port: u16) -> Option { + if reach(policy, ip, port) != Reach::Everything { + return None; + } + let (key, _) = known(policy)?; + let grant = key == "grants"; + let members = if grant { + json!({ "src": MEMBERS, "dst": ["*"], "ip": ["*"] }) + } else { + json!({ "action": "accept", "src": MEMBERS, "dst": ["*:*"] }) + }; + let mut new = policy.clone(); + new[key] = json!([members, shared_rule(ip, port, grant)]); + Some(new) +} + +/// Undoes `limit_shared`: Tailscale's default rule back. None if the policy isn't the limited one. +pub fn unlimit_shared(policy: &Value, ip: &str, port: u16) -> Option { + if reach(policy, ip, port) != Reach::ServerOnly { + return None; + } + let (key, _) = known(policy)?; + let mut new = policy.clone(); + new[key] = if key == "grants" { + json!([{ "src": ["*"], "dst": ["*"], "ip": ["*"] }]) + } else { + json!([{ "action": "accept", "src": ["*"], "dst": ["*:*"] }]) + }; + Some(new) +} + +/// The two rules to put in access controls someone wrote, by hand in the admin console. +pub fn snippet(ip: &str, port: u16) -> String { + format!( + "// Friends this computer is shared with reach only the Minecraft server.\n\ + // Replace \"*\" with these two in the rule that lets everyone reach everything:\n\ + // \"src\": [\"autogroup:member\", \"autogroup:tagged\"]\n\ + {{\"action\": \"accept\", \"src\": [\"autogroup:shared\"], \"dst\": [\"{ip}:{port}\"]}}," + ) +} + +#[cfg(test)] +mod tests; diff --git a/launcher/src/tailscale/tests.rs b/launcher/src/tailscale/tests.rs new file mode 100644 index 000000000..98078ddbc --- /dev/null +++ b/launcher/src/tailscale/tests.rs @@ -0,0 +1,270 @@ +use super::*; +use std::io::{BufRead, BufReader, Read, Write}; +use std::sync::{Arc, Mutex}; + +fn running() -> Value { + json!({ + "BackendState": "Running", + "AuthURL": "", + "Self": { + "ID": "nAbCdEf1CNTRL", + "HostName": "ludos-mac", + "DNSName": "ludos-mac.tail1234.ts.net.", + "TailscaleIPs": ["100.101.102.103", "fd7a:115c:a1e0::1"] + }, + "CurrentTailnet": { "Name": "ludo@example.com", "MagicDNSSuffix": "tail1234.ts.net", "MagicDNSEnabled": true } + }) +} + +#[test] +fn status_reads_as_the_cli_writes_it() { + let State::Running(node) = parse_status(&running()) else { + panic!("not running"); + }; + assert_eq!(node.id, "nAbCdEf1CNTRL"); + assert_eq!(node.dns_name, "ludos-mac.tail1234.ts.net"); + assert_eq!(node.ipv4(), Some("100.101.102.103")); + assert_eq!(node.address(25565), "ludos-mac.tail1234.ts.net"); + assert_eq!( + Node { + magic_dns: false, + ..node.clone() + } + .address(25570), + "100.101.102.103:25570" + ); + assert_eq!( + parse_status( + &json!({ "BackendState": "NeedsLogin", "AuthURL": "https://login.tailscale.com/a/abc" }) + ), + State::SignedOut { + auth_url: Some("https://login.tailscale.com/a/abc".into()) + } + ); + assert_eq!( + parse_status(&json!({ "BackendState": "NeedsLogin", "AuthURL": "" })), + State::SignedOut { auth_url: None } + ); + assert!(matches!( + parse_status(&json!({ "BackendState": "Stopped" })), + State::Off(_) + )); + assert_eq!(status_of(None), State::Missing); +} + +/// The CLI is only ever asked `status --json`: a stand-in that refuses anything else. +#[cfg(unix)] +#[test] +fn status_asks_the_cli_read_only() { + use std::os::unix::fs::PermissionsExt; + let dir = std::env::temp_dir().join(format!("horizon-tailscale-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let json = dir.join("status.json"); + std::fs::write(&json, running().to_string()).unwrap(); + let fake = dir.join("tailscale"); + std::fs::write( + &fake, + format!( + "#!/bin/sh\n[ \"$*\" = \"status --json\" ] || {{ echo \"unexpected: $*\" >&2; exit 9; }}\ncat '{}'\n", + json.display() + ), + ) + .unwrap(); + std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(matches!(status_of(Some(fake.clone())), State::Running(n) if n.host == "ludos-mac")); + // A stopped daemon: no JSON, a line on stderr. + std::fs::write( + &fake, + "#!/bin/sh\necho 'failed to connect to local tailscaled; it doesn'\\''t appear to be running' >&2\nexit 1\n", + ) + .unwrap(); + assert!(matches!(status_of(Some(fake)), State::Off(why) if why.contains("tailscaled"))); + std::fs::remove_dir_all(&dir).unwrap(); +} + +fn default_acls() -> Value { + json!({ + "tagOwners": { "tag:server": ["autogroup:admin"] }, + "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }], + "ssh": [{ "action": "check", "src": ["autogroup:member"], "dst": ["autogroup:self"], "users": ["autogroup:nonroot", "root"] }] + }) +} + +#[test] +fn the_default_policy_is_limited_for_shared_friends_only() { + let ip = "100.101.102.103"; + let policy = default_acls(); + assert_eq!(reach(&policy, ip, 25565), Reach::Everything); + let limited = limit_shared(&policy, ip, 25565).unwrap(); + assert_eq!( + limited["acls"], + json!([ + { "action": "accept", "src": ["autogroup:member", "autogroup:tagged"], "dst": ["*:*"] }, + { "action": "accept", "src": ["autogroup:shared"], "dst": ["100.101.102.103:25565"] } + ]) + ); + // Everything else stays. + assert_eq!(limited["ssh"], policy["ssh"]); + assert_eq!(limited["tagOwners"], policy["tagOwners"]); + assert_eq!(reach(&limited, ip, 25565), Reach::ServerOnly); + // Another port: not the launcher's rule for this server. + assert_eq!(reach(&limited, ip, 25566), Reach::Custom); + assert!(limit_shared(&limited, ip, 25565).is_none()); + // Undone, it's Tailscale's default again. + let undone = unlimit_shared(&limited, ip, 25565).unwrap(); + assert_eq!(reach(&undone, ip, 25565), Reach::Everything); + assert_eq!(undone["ssh"], policy["ssh"]); + + // The older form of the default rule. + let old = json!({ "acls": [{ "action": "accept", "users": ["*"], "ports": ["*:*"] }] }); + assert_eq!(reach(&old, ip, 25565), Reach::Everything); + assert!(limit_shared(&old, ip, 25565).is_some()); + + // Grants. + let grants = json!({ "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }); + let limited = limit_shared(&grants, ip, 25570).unwrap(); + assert_eq!( + limited["grants"][1], + json!({ "src": ["autogroup:shared"], "dst": [ip], "ip": ["tcp:25570"] }) + ); + assert_eq!(reach(&limited, ip, 25570), Reach::ServerOnly); + assert!(unlimit_shared(&limited, ip, 25570).is_some()); + + // Someone's own rules: never rewritten. + let custom = json!({ "acls": [ + { "action": "accept", "src": ["group:family"], "dst": ["*:*"] }, + { "action": "accept", "src": ["*"], "dst": ["*:*"] } + ] }); + assert_eq!(reach(&custom, ip, 25565), Reach::Custom); + assert!(limit_shared(&custom, ip, 25565).is_none()); + assert!(unlimit_shared(&custom, ip, 25565).is_none()); + let both = json!({ "acls": [{ "action": "accept", "src": ["*"], "dst": ["*:*"] }], "grants": [{ "src": ["*"], "dst": ["*"], "ip": ["*"] }] }); + assert_eq!(reach(&both, ip, 25565), Reach::Custom); + assert!(snippet(ip, 25565).contains("\"dst\": [\"100.101.102.103:25565\"]")); +} + +/// What the stand-in API saw: request line, headers, body. +type Seen = Arc>>; + +/// A stand-in for api.tailscale.com answering each request with the next reply (status, ETag, body). +fn stand_in(replies: Vec<(u16, Option<&'static str>, String)>) -> (String, Seen) { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let base = format!("http://{}", listener.local_addr().unwrap()); + let seen: Seen = Arc::default(); + let log = seen.clone(); + std::thread::spawn(move || { + for (code, etag, body) in replies { + let (stream, _) = listener.accept().unwrap(); + let mut reader = BufReader::new(stream.try_clone().unwrap()); + let mut first = String::new(); + reader.read_line(&mut first).unwrap(); + let mut head = String::new(); + loop { + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + if line == "\r\n" || line.is_empty() { + break; + } + head.push_str(&line); + } + let length = head + .lines() + .find_map(|l| { + l.to_ascii_lowercase() + .strip_prefix("content-length:") + .map(|n| n.trim().parse::().unwrap()) + }) + .unwrap_or(0); + let mut sent = vec![0; length]; + reader.read_exact(&mut sent).unwrap(); + log.lock().unwrap().push(( + first.trim().to_string(), + head, + String::from_utf8(sent).unwrap(), + )); + let reason = match code { + 200 => "OK", + 401 => "Unauthorized", + _ => "Error", + }; + let etag = etag.map(|e| format!("ETag: {e}\r\n")).unwrap_or_default(); + let mut stream = stream; + write!( + stream, + "HTTP/1.1 {code} {reason}\r\nContent-Type: application/json\r\n{etag}Content-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + .unwrap(); + } + }); + (base, seen) +} + +#[test] +fn invites_and_access_controls_go_through_the_api() { + let invite = json!([{ + "id": "12345", "created": "2026-10-19T12:00:00Z", "inviteUrl": "https://login.tailscale.com/admin/invite/code1", + "accepted": false + }]); + let accepted = json!([{ + "id": 12346, "created": "2026-10-18T12:00:00Z", "inviteUrl": "https://login.tailscale.com/admin/invite/code2", + "accepted": true, "acceptedBy": { "id": 1, "loginName": "friend@example.com" } + }]); + let (base, seen) = stand_in(vec![ + (200, None, invite.to_string()), + (200, None, accepted.to_string()), + (200, None, String::new()), + (200, Some("\"e1\""), default_acls().to_string()), + (200, None, "{}".into()), + (200, None, "{}".into()), + ( + 401, + None, + json!({ "message": "API token invalid" }).to_string(), + ), + ]); + let api = Api::at(&base, " tskey-api-test\n"); + let made = api.invite("nAbC", None).unwrap(); + assert_eq!(made.url, "https://login.tailscale.com/admin/invite/code1"); + assert!(!made.accepted); + let list = api.invites("nAbC").unwrap(); + assert_eq!(list[0].id, "12346"); + assert_eq!(list[0].accepted_by.as_deref(), Some("friend@example.com")); + api.revoke("12346").unwrap(); + let (policy, etag) = api.policy().unwrap(); + assert_eq!(etag.as_deref(), Some("\"e1\"")); + let limited = limit_shared(&policy, "100.101.102.103", 25565).unwrap(); + api.validate(&limited).unwrap(); + api.set_policy(&limited, etag.as_deref()).unwrap(); + assert!(api.invites("nAbC").unwrap_err().contains("access token")); + + let seen = seen.lock().unwrap(); + let lines: Vec<&str> = seen.iter().map(|(l, _, _)| l.as_str()).collect(); + assert_eq!( + lines, + [ + "POST /api/v2/device/nAbC/device-invites HTTP/1.1", + "GET /api/v2/device/nAbC/device-invites HTTP/1.1", + "DELETE /api/v2/device-invites/12346 HTTP/1.1", + "GET /api/v2/tailnet/-/acl HTTP/1.1", + "POST /api/v2/tailnet/-/acl/validate HTTP/1.1", + "POST /api/v2/tailnet/-/acl HTTP/1.1", + "GET /api/v2/device/nAbC/device-invites HTTP/1.1", + ] + ); + for (_, head, _) in seen.iter() { + assert!( + head.to_ascii_lowercase() + .contains("authorization: bearer tskey-api-test\r\n"), + "{head}" + ); + } + // One friend per invitation, never as an exit node. + let body: Value = serde_json::from_str(&seen[0].2).unwrap(); + assert_eq!(body, json!([{ "multiUse": false, "allowExitNode": false }])); + // The change applies only to the version read. + assert!(seen[5].1.to_ascii_lowercase().contains("if-match: \"e1\"")); + let sent: Value = serde_json::from_str(&seen[5].2).unwrap(); + assert_eq!(sent, limited); +} diff --git a/launcher/src/theme.rs b/launcher/src/theme.rs index 7b7ec3ea6..579259661 100644 --- a/launcher/src/theme.rs +++ b/launcher/src/theme.rs @@ -83,3 +83,47 @@ impl Theme { } } } + +/// How strongly a selected suggestion in a text field is tinted with the accent. +pub const SELECTION: f32 = 0.22; + +#[cfg(test)] +mod tests { + use super::{tokens, SELECTION}; + + /// `top` at `alpha` over `under`, as the GPU blends them. + fn blend(top: u32, under: u32, alpha: f32) -> u32 { + let channel = |shift: u32| { + let (a, b) = ((top >> shift & 0xff) as f32, (under >> shift & 0xff) as f32); + ((a * alpha + b * (1. - alpha)).round() as u32) << shift + }; + channel(16) | channel(8) | channel(0) + } + + /// What the Servers page draws besides text (whose colours horizon-theme's own test holds to + /// WCAG AA on every background): the keyboard focus ring, the borders of a focused or refused + /// field (WCAG 1.4.11 asks 3:1 for those), and text over a selected suggestion. + #[test] + fn marks_and_selections_read_clearly() { + for p in [tokens::LIGHT, tokens::DARK] { + let theme = if p.dark { "dark" } else { "light" }; + for (name, bg) in [ + ("page", p.page), + ("plate_soft", p.plate_soft), + ("plate", p.plate), + ("surface", p.surface), + ] { + let ring = tokens::contrast(p.accent, bg); + assert!(ring >= 3.0, "{theme} focus ring on {name}: {ring:.2}"); + let refused = tokens::contrast(p.danger, bg); + assert!( + refused >= 3.0, + "{theme} refused field on {name}: {refused:.2}" + ); + } + let selection = blend(p.accent, p.surface, SELECTION); + let ratio = tokens::contrast(p.ink, selection); + assert!(ratio >= 4.5, "{theme} text on a selection: {ratio:.2}"); + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java new file mode 100644 index 000000000..8034968a5 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java @@ -0,0 +1,109 @@ +package dev.horizonlab.parity; + +import java.lang.reflect.*; +import java.nio.file.*; +import java.io.PrintWriter; +import net.minecraft.client.*; +import net.minecraft.client.gui.Gui; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.world.entity.player.*; +import net.minecraft.world.item.*; +import net.minecraft.world.level.GameType; + +/** Runs the real key handler through its drop loop; stops before item-use handling. */ +public final class VanillaHeldDropOracle { + static Object unsafe; + static Method allocate; + static Field field(Class type, String name) throws Exception { + var f = type.getDeclaredField(name); + f.setAccessible(true); + return f; + } + static T make(Class type) throws Exception { + return type.cast(allocate.invoke(unsafe, type)); + } + static final class Done extends RuntimeException {} + static final class Client extends Minecraft { + boolean all; + Client() { super(null); } + @Override public boolean hasControlDown() { return all; } + } + static final class Interface extends Gui { + Interface() { super(null, null, null); } + @Override public void handleKeybinds() {} + } + static final class Key extends KeyMapping { + int clicks; + Key() { super("", 0, null); } + @Override public boolean consumeClick() { return clicks-- > 0; } + @Override public boolean isDown() { return false; } + } + static final class Actor extends LocalPlayer { + GameType mode; + Actor() { super(null, null, null, null, null, null, false, null, null); } + @Override public GameType gameMode() { return mode; } + @Override public boolean isUsingItem() { throw new Done(); } + } + static final class Controller extends MultiPlayerGameMode { + int dropped; + Controller() { super(null, null); } + // Controlled dispatch boundary: no networking, swings, statistics or item entities. + @Override public void dropItem(LocalPlayer player, boolean all) { + dropped += player.getInventory().removeFromSelected(all).getCount(); + } + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + Items.AIR.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY); + Items.STONE.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY); + var u = Class.forName("sun.misc.Unsafe"); + unsafe = field(u, "theUnsafe").get(null); + allocate = u.getMethod("allocateInstance", Class.class); + var handler = Minecraft.class.getDeclaredMethod("handleKeybinds"); + handler.setAccessible(true); + var client = make(Client.class); + var options = make(Options.class); + for (var f : Options.class.getDeclaredFields()) { + if (f.getType() == KeyMapping.class && !Modifier.isStatic(f.getModifiers())) { + f.setAccessible(true); + f.set(options, make(Key.class)); + } + } + var hotbar = new KeyMapping[9]; + for (int i = 0; i < 9; i++) hotbar[i] = make(Key.class); + field(Options.class, "keyHotbarSlots").set(options, hotbar); + field(Minecraft.class, "options").set(client, options); + field(Minecraft.class, "gui").set(client, make(Interface.class)); + var actor = make(Actor.class); + var inventory = new Inventory(actor, new PlayerEquipment(actor)); + field(Player.class, "inventory").set(actor, inventory); + field(Minecraft.class, "player").set(client, actor); + var controller = make(Controller.class); + field(Minecraft.class, "gameMode").set(client, controller); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[0])))) { + for (var mode : GameType.values()) for (boolean all : new boolean[]{false, true}) { + for (int selected : new int[]{0, 8}) for (int count : new int[]{0, 1, 4, 64}) { + actor.mode = mode; + client.all = all; + inventory.clearContent(); + inventory.setSelectedSlot(selected); + inventory.setItem(selected, new ItemStack(Items.STONE, count)); + controller.dropped = 0; + // Two consecutive key presses also cover an emptied stack and repeated spectator drops. + for (int press = 0; press < 2; press++) { + ((Key) options.keyDrop).clicks = 1; + try { + handler.invoke(client); + throw new AssertionError("did not reach item-use boundary"); + } catch (InvocationTargetException e) { + if (!(e.getCause() instanceof Done)) throw e; + } + out.println(inventory.getSelectedItem().getCount() + " " + controller.dropped); + } + } + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMarkerParticlesOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMarkerParticlesOracle.java new file mode 100644 index 000000000..efcdaf188 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMarkerParticlesOracle.java @@ -0,0 +1,98 @@ +package dev.horizonlab.parity; + +import com.google.gson.JsonParser; +import java.lang.reflect.Field; +import java.nio.file.Files; +import java.nio.file.Path; +import net.minecraft.client.Minecraft; +import net.minecraft.client.multiplayer.ClientLevel; +import net.minecraft.client.multiplayer.MultiPlayerGameMode; +import net.minecraft.client.player.LocalPlayer; +import net.minecraft.core.BlockPos; +import net.minecraft.core.particles.ParticleOptions; +import net.minecraft.core.registries.BuiltInRegistries; +import net.minecraft.resources.Identifier; +import net.minecraft.util.RandomSource; +import net.minecraft.world.InteractionHand; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.level.GameType; +import net.minecraft.world.level.Level; +import net.minecraft.world.level.block.Block; +import net.minecraft.world.level.block.Blocks; +import net.minecraft.world.level.block.state.BlockState; +import net.minecraft.world.level.material.FluidState; +import net.minecraft.world.level.material.Fluids; + +/** Invoke shipped marker selection and ambient sampling in a dry barrier world. */ +public final class VanillaMarkerParticlesOracle { + static Field field(Class type, String name) throws Exception { + var field = type.getDeclaredField(name); + field.setAccessible(true); + return field; + } + public static final class Player extends LocalPlayer { + ItemStack main, off; + Player() { super(null, null, null, null, null, null, false, null, null); } + @Override public ItemStack getMainHandItem() { return main; } + @Override public ItemStack getItemInHand(InteractionHand hand) { + return hand == InteractionHand.MAIN_HAND ? main : off; + } + } + public static final class Mode extends MultiPlayerGameMode { + GameType mode; + Mode() { super(null, null); } + @Override public GameType getPlayerMode() { return mode; } + } + public static final class MarkerLevel extends ClientLevel { + java.io.BufferedWriter out; + MarkerLevel() { super(null, null, null, null, 0, 0, null, false, 0L, 0); } + @Override public BlockState getBlockState(BlockPos pos) { return Blocks.BARRIER.defaultBlockState(); } + @Override public FluidState getFluidState(BlockPos pos) { return Fluids.EMPTY.defaultFluidState(); } + @Override public void addParticle(ParticleOptions options, double x, double y, double z, + double dx, double dy, double dz) { + if (dx != 0 || dy != 0 || dz != 0) throw new AssertionError("marker velocity"); + try { + out.write("marker " + x + " " + y + " " + z); + out.newLine(); + } catch (java.io.IOException e) { throw new RuntimeException(e); } + } + } + public static void main(String[] args) throws Exception { + net.minecraft.SharedConstants.tryDetectVersion(); + net.minecraft.server.Bootstrap.bootStrap(); + for (var item : BuiltInRegistries.ITEM) { + item.builtInRegistryHolder().bindComponents(net.minecraft.core.component.DataComponentMap.EMPTY); + } + var allocator = Class.forName("sun.misc.Unsafe"); + var unsafe = field(allocator, "theUnsafe").get(null); + var allocate = allocator.getMethod("allocateInstance", Class.class); + var mc = (Minecraft) allocate.invoke(unsafe, Minecraft.class); + var level = (MarkerLevel) allocate.invoke(unsafe, MarkerLevel.class); + var player = (Player) allocate.invoke(unsafe, Player.class); + var mode = (Mode) allocate.invoke(unsafe, Mode.class); + field(ClientLevel.class, "minecraft").set(level, mc); + mc.player = player; + mc.gameMode = mode; + var select = ClientLevel.class.getDeclaredMethod("getMarkerParticleTarget"); + select.setAccessible(true); + try (var out = Files.newBufferedWriter(Path.of(args[1]))) { + level.out = out; + for (var line : Files.readAllLines(Path.of(args[0]))) { + var c = JsonParser.parseString(line).getAsJsonObject(); + mode.mode = GameType.byName(c.get("mode").getAsString()); + player.main = new ItemStack(BuiltInRegistries.ITEM.getValue( + Identifier.parse("minecraft:" + c.get("main").getAsString())), c.get("count").getAsInt()); + player.off = new ItemStack(BuiltInRegistries.ITEM.getValue( + Identifier.parse("minecraft:" + c.get("off").getAsString()))); + var block = (Block) select.invoke(level); + out.write(block == null ? "none" : BuiltInRegistries.BLOCK.getKey(block).toString()); + out.newLine(); + var random = RandomSource.create(1057); + field(Level.class, "random").set(level, random); + level.animateTick(0, 64, 0); + out.write("next " + random.nextInt()); + out.newLine(); + } + } + } +} diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 58c2eb94f..5c784fdfe 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -35,6 +35,8 @@ public final class VanillaMenuOracle { static java.lang.reflect.Method allocate; static RecipeManager recipes; static final List drops = new ArrayList<>(); + /** onEquipItem calls that change the item (its sound and game event): slot and new stack. */ + static final List equips = new ArrayList<>(); /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; @@ -105,7 +107,9 @@ public final class VanillaMenuOracle { @Override public EntityType getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; } @Override public net.minecraft.core.Holder> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); } @Override public boolean canUseSlot(EquipmentSlot slot) { return true; } - @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { } + @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { + if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now)); + } @Override public boolean hasDisconnected() { return false; } @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); @@ -193,6 +197,11 @@ public final class VanillaMenuOracle { return out.toString(); } + /** {@link #state} and what was equipped: the menu_click harness's line (place_recipe prints {@code state}). */ + static String clickState(AbstractContainerMenu menu, Inventory inv) throws Exception { + return state(menu, inv) + " | " + String.join(";", equips); + } + public static void main(String[] args) throws Exception { ParityData.init(); var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); @@ -207,6 +216,7 @@ public final class VanillaMenuOracle { var f = JsonParser.parseString(line).getAsJsonObject(); try { drops.clear(); + equips.clear(); var world = make(World.class); world.server = make(Server.class); var player = make(FakePlayer.class); @@ -228,7 +238,8 @@ public final class VanillaMenuOracle { var dataJson = f.getAsJsonArray("data"); for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); - out.println("init " + state(menu, inv)); + equips.clear(); + out.println("init " + clickState(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); int slot = op.get(0).getAsInt(); @@ -237,13 +248,13 @@ public final class VanillaMenuOracle { if (kind.equals("BUTTON")) { // ServerGamePacketListenerImpl.handleContainerButtonClick if (menu.clickMenuButton(player, slot)) menu.broadcastChanges(); - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } if (kind.equals("SLOT_STATE")) { // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } if (kind.equals("QUICK_MOVE_ALL")) { @@ -259,7 +270,7 @@ public final class VanillaMenuOracle { } } } - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } var input = ContainerInput.valueOf(kind); @@ -271,7 +282,7 @@ public final class VanillaMenuOracle { if (System.getenv("MENU_TRACE") != null) cause.printStackTrace(); continue; } - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); } out.println("end"); } catch (Throwable e) { diff --git a/tests/test_pr_ready.py b/tests/test_pr_ready.py index c5b1b4815..c10e7b2ac 100644 --- a/tests/test_pr_ready.py +++ b/tests/test_pr_ready.py @@ -1,4 +1,5 @@ import argparse +import json import unittest from unittest import mock @@ -6,6 +7,8 @@ from tools import pr_ready PACKAGES = {"horizon-core": "crates/horizon-core", "horizon-client": "crates/horizon-client", "horizon-theme": "crates/horizon-theme", "xtask": "xtask"} +LIBRARIES = set(PACKAGES) - {"xtask"} +DEPENDENCIES = {"horizon-client": {"horizon-core"}} def args(host="local", quick=False): @@ -38,6 +41,100 @@ class PrReadyTests(unittest.TestCase): self.assertFalse(pr_ready.launcher_rust("launcher/README.md")) self.assertFalse(pr_ready.launcher_rust("crates/horizon-client/src/game.rs")) + def test_crate_checks_do_not_link_unrelated_examples(self): + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(quick=True), "origin/main", {"crates/horizon-client/src/game.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) + by_name = {step.name: step for step in steps} + self.assertEqual(by_name["clippy"].command, + "cargo clippy -p horizon-client --all-targets --locked -- -D warnings") + self.assertEqual(by_name["tests: horizon-client"].command, + "cargo test --locked -p horizon-client --tests") + self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-client --doc") + self.assertIsNone(by_name["doc tests"].status) + + def test_shared_rust_configuration_keeps_workspace_coverage(self): + for path in sorted(pr_ready.ROOT_RUST | {".cargo/config.toml", "crates/unknown/src/lib.rs"}): + with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) + by_name = {step.name: step for step in steps} + self.assertEqual(by_name["clippy"].command, + "cargo clippy --workspace --all-targets --locked -- -D warnings") + self.assertEqual(by_name["tests: workspace"].command, + "cargo test --locked --workspace --tests") + self.assertEqual(by_name["doc tests"].command, "cargo test --locked --workspace --doc") + + def test_non_rust_changes_skip_workspace_checks(self): + for path in ("README.md", "tools/pr_ready.py", "launcher/src/main.rs"): + with self.subTest(path=path), mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(quick=True), "origin/main", {path}, PACKAGES, LIBRARIES, DEPENDENCIES) + by_name = {step.name: step for step in steps} + for name in ("clippy", "tests", "doc tests"): + self.assertEqual(by_name[name].status, "skip") + + def test_multiple_touched_crates_share_the_same_check_scope(self): + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(), "origin/main", + {"crates/horizon-core/src/lib.rs", "crates/horizon-client/examples/probe.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) + for step in steps: + if step.name in ("clippy", "tests: horizon-client, horizon-core", "doc tests"): + self.assertIn("-p horizon-client -p horizon-core", step.command) + self.assertIsNone(step.status) + + def test_binary_only_crates_skip_doc_tests(self): + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(), "origin/main", {"xtask/src/main.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) + by_name = {step.name: step for step in steps} + self.assertEqual(by_name["tests: xtask"].command, "cargo test --locked -p xtask --tests") + self.assertIsNone(by_name["tests: xtask"].status) + self.assertEqual(by_name["doc tests"].status, "skip") + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(), "origin/main", + {"xtask/src/main.rs", "crates/horizon-core/src/lib.rs"}, PACKAGES, LIBRARIES, DEPENDENCIES) + by_name = {step.name: step for step in steps} + self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p horizon-core --doc") + + def test_clippy_checks_transitive_consumers_but_tests_only_touched_crates(self): + packages = {name: f"crates/{name}" for name in ("core", "world", "client", "unrelated")} + dependencies = {"world": {"core"}, "client": {"world"}, "unrelated": set()} + with mock.patch.object(pr_ready, "affected_here", return_value=[]): + steps = pr_ready.plan(args(), "origin/main", {"crates/core/src/lib.rs"}, + packages, set(packages), dependencies) + by_name = {step.name: step for step in steps} + self.assertEqual(by_name["clippy"].command, + "cargo clippy -p client -p core -p world --all-targets --locked -- -D warnings") + self.assertEqual(by_name["tests: core"].command, "cargo test --locked -p core --tests") + self.assertEqual(by_name["doc tests"].command, "cargo test --locked -p core --doc") + + def test_dependent_scope_handles_cycles_and_multiple_changed_crates(self): + dependencies = {"a": {"b"}, "b": {"a"}, "c": {"b"}, "d": set()} + self.assertEqual(pr_ready.dependent_crates(["a"], dependencies), ["a", "b", "c"]) + self.assertEqual(pr_ready.dependent_crates(["a", "d"], dependencies), ["a", "b", "c", "d"]) + self.assertEqual(pr_ready.dependent_crates([], dependencies), []) + self.assertIsNone(pr_ready.dependent_crates(None, dependencies)) + + def test_metadata_includes_renamed_optional_platform_build_and_dev_consumers(self): + core = str(pr_ready.ROOT / "crates/core") + metadata = {"workspace_members": ["core", "optional", "build", "dev"], "packages": [ + {"id": "core", "name": "core", "manifest_path": core + "/Cargo.toml", + "targets": [{"kind": ["lib"]}], "dependencies": []}, + ]} + for name, kind in (("optional", None), ("build", "build"), ("dev", "dev")): + metadata["packages"].append({ + "id": name, "name": name, "manifest_path": str(pr_ready.ROOT / f"crates/{name}/Cargo.toml"), + "targets": [{"kind": ["bin"]}], "dependencies": [ + {"name": "core", "rename": "alias", "path": core, "kind": kind, + "optional": name == "optional", "target": "cfg(windows)"}, + {"name": "external", "path": None}, + ], + }) + # A path dependency outside this workspace must not become a selectable package. + metadata["packages"].append({"id": "outside", "name": "outside", "manifest_path": "/outside/Cargo.toml"}) + with mock.patch.object(pr_ready.subprocess, "run", return_value=mock.Mock(stdout=json.dumps(metadata))): + directories, libraries, dependencies = pr_ready.packages() + self.assertEqual(set(directories), {"core", "optional", "build", "dev"}) + self.assertEqual(libraries, {"core"}) + self.assertEqual(pr_ready.dependent_crates(["core"], dependencies), ["build", "core", "dev", "optional"]) + def test_scope_warns_on_size_and_mixed_areas(self): self.assertEqual(pr_ready.scope_warnings({"crates/horizon-client/src/game.rs", "tools/test_food_parity.py", "mods/horizon/src/test/java/dev/horizonlab/parity/X.java", @@ -85,7 +182,7 @@ class PrReadyTests(unittest.TestCase): def test_harnesses_are_listed_when_they_cannot_run(self): changed = {"crates/horizon-world/src/food.rs"} with mock.patch.object(pr_ready, "affected_here", return_value=["food", "light"]): - steps = pr_ready.plan(args(quick=True), "origin/main", changed, {"horizon-world": "crates/horizon-world"}) + steps = pr_ready.plan(args(quick=True), "origin/main", changed, {"horizon-world": "crates/horizon-world"}, {"horizon-world"}, {}) harness = steps[-1] self.assertEqual(harness.status, "list") self.assertIn("2 affected, to run in CI (--quick): food, light", harness.detail) @@ -94,7 +191,7 @@ class PrReadyTests(unittest.TestCase): self.assertEqual(by_name["launcher clippy"].status, "skip") self.assertIsNone(by_name["clippy"].status) with mock.patch.object(pr_ready, "affected_here", return_value=["food"]): - steps = pr_ready.plan(args(host="macmini"), "origin/main", changed, {"horizon-world": "crates/horizon-world"}) + steps = pr_ready.plan(args(host="macmini"), "origin/main", changed, {"horizon-world": "crates/horizon-world"}, {"horizon-world"}, {}) self.assertIn("--changed-files", steps[-1].command) self.assertIn("crates/horizon-world/src/food.rs", steps[-1].command) diff --git a/tests/test_release_channels.py b/tests/test_release_channels.py new file mode 100644 index 000000000..0b27ae8a3 --- /dev/null +++ b/tests/test_release_channels.py @@ -0,0 +1,107 @@ +import datetime as dt +import unittest + +from tools import release_channels as channels +from tools import release_train as train + +NOW = dt.datetime(2026, 10, 19, 18, 0, tzinfo=dt.timezone.utc) + + +def release(tag, hours_ago, prerelease=True, smoke=True, draft=False): + published = (NOW - dt.timedelta(hours=hours_ago)).isoformat().replace("+00:00", "Z") + assets = [{"name": "horizon-linux-x86_64.tar.gz"}] + ([{"name": channels.SMOKE_ASSET}] if smoke else []) + return {"tag_name": tag, "published_at": published, "prerelease": prerelease, "draft": draft, "assets": assets} + + +def blocker(number, title, body="", state="open", reason=None, closed_hours_ago=None): + closed = None if closed_hours_ago is None else (NOW - dt.timedelta(hours=closed_hours_ago)).isoformat() + return {"number": number, "title": title, "body": body, "state": state, "state_reason": reason, "closed_at": closed} + + +STABLE = release("v2026.10.18.04", 30, prerelease=False) + + +class ReleaseChannelTests(unittest.TestCase): + def test_the_newest_beta_out_six_hours_with_a_smoke_test_is_promoted(self): + releases = [STABLE, release("v2026.10.19", 9), release("v2026.10.19.01", 7), release("v2026.10.19.02", 2)] + chosen, why = channels.choose(releases, [], NOW) + self.assertEqual(chosen["tag_name"], "v2026.10.19.01") + self.assertIn("6 h", why) + + def test_nothing_is_due_before_six_hours(self): + chosen, why = channels.choose([STABLE, release("v2026.10.19", 5.5)], [], NOW) + self.assertIsNone(chosen) + self.assertIn("0 h 30 min to go", why) + + def test_a_beta_without_its_smoke_test_waits_for_a_hand(self): + releases = [STABLE, release("v2026.10.19", 8, smoke=False)] + self.assertIsNone(channels.choose(releases, [], NOW)[0]) + self.assertIsNone(channels.choose(releases, [], NOW, tag="v2026.10.19")[0]) + self.assertEqual(channels.choose(releases, [], NOW, tag="v2026.10.19", force=True)[0]["tag_name"], "v2026.10.19") + + def test_by_hand_skips_the_wait_but_not_a_blocker(self): + releases = [STABLE, release("v2026.10.19.02", 1)] + self.assertEqual(channels.choose(releases, [], NOW, tag="v2026.10.19.02")[0]["tag_name"], "v2026.10.19.02") + blocked = [blocker(5, "Crash on start in 2026.10.19.2")] + chosen, why = channels.choose(releases, blocked, NOW, tag="v2026.10.19.02") + self.assertIsNone(chosen) + self.assertIn("#5", why) + self.assertIsNotNone(channels.choose(releases, blocked, NOW, tag="v2026.10.19.02", force=True)[0]) + + def test_stable_releases_and_drafts_are_never_promoted(self): + self.assertIsNone(channels.choose([STABLE], [], NOW, tag=STABLE["tag_name"])[0]) + withdrawn = release("v2026.10.19", 9, draft=True) + self.assertIsNone(channels.choose([STABLE, withdrawn], [], NOW)[0]) + older = release("v2026.10.18.03", 40) + self.assertIsNone(channels.choose([STABLE, older], [], NOW)[0]) + + def test_an_open_blocker_holds_every_beta_whatever_its_text_says(self): + releases = [STABLE, release("v2026.10.19", 12), release("v2026.10.19.01", 10), release("v2026.10.19.02", 8)] + # The issue's author can edit its text after it is labelled: naming a later version must not free a beta. + for text in ("Something is badly wrong", "Only in v2099.01.01", "Since v2026.10.19.01 the chests…"): + chosen, why = channels.choose(releases, [blocker(7, text, body=text)], NOW) + self.assertIsNone(chosen, text) + self.assertIn("release-blocker #7", why) + + def test_a_fixed_blocker_still_holds_the_betas_published_before_the_fix(self): + fixed = blocker(9, "Crash", state="closed", reason="completed", closed_hours_ago=7.5) + releases = [STABLE, release("v2026.10.19", 12), release("v2026.10.19.01", 7)] + self.assertEqual(channels.choose(releases, [fixed], NOW)[0]["tag_name"], "v2026.10.19.01") + self.assertIsNone(channels.choose(releases[:2], [fixed], NOW)[0]) + not_planned = blocker(10, "Crash", state="closed", reason="not_planned", closed_hours_ago=1) + self.assertEqual(channels.choose(releases[:2], [not_planned], NOW)[0]["tag_name"], "v2026.10.19") + + def test_force_never_moves_latest_backwards(self): + # horizon-server update and install.sh download GitHub's latest: an older beta must never become it. + older = release("v2026.10.18.03", 40, smoke=False) + chosen, why = channels.choose([STABLE, older], [blocker(3, "x")], NOW, tag="v2026.10.18.03", force=True) + self.assertIsNone(chosen) + self.assertIn("not newer than the stable v2026.10.18.04", why) + same = release("v2026.10.18.04", 30, prerelease=False) + self.assertIsNone(channels.choose([same], [], NOW, tag="v2026.10.18.04", force=True)[0]) + + def test_a_stall_is_reported_once_the_oldest_waiting_beta_is_a_day_old(self): + self.assertIsNone(channels.stalled([STABLE, release("v2026.10.19", 23), release("v2026.10.19.01", 2)], NOW)) + releases = [STABLE, release("v2026.10.19", 25), release("v2026.10.19.01", 2)] + oldest, age = channels.stalled(releases, NOW) + self.assertEqual(oldest["tag_name"], "v2026.10.19") + title, body = channels.stall_issue(releases, (oldest, age), "no beta is due (release-blocker #4)") + self.assertEqual(title, "Promotion to stable has stalled: v2026.10.19 has waited 25 h") + self.assertIn("v2026.10.18.04", body) + self.assertIn("release-blocker #4", body) + # Betas older than the stable release are contained in it: they aren't waiting. + self.assertIsNone(channels.stalled([STABLE, release("v2026.10.18.03", 40)], NOW)) + self.assertIsNone(channels.stalled([STABLE], NOW)) + + def test_beta_notes_say_so_and_stable_notes_do_not(self): + pr = {"number": 1, "title": "Fix a thing", "labels": [], "paths": ["crates/x.rs"], "issues": [], "author": "ludovic111"} + _, beta = train.notes("game", "v2026.10.19", [pr], [], beta=True) + _, stable = train.notes("game", "v2026.10.19", [pr], [], beta=False) + self.assertIn("beta build", beta) + self.assertNotIn("beta build", stable) + _, launcher = train.notes("launcher", "launcher-v0.9.0", [pr], [], beta=True) + self.assertNotIn("beta build", launcher) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/ci/new_release_key.sh b/tools/ci/new_release_key.sh new file mode 100755 index 000000000..dc2a23742 --- /dev/null +++ b/tools/ci/new_release_key.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Makes a release signing key (docs/security.md, "Signed updates"): the private key goes straight from +# horizon-release-sign into the `release` environment's secret through a pipe (never on disk, never printed, +# never in the Agents vault); the public key is printed for crates/horizon-release-sign/release-keys.txt. +# Needs a gh login that may write the repository's environment secrets (the maintainer's), and the `release` +# environment to exist. +# +# tools/ci/new_release_key.sh # the first key: RELEASE_SIGNING_KEY +# tools/ci/new_release_key.sh RELEASE_SIGNING_KEY_NEXT # rotating: the next key, signed with alongside +set -euo pipefail +secret=${1:-RELEASE_SIGNING_KEY} +case "$secret" in RELEASE_SIGNING_KEY|RELEASE_SIGNING_KEY_NEXT) ;; *) echo "unknown secret $secret" >&2; exit 2 ;; esac +repo=${GITHUB_REPOSITORY:-ludovic111/horizon} +cd "$(dirname "$0")/../.." +gh api "repos/$repo/environments/release" > /dev/null || { + echo "The release environment doesn't exist yet: create it first (docs/security.md)." >&2; exit 1; } +public=$(mktemp) +trap 'rm -f "$public"' EXIT +cargo run --quiet --locked -p horizon-release-sign -- keygen --public-out "$public" \ + | gh secret set "$secret" --env release --repo "$repo" +echo "$secret is set in $repo's release environment. Its public key, for crates/horizon-release-sign/release-keys.txt:" +cat "$public" diff --git a/tools/ci/protect_pipeline.sh b/tools/ci/protect_pipeline.sh new file mode 100755 index 000000000..1b97bb35e --- /dev/null +++ b/tools/ci/protect_pipeline.sh @@ -0,0 +1,54 @@ +#!/usr/bin/env bash +# Makes main's branch protection require the code owners' review (docs/security.md): a pull request that +# changes a file .github/CODEOWNERS lists waits for Ludovic's approval; every other one still merges as soon as +# `verify` passes (no approvals are required otherwise). Approvals are dismissed by a later push. Everything +# else in the protection (the required `verify` from GitHub Actions, admins included) is kept as it is. +# +# Ludovic is the only code owner, and GitHub never counts an author's approval of their own pull request, so his +# own pull requests to listed files could never merge. He is therefore the one account allowed to bypass the +# pull-request rules (bypass_pull_request_allowances). The alternative, not enforcing the protection on admins, +# would also let an admin merge without `verify`; here `verify` stays required for everyone, admins and Ludovic +# included (enforce_admins stays on), and only the review requirement has an exception, for him alone. +# +# Apply it only once agents open, push and merge pull requests as the horizon-agent GitHub App, not as ludovic111: +# while agents use his token, his bypass is theirs too, and their changes to listed files would skip his review. +# +# tools/ci/protect_pipeline.sh # print the protection it would set, change nothing +# tools/ci/protect_pipeline.sh --apply # set it (needs the maintainer's admin login) +set -euo pipefail +repo=${GITHUB_REPOSITORY:-ludovic111/horizon} +api="repos/$repo/branches/main/protection" +body=$(gh api "$api" | jq '{ + required_status_checks: (.required_status_checks + | {strict, checks: [.checks[] | {context, app_id}]}), + enforce_admins: .enforce_admins.enabled, + required_pull_request_reviews: { + require_code_owner_reviews: true, + required_approving_review_count: 0, + dismiss_stale_reviews: true, + require_last_push_approval: false, + bypass_pull_request_allowances: {users: ["ludovic111"], teams: [], apps: []} + }, + restrictions: null, + required_linear_history: .required_linear_history.enabled, + allow_force_pushes: .allow_force_pushes.enabled, + allow_deletions: .allow_deletions.enabled, + required_conversation_resolution: .required_conversation_resolution.enabled, + lock_branch: .lock_branch.enabled, + allow_fork_syncing: .allow_fork_syncing.enabled +}') +echo "$body" +if [[ "${1:-}" == --apply ]]; then + gh api -X PUT "$api" --input - <<< "$body" > /dev/null + set_now=$(gh api "$api" --jq '[.required_pull_request_reviews.require_code_owner_reviews, + .enforce_admins.enabled, ([.required_pull_request_reviews.bypass_pull_request_allowances.users[]?.login] + | index("ludovic111") != null), ([.required_status_checks.checks[].context] | index("verify") != null)] + | map(tostring) | join(" ")') + if [[ "$set_now" != "true true true true" ]]; then + echo "GitHub didn't keep everything (code owners, admins enforced, Ludovic's bypass, verify): $set_now" >&2 + exit 1 + fi + echo "main now requires code owners' reviews; Ludovic may bypass them; verify is required for everyone." +else + echo "(not applied: run with --apply)" +fi diff --git a/tools/ci/sign_release.sh b/tools/ci/sign_release.sh new file mode 100755 index 000000000..4fa03ebd1 --- /dev/null +++ b/tools/ci/sign_release.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +# Signs a release (docs/release-flow.md, "Signed checksums"): writes SHA256SUMS for the files given, then +# SHA256SUMS.sig beside them, one base64 Ed25519 signature per line over "horizon release \n" + SHA256SUMS, +# for every key set in RELEASE_SIGNING_KEY and RELEASE_SIGNING_KEY_NEXT (base64 PKCS#8, the `release` +# environment's secrets). The job that runs this holds the private keys, so it runs nothing from the repository +# but this file, which calls only the runner's sha256sum and OpenSSL; the publish job then checks the result +# with horizon-release-sign, as launchers do. +# EPHEMERAL=yes (dry runs) signs with a throwaway key instead and writes its public key to ephemeral.pub. +# tools/ci/sign_release.sh v2026.10.19 dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip ... +set -euo pipefail +tag=$1; shift +dir=$(dirname "$1") +openssl=${OPENSSL:-openssl} +if command -v sha256sum > /dev/null; then sha=(sha256sum); else sha=(shasum -a 256); fi +umask 077 +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +names=() +for file in "$@"; do + [[ "$(dirname "$file")" == "$dir" ]] || { echo "$file: every file must be in $dir" >&2; exit 1; } + names+=("$(basename "$file")") +done +(cd "$dir" && "${sha[@]}" -- "${names[@]}") > "$dir/SHA256SUMS" +{ printf 'horizon release %s\n' "$tag"; cat "$dir/SHA256SUMS"; } > "$work/message" +rm -f "$dir/SHA256SUMS.sig" "$dir/ephemeral.pub" + +sign_with() { # the key file in $1 + "$openssl" pkeyutl -sign -rawin -inkey "$1" -keyform DER -in "$work/message" -out "$work/signature" + # base64 of the 64 bytes on one line (GNU base64 wraps at 76 characters). + base64 < "$work/signature" | tr -d '\n' >> "$dir/SHA256SUMS.sig" + echo >> "$dir/SHA256SUMS.sig" + rm -f "$1" "$work/signature" +} + +if [[ -n "${EPHEMERAL:-}" ]]; then + "$openssl" genpkey -algorithm ed25519 -outform DER -out "$work/key" + "$openssl" pkey -inform DER -in "$work/key" -pubout -outform DER | tail -c 32 | base64 > "$dir/ephemeral.pub" + sign_with "$work/key" +else + for name in RELEASE_SIGNING_KEY RELEASE_SIGNING_KEY_NEXT; do + if [[ -n "${!name:-}" ]]; then + # From the environment into a private temporary file: never an argument, never printed. + printf '%s' "${!name}" | base64 --decode > "$work/key" + sign_with "$work/key" + fi + done +fi +echo "$tag: SHA256SUMS lists ${#names[@]} files; $( [[ -f "$dir/SHA256SUMS.sig" ]] && echo "signed with $(wc -l < "$dir/SHA256SUMS.sig" | tr -d ' ') key(s)" || echo "no signing key, so unsigned")" diff --git a/tools/command_exec_corpus.py b/tools/command_exec_corpus.py index 166ecaf70..02311beda 100644 --- a/tools/command_exec_corpus.py +++ b/tools/command_exec_corpus.py @@ -401,7 +401,11 @@ def execute(): {'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 ~ ~ ~'), + # Back to the terrain loaded since the start (x and z scaled by 8: 12 230 4). The fresh + # ocean chunks at 644 100 -316 broke some of their kelp and seagrass while they loaded, + # on some runs only (vanilla loads chunks asynchronously): that rolled those blocks' loot + # and added their random sequences to the count of /random reset *. + cmd('/execute in minecraft:the_nether positioned 1 230 0 in minecraft:overworld run tp @s ~ ~ ~'), {'op': 'settle'}, cmd('/execute if dimension minecraft:overworld run say relative dimension'), cmd('/data get entity @s Pos'), diff --git a/tools/hud_parity_cases.py b/tools/hud_parity_cases.py index 3a0b10a45..7d1f50333 100644 --- a/tools/hud_parity_cases.py +++ b/tools/hud_parity_cases.py @@ -135,7 +135,10 @@ def jump(rng, n): 'jumpScale': rng.choice([0.0, 1.0, 0.4, 0.001, round(rng.random(), 4)])} -OWNERS = ['Alex', 'steve', 'Zed', 'bob', 'Bobby', 'ÉLodie', 'élan', '#hidden', 'x', 'LongPlayerName_123', 'Mia', '_under'] +# Servers' sidebars use legacy formatting codes in fake owners, team affixes and titles (#937): +# a code, an unknown code, `§r` and a trailing lone `§`. +OWNERS = ['Alex', 'steve', 'Zed', 'bob', 'Bobby', 'ÉLodie', 'élan', '#hidden', 'x', 'LongPlayerName_123', 'Mia', '_under', + '§1§r', '§a§lPro§r name', 'end§', '§zodd§Rcase'] FORMATS = [None, None, None, {'type': 'blank'}, {'type': 'fixed', 'value': {'text': 'FIX', 'color': 'aqua'}}, {'type': 'styled', 'style': {'color': 'gold', 'bold': True}}, {'type': 'styled', 'style': {}}] @@ -150,12 +153,14 @@ def sidebar(rng, n): 'format': rng.choice(FORMATS)} for o in owners] teams = [] for t in range(rng.choice([0, 0, 1, 2])): - teams.append({'name': f'team{t}', 'prefix': rng.choice([{'text': ''}, {'text': '[A] '}, {'text': '<', 'color': 'red'}]), - 'suffix': rng.choice([{'text': ''}, {'text': ' *'}]), + teams.append({'name': f'team{t}', 'prefix': rng.choice([{'text': ''}, {'text': '[A] '}, {'text': '<', 'color': 'red'}, + {'text': '§c§lRed §r', 'color': 'blue'}]), + 'suffix': rng.choice([{'text': ''}, {'text': ' *'}, {'text': ' §7(§e5§7)§'}]), 'color': rng.choice([None, 'red', 'blue', 'gold', 'white']), 'members': [o for o in owners if rng.random() < 0.3]}) return {**screen(rng), **backdrop(rng), - 'objective': {'display': rng.choice(TITLES + [{'text': 'Kills'}]), 'format': rng.choice(FORMATS)}, + 'objective': {'display': rng.choice(TITLES + [{'text': 'Kills'}, {'text': '§e§lANTICHEAT §7test'}]), + 'format': rng.choice(FORMATS + [{'type': 'fixed', 'value': {'text': '§a12§'}}])}, 'scores': scores, 'teams': teams} diff --git a/tools/pr_ready.py b/tools/pr_ready.py index 9ec216fea..e3e317ef8 100755 --- a/tools/pr_ready.py +++ b/tools/pr_ready.py @@ -12,6 +12,9 @@ same way when it, horizon-prepare or horizon-theme changed; website/src/tokens.c Cargo.lock changing only with a Cargo.toml; the Python tests and the public-tree check; and the vanilla harnesses the changes can affect, picked as CI's parity job picks them (tools/parity.py --changed). Harnesses run where the vanilla data is (a prepared .local/ here, or the Mac mini); elsewhere they are listed for CI. +Clippy checks all targets of touched crates and their transitive workspace dependents, including examples. +Tests select library, binary and integration targets explicitly, followed by doc tests, so unrelated example +executables are not built and linked again. It prints one Markdown block for the pull request's body (stdout) and exits non-zero when a check fails. Progress, and the end of a failed check's output, go to stderr (--verbose: all of it). @@ -89,7 +92,7 @@ def launcher_rust(path): def touched_crates(paths, packages): """Workspace packages to test for these paths ({name: directory}), or None for the whole workspace.""" - if any(path in ("Cargo.toml", "Cargo.lock") or path.startswith(".cargo/") for path in paths): + if any(path in ROOT_RUST or path.startswith(".cargo/") for path in paths): return None crates = set() for path in paths: @@ -195,14 +198,37 @@ def line_counts(base, changed): def packages(): - """The main workspace's packages and their directories, from Cargo's metadata.""" + """Workspace directories, libraries and path dependencies, including optional/build/dev dependencies.""" try: output = subprocess.run(["cargo", "metadata", "--no-deps", "--format-version", "1"], cwd=ROOT, capture_output=True, text=True, check=True).stdout except (OSError, subprocess.CalledProcessError) as error: sys.exit(f"pr_ready: cargo metadata failed: {getattr(error, 'stderr', error)}") - return {package["name"]: Path(package["manifest_path"]).parent.relative_to(ROOT).as_posix() - for package in json.loads(output)["packages"]} + metadata = json.loads(output) + members = set(metadata["workspace_members"]) + workspace = [package for package in metadata["packages"] if package["id"] in members] + directories = {package["name"]: Path(package["manifest_path"]).parent.relative_to(ROOT).as_posix() + for package in workspace} + libraries = {package["name"] for package in workspace + if any("lib" in target["kind"] for target in package["targets"])} + names_by_path = {Path(package["manifest_path"]).parent.resolve(): package["name"] for package in workspace} + dependencies = {package["name"]: {names_by_path[path] for dependency in package["dependencies"] + if dependency.get("path") and + (path := Path(dependency["path"]).resolve()) in names_by_path} + for package in workspace} + return directories, libraries, dependencies + + +def dependent_crates(crates, dependencies): + """Include every workspace consumer, even through renamed or feature-gated dependencies.""" + if crates is None: + return None + selected = set(crates) + while True: + consumers = {name for name, used in dependencies.items() if selected.intersection(used)} + if consumers <= selected: + return sorted(selected) + selected.update(consumers) def prepare_key(): @@ -248,12 +274,22 @@ def parity_summary(output): return text -def plan(args, base, changed, crates_of): +def plan(args, base, changed, crates_of, libraries, dependencies): """The checks for these changed files, in the order they run.""" rust = any(workspace_rust(path) for path in changed) launcher = any(launcher_rust(path) for path in changed) python = any(path.endswith(".py") or path.startswith(("tests/", "tools/")) for path in changed) crates = touched_crates(changed, crates_of) if rust or TOKENS in changed else [] + # An unrecognised Rust path must not silently skip validation. + if rust and crates == []: + crates = None + selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in crates) + clippy_crates = dependent_crates(crates, dependencies) + clippy_selection = "--workspace" if clippy_crates is None else " ".join( + f"-p {shlex.quote(c)}" for c in clippy_crates) + test_skip = None if crates is None or crates else "no crate touched" + doc_crates = sorted(libraries if crates is None else libraries.intersection(crates)) + doc_selection = "--workspace" if crates is None else " ".join(f"-p {shlex.quote(c)}" for c in doc_crates) no_rust = "no Rust change" steps = [ Step("Cargo.lock", where="git"), @@ -261,10 +297,13 @@ def plan(args, base, changed, crates_of): Step("Python tests", "python3 -m unittest discover -s tests", where="here", skip=None if python else "no Python change", summary=unittest_passed), Step("rustfmt", "cargo fmt --all -- --check", skip=None if rust else no_rust), - Step("clippy", "cargo clippy --workspace --all-targets --locked -- -D warnings", skip=None if rust else no_rust), + Step("clippy", f"cargo clippy {clippy_selection} --all-targets --locked -- -D warnings", + skip=None if rust else no_rust), Step("tests" + (": workspace" if crates is None else f": {', '.join(crates)}" if crates else ""), - "cargo test --locked " + ("--workspace" if crates is None else " ".join(f"-p {c}" for c in crates or [])), - skip=None if crates is None or crates else "no crate touched", summary=tests_passed), + f"cargo test --locked {selection} --tests", + skip=test_skip, summary=tests_passed), + Step("doc tests", f"cargo test --locked {doc_selection} --doc", + skip=test_skip or (None if doc_crates else "no library touched"), summary=tests_passed), Step("tokens.css up to date", "cargo test --locked -p horizon-theme --lib website_tokens_are_up_to_date", skip=None if any(p.startswith(("crates/horizon-theme/", "xtask/")) or p == TOKENS for p in changed) else "theme untouched"), @@ -448,7 +487,9 @@ def main(): parser.error(f"no merge base with {args.base} (git fetch?)") merge_base = git("merge-base", "HEAD", args.base).strip() counts = line_counts(merge_base, changed) - steps = plan(args, args.base, changed, packages() if any(workspace_rust(p) for p in changed) or TOKENS in changed else {}) + crates_of, libraries, dependencies = packages() if any(workspace_rust(p) for p in changed) or TOKENS in changed \ + else ({}, set(), {}) + steps = plan(args, args.base, changed, crates_of, libraries, dependencies) print(f"pr_ready: {len(changed)} files changed since {args.base}; checks on {args.host}", file=sys.stderr, flush=True) lock = steps[0] diff --git a/tools/release_channels.py b/tools/release_channels.py new file mode 100644 index 000000000..3ae58a84b --- /dev/null +++ b/tools/release_channels.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Promotes Horizon's beta game releases to stable (.github/workflows/promote.yml, docs/release-flow.md). + + python3 tools/release_channels.py promote # the newest beta that is due, if any + python3 tools/release_channels.py promote --tag v2026.10.19.03 # that beta now (by hand) + python3 tools/release_channels.py promote --tag v2026.10.19.03 --force # even if blocked or untested + python3 tools/release_channels.py promote --dry-run # say what would happen, change nothing + +Every game release goes out as a beta (a GitHub pre-release). A beta is due for stable when: +- it is newer than the stable release (GitHub's "latest", which launchers and servers install by default), +- it has been out PROMOTE_AFTER (6 hours) without trouble; a promotion by hand (--tag) skips the wait, +- its release smoke test passed: release.yml attaches smoke-test.json only after the Mac mini ran the game, +- and no issue labelled release-blocker covers it. An open blocker holds every beta; one closed as completed keeps + holding the betas published before it closed (they still have the bug); one closed as not planned holds nothing. + Only people who can triage the repository can add the label, and the issue's text is never read: whoever wrote + the issue could edit it afterwards, so it can't decide which betas go out. + +The newest due beta is promoted: marked stable and latest, with notes covering everything since the previous +stable release (tools/release_train.py notes --stable). Older betas stay betas: the stable one contains them. +Nothing older than the current stable release is ever promoted, even with --force: GitHub's "latest" is what +horizon-server update and install.sh download, and it only moves forward. + +When the oldest beta newer than the stable release has waited STALL_AFTER (24 hours), promotion has stalled +(blocked, smoke tests not running, the schedule off): an issue says so, and is closed once a beta is promoted. +""" + +import argparse +import datetime as dt +import json +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + +ROOT = Path(__file__).resolve().parents[1] +REPO = os.environ.get("GITHUB_REPOSITORY", "ludovic111/horizon") +PROMOTE_AFTER = dt.timedelta(hours=6) +SMOKE_ASSET = "smoke-test.json" +BLOCKER = "release-blocker" +STALL_AFTER = dt.timedelta(hours=24) +STALLED = "Promotion to stable has stalled" +GAME_TAG = re.compile(r"v\d{4}\.\d{2}\.\d{2}(?:\.\d+)?") + + +def tag_key(tag): + """A game tag's numbers, four of them (v2026.10.19 is (2026, 10, 19, 0)), so tags compare.""" + version = tuple(int(part) for part in re.findall(r"\d+", tag)) + return version + (0,) * (4 - len(version)) + + +def parse_time(text): + return dt.datetime.fromisoformat(text.replace("Z", "+00:00")) if text else None + + +def covers(blocker, release): + """Whether a release-blocker issue holds this beta back. Only its state and dates count, never its text.""" + if blocker.get("state") != "closed": + return True + closed = parse_time(blocker.get("closed_at")) + return blocker.get("state_reason") == "completed" and bool(closed) and parse_time(release["published_at"]) < closed + + +def stable(releases): + """The newest stable (non pre-release) game release.""" + stables = [r for r in releases if not r["prerelease"]] + return max(stables, key=lambda r: tag_key(r["tag_name"]), default=None) + + +def reasons_against(release, current, blockers, now, by_hand=False): + """Why this beta can't become stable now: an empty list when it can.""" + reasons = [] + if not release["prerelease"]: + reasons.append("it is already stable") + if current and tag_key(release["tag_name"]) <= tag_key(current["tag_name"]): + reasons.append(f"it is not newer than the stable {current['tag_name']}") + age = now - parse_time(release["published_at"]) + if not by_hand and age < PROMOTE_AFTER: + left = PROMOTE_AFTER - age + reasons.append(f"it has been out {age.seconds // 3600} h {age.seconds % 3600 // 60} min, " + f"{left.seconds // 3600} h {left.seconds % 3600 // 60} min to go") + if not any(asset["name"] == SMOKE_ASSET for asset in release.get("assets", [])): + reasons.append(f"it has no {SMOKE_ASSET}: the release smoke test did not run") + for blocker in blockers: + if covers(blocker, release): + reasons.append(f"release-blocker #{blocker['number']}") + return reasons + + +def choose(releases, blockers, now, tag=None, force=False): + """(the beta to promote or None, a line saying why) for the game releases `releases`.""" + games = [r for r in releases if not r["draft"] and GAME_TAG.fullmatch(r["tag_name"])] + current = stable(games) + if tag: + release = next((r for r in games if r["tag_name"] == tag), None) + if not release: + return None, f"no published game release is tagged {tag}" + reasons = reasons_against(release, current, blockers, now, by_hand=True) + if force: + # Even forced, "latest" only moves forward: horizon-server update and install.sh follow it. + reasons = [r for r in reasons if r == "it is already stable" or r.startswith("it is not newer")] + if reasons: + return None, f"{tag} stays a beta: " + "; ".join(reasons) + return release, f"{tag} promoted by hand" + (" with force" if force else "") + betas = sorted((r for r in games if r["prerelease"]), key=lambda r: tag_key(r["tag_name"]), reverse=True) + held = [] + for release in betas: + reasons = reasons_against(release, current, blockers, now) + if not reasons: + return release, f"{release['tag_name']} has been out {PROMOTE_AFTER.seconds // 3600} h, passed its smoke test " \ + "and no release-blocker covers it" + held.append(f"{release['tag_name']}: " + "; ".join(reasons)) + return None, "no beta is due" + (" (" + " / ".join(held[:3]) + ")" if held else "") + + +def stalled(releases, now): + """(the oldest beta newer than the stable release, how long it has waited) once that is STALL_AFTER, else None.""" + games = [r for r in releases if not r["draft"] and GAME_TAG.fullmatch(r["tag_name"])] + current = stable(games) + waiting = [r for r in games if r["prerelease"] and (not current or tag_key(r["tag_name"]) > tag_key(current["tag_name"]))] + if not waiting: + return None + oldest = min(waiting, key=lambda r: parse_time(r["published_at"])) + age = now - parse_time(oldest["published_at"]) + return (oldest, age) if age >= STALL_AFTER else None + + +def stall_issue(releases, stall, reason): + """The title and body of the issue saying promotion has stalled.""" + oldest, age = stall + current = stable([r for r in releases if not r["draft"] and GAME_TAG.fullmatch(r["tag_name"])]) + hours = int(age.total_seconds() // 3600) + body = (f"Opened by .github/workflows/promote.yml, not by a person.\n\n" + f"No beta has become stable for {hours} hours: {oldest['tag_name']} has waited since " + f"{oldest['published_at']}, and launchers, servers and install.sh still get " + f"{current['tag_name'] if current else 'no stable release'}.\n\n" + f"The last check said: {reason}\n\n" + "Usual causes: an open `release-blocker` issue (it holds every beta until it is closed), the Mac mini's " + "release smoke test not running (no smoke-test.json on the betas), or the promote workflow disabled. " + "To promote a beta by hand: `gh workflow run promote -f tag=` (add `-f force=true` to skip the " + "smoke test and blockers). This issue closes itself once a beta is promoted.") + return f"{STALLED}: {oldest['tag_name']} has waited {hours} h", body + + +def gh(*arguments, capture=True): + result = subprocess.run(["gh", *arguments], cwd=ROOT, capture_output=capture, text=True) + if result.returncode: + raise SystemExit(f"gh {' '.join(arguments)}: {(result.stderr or '').strip()}") + return result.stdout + + +def gh_pages(path): + return [item for page in json.loads(gh("api", path, "--paginate", "--slurp") or "[]") for item in page] + + +def promote(release): + """Marks the beta stable and latest, with notes covering everything since the previous stable release.""" + tag = release["tag_name"] + with tempfile.TemporaryDirectory() as out: + subprocess.run([sys.executable, str(ROOT / "tools" / "release_train.py"), "notes", "--kind", "game", "--tag", tag, + "--head", tag, "--stable", "--out", out], cwd=ROOT, check=True, stdout=subprocess.DEVNULL) + title = (Path(out) / "title.txt").read_text().strip() + gh("release", "edit", tag, "--repo", REPO, "--prerelease=false", "--latest", "--title", title, + "--notes-file", str(Path(out) / "body.md")) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("command", choices=["promote"]) + parser.add_argument("--tag", help="promote this beta now (by hand: no 6-hour wait)") + parser.add_argument("--force", action="store_true", help="with --tag: even without a smoke test or with a blocker") + parser.add_argument("--dry-run", action="store_true", help="say what would be promoted, change nothing") + parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") + args = parser.parse_args() + if args.force and not args.tag: + parser.error("--force needs --tag: only a named beta is forced") + now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc) + releases = gh_pages(f"repos/{REPO}/releases?per_page=100") + blockers = [issue for issue in gh_pages(f"repos/{REPO}/issues?labels={BLOCKER}&state=all&per_page=100") + if "pull_request" not in issue] + release, reason = choose(releases, blockers, now, args.tag, args.force) + if release and not args.dry_run: + promote(release) + line = ("Would promote: " if release and args.dry_run else "") + reason + print(line) + if os.environ.get("GITHUB_STEP_SUMMARY"): + with open(os.environ["GITHUB_STEP_SUMMARY"], "a") as summary: + summary.write(f"### {line}\n") + report_stall(releases, release, reason, now, args.dry_run) + return 1 if args.tag and not release else 0 + + +def report_stall(releases, promoted, reason, now, dry_run): + """Opens the stalled-promotion issue when one is due and none is open; closes it after a promotion.""" + open_issues = [issue for issue in gh_pages(f"repos/{REPO}/issues?state=open&per_page=100") + if "pull_request" not in issue and issue["title"].startswith(STALLED)] + stall = None if promoted else stalled(releases, now) + if stall and not open_issues: + title, body = stall_issue(releases, stall, reason) + print(("Would open: " if dry_run else "Opening: ") + title) + if not dry_run: + gh("issue", "create", "--repo", REPO, "--title", title, "--body", body) + if promoted and not dry_run: + for issue in open_issues: + gh("issue", "close", str(issue["number"]), "--repo", REPO, "--comment", + f"{promoted['tag_name']} is stable now (promote.yml).") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release_train.py b/tools/release_train.py index 70e7b0287..943c650d2 100644 --- a/tools/release_train.py +++ b/tools/release_train.py @@ -4,6 +4,7 @@ python3 tools/release_train.py decide --kind game [--head SHA] [--force] python3 tools/release_train.py decide --kind launcher python3 tools/release_train.py notes --kind game --tag v2026.10.15 --out dist/notes + python3 tools/release_train.py notes --kind game --tag v2026.10.15 --head v2026.10.15 --stable # at promotion A kind releases when a pull request merged into main since its last published release changed one of its player-facing paths (GAME_PATHS, LAUNCHER_PATHS) and the newest of them merged at least DEBOUNCE ago (a burst @@ -14,7 +15,9 @@ towards a release and aren't listed in the notes. RELEASES_PAUSED=1 (a repositor Game releases are tagged vYYYY.MM.DD, then .01, .02 the same UTC day; launcher releases launcher-vX.Y.Z, the patch after the last launcher tag, or the next minor when a merged pull request is labelled feature. Notes: "### New" lists the pull requests labelled feature, "### Fixed" the others, "### Known issues" the bullets of -docs/known-issues.md. See docs/release-flow.md. +docs/known-issues.md. Game releases go out as betas (GitHub pre-releases) and tools/release_channels.py promotes +them to stable; a beta's notes cover what changed since the release before it (beta or stable), a promoted +release's (--stable) everything since the last stable one. See docs/release-flow.md. Prints the decision as JSON and writes it to $GITHUB_OUTPUT when set. Needs git history and the gh CLI. """ @@ -55,6 +58,8 @@ LAUNCHER_IGNORED = ["launcher/links.json", "launcher/docs/", "launcher/tests/"] FOOTER = { "game": "Install or update it from the Horizon launcher: it installs new versions by itself. " "New here? Get the launcher at https://playhorizon.dev. You need your own copy of Minecraft: Java Edition.", + "beta": "This is a beta build: launchers with Beta builds turned on in Settings install it now; everyone gets it " + "once it has been out 6 hours without a release-blocker.", "launcher": "Your launcher updates itself. New here? Download the archive for your system below, extract it, " "and run `horizon-launcher`. Website: https://playhorizon.dev", } @@ -149,11 +154,11 @@ def pull_request(number): } -def published_releases(): - """Published (not draft, not pre-release) releases, newest first, with their tags and dates.""" +def published_releases(betas=True): + """Published (not draft) releases with their tags and dates; without betas (pre-releases) when betas is False.""" releases = gh_json("api", f"repos/{REPO}/releases?per_page=100", "--paginate", "--slurp") flat = [release for page in releases for release in page] - return [release for release in flat if not release["draft"] and not release["prerelease"]] + return [release for release in flat if not release["draft"] and (betas or not release["prerelease"])] def last_release(releases, kind): @@ -225,8 +230,8 @@ def known_issues(path=ROOT / "docs" / "known-issues.md"): return [line.rstrip() for line in path.read_text().splitlines() if line.startswith("- ")] -def notes(kind, version, prs, issues): - """(title, body) of a release.""" +def notes(kind, version, prs, issues, beta=False): + """(title, body) of a release; a game beta's say it is one.""" shown = [pr for pr in prs if pr["paths"] and "skip-release" not in pr["labels"]] new = [pr for pr in shown if "feature" in pr["labels"]] fixed = [pr for pr in shown if "feature" not in pr["labels"]] @@ -244,14 +249,17 @@ def notes(kind, version, prs, issues): contributors = sorted({pr["author"] for pr in shown if pr["author"] and pr["author"] != REPO.split("/")[0]}) if contributors: parts.append("Thanks to " + ", ".join(f"@{name}" for name in contributors) + ".") + if beta and kind == "game": + parts.append(FOOTER["beta"]) parts.append(FOOTER[kind]) parts.append(DISCLAIMER) return title, "\n\n".join(parts) + "\n" -def gather(kind, head, releases=None): - """The last published release of this kind and the pull requests merged since, with their player-facing paths.""" - releases = published_releases() if releases is None else releases +def gather(kind, head, releases=None, betas=True): + """The last published release of this kind (stable only when betas is False) and the pull requests merged + since, with their player-facing paths.""" + releases = published_releases(betas) if releases is None else releases last = last_release(releases, kind) base = last["tag_name"] if last else run("git", "rev-list", "--max-parents=0", head).split()[0] exporter_paths = exporters() @@ -289,6 +297,8 @@ def main(): parser.add_argument("--force", action="store_true", help="release even without player-facing changes, before merges settle or while paused") parser.add_argument("--out", type=Path, help="notes: write title.txt and body.md here") parser.add_argument("--now", help="the time to decide at (ISO 8601; default now)") + parser.add_argument("--stable", action="store_true", + help="notes: for promoting a beta to stable, so since the last stable release, without the beta line") args = parser.parse_args() now = dt.datetime.fromisoformat(args.now) if args.now else dt.datetime.now(dt.timezone.utc) @@ -299,10 +309,10 @@ def main(): write_outputs({"release": "false", "reason": result["reason"]}) return 0 head = run("git", "rev-parse", head).strip() - last, prs = gather(args.kind, head) + last, prs = gather(args.kind, head, betas=not args.stable) if args.command == "notes": version = args.tag or "unreleased" - title, body = notes(args.kind, version, prs, known_issues()) + title, body = notes(args.kind, version, prs, known_issues(), beta=not args.stable) if args.out: args.out.mkdir(parents=True, exist_ok=True) (args.out / "title.txt").write_text(title + "\n") diff --git a/tools/test_held_drop_parity.py b/tools/test_held_drop_parity.py new file mode 100644 index 000000000..c546c5987 --- /dev/null +++ b/tools/test_held_drop_parity.py @@ -0,0 +1,42 @@ +#!/usr/bin/env python3 +"""Compare selected-slot drops with Minecraft.handleKeybinds in all four game modes. + +The oracle invokes the unmodified native key handler, consuming real drop-key +clicks. Its controlled dropItem callback removes from the real player Inventory; +other keys are idle and execution stops at the following item-use boundary. +Checks Q/Ctrl+Q, slots 0/8, empty/single/partial/full stacks and repeated drops. +Packet delivery, item entities, swing animation and statistics are outside scope. +""" +import os +import subprocess +try: + from . import lab, test_rust_parity as base +except ImportError: + import lab + import test_rust_parity as base + + +def main(): + lock, jars, libraries = base.verify_artifacts() + build = lab.LOCAL / 'held-drop-parity' + build.mkdir(parents=True, exist_ok=True) + classes = build / 'classes' + classes.mkdir(exist_ok=True) + # Minecraft's key handler also links client-only libraries. + _, game_dir = lab.config() + libraries += sorted((game_dir / 'libraries/client').rglob('*.jar')) + classpath = os.pathsep.join(map(str, [jars['client'], *libraries])) + oracle = lab.ROOT / 'mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHeldDropOracle.java' + subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', + '-cp', classpath, '-d', str(classes), str(oracle)], check=True) + subprocess.run(['java', '-Xmx512M', '-cp', str(classes) + os.pathsep + classpath, + 'dev.horizonlab.parity.VanillaHeldDropOracle', str(build / 'vanilla.txt')], check=True) + with (build / 'rust.txt').open('w') as out: + subprocess.run(['cargo', 'run', '--quiet', '-p', 'horizon-client', '--example', + 'held_drop_fixture'], cwd=lab.ROOT, stdout=out, check=True) + matched = base.compare(build / 'vanilla.txt', build / 'rust.txt') + print(f'Held drop parity passed: {matched} selected-stack/drop-count snapshots match vanilla') + + +if __name__ == '__main__': + main() diff --git a/tools/test_marker_particles_parity.py b/tools/test_marker_particles_parity.py new file mode 100644 index 000000000..54a332ea4 --- /dev/null +++ b/tools/test_marker_particles_parity.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Compare creative marker selection and ambient sampling with the pinned ClientLevel.""" +import itertools +import json + +try: + from . import lab, oracle_harness as harness +except ImportError: + import lab + import oracle_harness as harness + + +def make_input(build): + items = ['air', 'barrier', 'light', 'stone', 'structure_void', 'apple'] + cases = [dict(mode=mode, main=main, off=off, count=count) + for mode, main, off, count in itertools.product( + ['survival', 'creative', 'adventure', 'spectator'], items, items, [0, 1, 64])] + path = build / 'cases.jsonl' + path.write_text(''.join(json.dumps(case) + '\n' for case in cases)) + return path, len(cases) + + +def main(): + harness.differential( + 'marker-particles-parity', 'VanillaMarkerParticlesOracle', 'marker_particles_probe', + make_input, 'Creative main-hand marker selection and barrier marker positions, velocities and random draws', + sources=[lab.ROOT / 'tools/test_marker_particles_parity.py', + lab.ROOT / 'crates/horizon-client/src/animate_tick.rs'], expected_lines=16872) + + +if __name__ == '__main__': + main() diff --git a/website/Caddyfile b/website/Caddyfile index 9ede5bf9d..1ae4639f5 100644 --- a/website/Caddyfile +++ b/website/Caddyfile @@ -27,9 +27,13 @@ header @assets Cache-Control "public, max-age=31536000, immutable" @media path /media/* /fonts/* /og.png /favicon* /apple-touch-icon.png header @media Cache-Control "public, max-age=604800" + # The server guide became a section of the documentation. + redir /server /docs/hosting permanent + redir /server.html /docs/hosting permanent rewrite /privacy /privacy.html - rewrite /server /server.html - @pages path / /index.html /404.html /privacy.html /server.html + @doc path_regexp doc ^/docs/([a-z-]+)$ + rewrite @doc /docs/{re.doc.1}.html + @pages path / /index.html /404.html /privacy.html /docs /docs/* /sitemap.xml header @pages Cache-Control "no-cache" @legal path /LEGAL.md /fonts/*.txt header @legal Content-Type "text/plain; charset=utf-8" diff --git a/website/Dockerfile b/website/Dockerfile index a5ae2f744..ea9cc9afc 100644 --- a/website/Dockerfile +++ b/website/Dockerfile @@ -4,6 +4,7 @@ FROM node:22-alpine AS build WORKDIR /site COPY build.mjs ./ COPY src ./src +COPY docs ./docs COPY public ./public COPY LEGAL.md ./ ARG GITHUB_TOKEN diff --git a/website/LEGAL.md b/website/LEGAL.md index 9700017dd..a68797346 100644 --- a/website/LEGAL.md +++ b/website/LEGAL.md @@ -64,10 +64,19 @@ shown as screenshots of the game, as the fan websites about the game, with the disclaimer they require. The site offers no game files: players need their own legally obtained copy of Minecraft: Java Edition. +### The launcher's Servers page + +| Files in `public/media/docs/` | Source | What it shows | +| --- | --- | --- | +| `servers-create.webp`, `servers-dashboard.webp`, `servers-invite.webp`, `servers-backups.webp` | Screenshots of the Horizon launcher's Servers page (a debug build on Linux, with made-up addresses, names and `@example.com` emails), converted to WebP | The Create a server dialog, a running server, a Tailscale invitation, the Backups tab | + +They show only Horizon's own interface (MIT) and a default player head. + ## Text The parity table is generated from Horizon's README, and the patch notes -come from Horizon's GitHub releases: Horizon's own text, MIT. +come from Horizon's GitHub releases: Horizon's own text, MIT. The documentation +(`docs/*.md` in this folder, served under `/docs`) is Horizon's own text, MIT. ## Contributors diff --git a/website/README.md b/website/README.md index cfea517c3..76d8ecaf0 100644 --- a/website/README.md +++ b/website/README.md @@ -2,7 +2,7 @@ Live at **https://playhorizon.dev**. -One static page in Horizon's design language (`docs/design-system.md`), with the tokens of +A landing page and a documentation section in Horizon's design language (`docs/design-system.md`), with the tokens of `crates/horizon-theme` (generated into `src/tokens.css` by `cargo run -p xtask -- tokens`): Geist and Geist Mono, cool neutrals in a light and a dark appearance (the system's, or the toggle's) and one violet accent, numbered index lists with one-pixel rules, and short, eased @@ -14,18 +14,20 @@ no runtime dependencies. ``` build.mjs renders dist/ (no dependencies) +docs/*.md the documentation, one Markdown file per page: "# Title", a lede paragraph, then sections +docs/nav.json the order of the pages and the groups of the left navigation serve.mjs a tiny static server for local checks src/index.html the page, with {{placeholders}} build.mjs fills src/404.html the not-found page src/privacy.html what the launcher can send when players allow it, retention, deletion (/privacy) -src/server.html host a server (/server): docs/hosting.md rendered into the page +src/docs.html the template of every documentation page (/docs/...), with its left navigation src/tokens.css the design tokens, generated from crates/horizon-theme (do not edit) src/style.css every style, on top of the tokens src/main.js download buttons, patch notes, links, contributors, nav and menu, tabs, lightbox, motion src/markdown.js a small Markdown renderer (escapes everything), shared by build and page src/releases.js the patch notes' markup, shared by build and page src/contributors.js the contributors' filtering and markup, shared by build and page -public/ fonts, screenshots, icons, og.png, robots.txt, sitemap.xml: copied as is +public/ fonts, screenshots, icons, og.png, robots.txt: copied as is (sitemap.xml is written by the build) scripts/assets.mjs rebuilds public/ from the repo (fonts to WOFF2, images to WebP) scripts/shots.mjs Playwright screenshots at every width, and og.png Dockerfile, Caddyfile, railway.json the Railway service @@ -36,7 +38,7 @@ shots/ (gitignored) full-page screenshots at 360–1920 px, a 1250× ## What comes from where - **Built in** (`build.mjs`): the parity table, its score, harness count and audit date, - all from `README.md`; the server guide (`/server`) from `docs/hosting.md`; the Discord and Sponsor links from + all from `README.md`; the documentation pages (`/docs`) from `website/docs/`; the Discord and Sponsor links from `launcher/links.json`; the latest releases and the contributors (`/repos/ludovic111/horizon/contributors`, bots left out, the owner first), when GitHub answers; without an answer the build still succeeds and the Contributors block and its menu entries stay hidden until the page loads them. Locally these come from @@ -48,6 +50,17 @@ shots/ (gitignored) full-page screenshots at 360–1920 px, a 1250× and `links.json` from `main`. Each falls back to what was built in, and the download button to the releases page. +## The documentation + +`docs/.md` becomes `/docs/` (`index.md` is `/docs/`). Write for players first, then hosters, +then contributors; plain words, short paragraphs; claim only what players can download today, and +mark merged-but-unreleased things "next release". `{{HARNESSES}}` and `{{PERCENT}}` are filled from +the README. A line holding only `![caption](/media/...)` becomes a figure (the file must be in +`public/media/`); links to other pages are `/docs/#heading`. The build checks every link +between pages and every image, and fails with the list when one is broken. `/server` +redirects to `/docs/hosting`. The developer docs in the repository's `docs/` stay as they are and are linked from +the Contributing page. + ## Run it locally ```sh diff --git a/website/build.mjs b/website/build.mjs index 0a921d9d1..28c9c99fd 100644 --- a/website/build.mjs +++ b/website/build.mjs @@ -1,8 +1,9 @@ // Builds the site into dist/: src/index.html with the README's parity table and -// the community links and contributors baked in, plus public/ and fingerprinted CSS and JS. No dependencies. +// the community links and contributors baked in, the documentation (docs/*.md, one page each, listed in +// docs/nav.json), plus public/ and fingerprinted CSS and JS. No dependencies. // // Railway builds only website/, so the README and links.json come from the repo when they -// are next to it (a local checkout) and from main on GitHub otherwise. The latest releases and +// are next to it (a local checkout) and from main on GitHub otherwise. The documentation lives in website/. The latest releases and // the contributors are baked in when GitHub answers, so the page reads well before (or without) JavaScript. import { readFile, writeFile, mkdir, rm, cp } from "node:fs/promises"; import { existsSync } from "node:fs"; @@ -29,11 +30,6 @@ async function repoFile(path) { // The README: required, a site with a stale or missing parity table is worse than no deploy. const [readme, readmeFrom] = await repoFile("README.md"); -// The server guide (/server) is docs/hosting.md from its first section on: the page has its own title and lede. -const [hosting] = await repoFile("docs/hosting.md"); -const guideStart = hosting.search(/^## /m); -if (guideStart < 0) throw new Error("docs/hosting.md: no '## ' section"); - let links = { ...DEFAULT_LINKS }; try { const parsed = JSON.parse((await repoFile("launcher/links.json"))[0]); @@ -42,15 +38,18 @@ try { console.warn(`links.json: ${e.message}; using the built-in links`); } +// An optional token (a Railway variable, or `gh auth token` locally) lifts the rate limit. +const githubHeaders = { Accept: "application/vnd.github+json", ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}) }; let releases = []; try { - const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=100`, { - // An optional token (a Railway variable, or `gh auth token` locally) lifts the rate limit. - headers: { Accept: "application/vnd.github+json", ...(process.env.GITHUB_TOKEN ? { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` } : {}) }, - signal: AbortSignal.timeout(15000), - }); + const res = await fetch(`https://api.github.com/repos/${REPO}/releases?per_page=100`, { headers: githubHeaders, signal: AbortSignal.timeout(15000) }); if (res.ok) releases = (await res.json()).filter((r) => !r.draft); else console.warn(`releases: ${res.status} from GitHub; the page will load them itself`); + // A day of betas can push the stable release out of the newest 100: it is GitHub's "latest" (betas never are). + if (res.ok && !releases.some((r) => /^v\d{4}\./.test(r.tag_name) && !r.prerelease)) { + const latest = await fetch(`https://api.github.com/repos/${REPO}/releases/latest`, { headers: githubHeaders, signal: AbortSignal.timeout(15000) }); + if (latest.ok) releases.push(await latest.json()); + } } catch (e) { console.warn(`releases: ${e.message}; the page will load them itself`); } @@ -114,7 +113,8 @@ const parityHeadline = matching === body.length ? "Every subsystem matches vanil const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); const isLauncher = (tag) => tag.startsWith("launcher-v"); -const game = releases.filter((r) => isGame(r.tag_name)).slice(0, 3); +// Stable releases only: betas become stable 6 hours later (docs/release-flow.md, "Channels"). +const game = releases.filter((r) => isGame(r.tag_name) && !r.prerelease).slice(0, 3); const launcher = releases.find((r) => isLauncher(r.tag_name) && !r.prerelease); // --- The page -------------------------------------------------------------------------- @@ -202,10 +202,81 @@ const values = { CONTRIBUTORS_HIDDEN: contributors.length ? "" : " hidden", BAKED: JSON.stringify(baked).replace(/.md: "# Title", a one-paragraph lede, then the body. docs/nav.json orders them in groups. + +const docsNav = JSON.parse(await readFile(join(site, "docs", "nav.json"), "utf8")); +const docs = []; +for (const { group, pages: slugs } of docsNav) { + for (const slug of slugs) { + const file = `${slug}.md`; + const text = (await readFile(join(site, "docs", file), "utf8")).replace(/\r\n?/g, "\n"); + const m = text.match(/^# (.+)\n\n((?:[^\n]+\n)+)\n/); + if (!m) throw new Error(`docs/${file}: needs "# Title", a blank line, a lede paragraph and a blank line`); + docs.push({ slug, file, group, title: m[1].trim(), lede: m[2].trim().replace(/\n/g, " "), body: text.slice(m[0].length), path: slug === "index" ? "/docs/" : `/docs/${slug}` }); + } +} +const plain = (md) => md.replace(/`/g, "").replace(/\[([^\]]+)\]\([^)]*\)/g, "$1").replace(/\*\*/g, ""); +const anchors = new Map(); // path -> ids, to check every link between the pages +const problems = []; +const renderedDocs = docs.map((d) => { + const headings = []; + const html = markdown(d.body.replaceAll("{{HARNESSES}}", harnesses).replaceAll("{{PERCENT}}", percent), { site: true, headings }); + anchors.set(d.path, new Set(headings.map((h) => h.id))); + return { ...d, html, headings }; +}); +for (const d of renderedDocs) { + for (const [, link] of d.html.matchAll(/ + docsNav + .map(({ group, pages: slugs }) => { + const items = slugs + .map((slug) => { + const d = docs.find((x) => x.slug === slug); + return `
  • ${escape(d.title)}
  • `; + }) + .join(""); + return `

    ${escape(group)}

    \n
      ${items}
    `; + }) + .join("\n"); +const pagerLink = (d, rel) => (d ? `${rel === "next" ? "Next" : "Previous"}${escape(d.title)}` : ""); + +await mkdir(join(dist, "docs"), { recursive: true }); +const docPageFiles = []; +const docPages = renderedDocs.map((d, i) => { + const toc = d.headings.filter((h) => h.level === 2); + return { + file: join("docs", d.slug + ".html"), + values: { + DOC_TITLE: escape(d.title), + DOC_DESC: escape(plain(d.lede).slice(0, 220)), + DOC_PATH: d.path, + DOC_GROUP: escape(d.group), + DOC_LEDE: inline(d.lede, true), + DOC_NAV: docNav(d), + DOC_TOC: toc.length >= 4 ? ` ` : "", + DOC_BODY: d.html, + DOC_PAGER: pagerLink(renderedDocs[i - 1], "prev") + pagerLink(renderedDocs[i + 1], "next"), + DOC_FILE: d.file, + }, + }; +}); + +const pages = ["index.html", "404.html", "privacy.html"]; for (const page of pages) { let html = await readFile(join(site, "src", page), "utf8"); html = html.replace(/\{\{(\w+)\}\}/g, (all, key) => { @@ -215,15 +286,32 @@ for (const page of pages) { html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`); await writeFile(join(dist, page), html); } +const docTemplate = await readFile(join(site, "src", "docs.html"), "utf8"); +for (const { file, values: own } of docPages) { + let html = docTemplate.replace(/\{\{(\w+)\}\}/g, (all, key) => { + const value = key in own ? own[key] : values[key]; + if (value === undefined) throw new Error(`docs.html: unknown placeholder ${all}`); + return value; + }); + html = html.replace(/href="\/(favicon\.svg|favicon-32\.png|apple-touch-icon\.png)"/g, (all, icon) => `href="/${icon}?v=${iconVersions[icon]}"`); + await writeFile(join(dist, file), html); + docPageFiles.push(file); +} // The pages' inline scripts (they mark the page as scripted and apply the saved theme before CSS // applies) and the inlined stylesheet: the Content-Security-Policy in the Caddyfile allows them by hash. -const allHtml = (await Promise.all(pages.map((page) => readFile(join(dist, page), "utf8")))).join("\n"); +const allHtml = (await Promise.all([...pages, ...docPageFiles].map((page) => readFile(join(dist, page), "utf8")))).join("\n"); const hashes = (re) => [...new Set([...allHtml.matchAll(re)].map((m) => `'sha256-${createHash("sha256").update(m[1]).digest("base64")}'`))].join(" "); await writeFile(join(dist, ".csp-script"), hashes(/ + + + +
    +
    + Horizon + Docs + + GitHub + Download + +
    +
    + +
    +
    + Docs menu + +
    + + +
    +

    {{DOC_GROUP}}

    +

    {{DOC_TITLE}}

    +

    {{DOC_LEDE}}

    +{{DOC_TOC}} +
    +{{DOC_BODY}} +
    + +

    Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.

    +

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    +
    +
    + + + diff --git a/website/src/index.html b/website/src/index.html index eac74b409..7668951a7 100644 --- a/website/src/index.html +++ b/website/src/index.html @@ -45,7 +45,7 @@ Notes Community Contributors - Server + Docs diff --git a/website/src/main.js b/website/src/main.js index 5178d4207..825de1f25 100644 --- a/website/src/main.js +++ b/website/src/main.js @@ -39,14 +39,21 @@ const slim = (r) => ({ body: r.body || "", assets: r.assets.map((a) => ({ name: a.name, browser_download_url: a.browser_download_url, size: a.size })), }); +const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); const isLauncher = (r) => r.tag_name.startsWith("launcher-v") && !r.prerelease; const versionKey = (tag) => tag.replace("launcher-v", "").split(".").map(Number); const newer = (a, b) => versionKey(b).reduce((d, n, i) => d || n - (versionKey(a)[i] || 0), 0); -// The newest 30 releases. Game releases come out several times a day, so the newest launcher release can be -// older than all of them: then it is looked up by its tag (the newest launcher-v tag with a published release). +// The newest 100 releases (GitHub's most per page). Game betas come out several times a day, so the stable game +// release and the newest launcher release can both be older than all of them. The stable game release is then +// GitHub's "latest" (betas and launcher releases are never marked latest); the launcher release is looked up by its +// tag (the newest launcher-v tag with a published release). async function loadReleases() { - const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=30`)).filter((r) => !r.draft).map(slim); + const list = (await get(`https://api.github.com/repos/${REPO}/releases?per_page=100`)).filter((r) => !r.draft).map(slim); + if (!list.some((r) => isGame(r.tag_name) && !r.prerelease)) { + const latest = await get(`https://api.github.com/repos/${REPO}/releases/latest`).catch(() => null); + if (latest && !latest.draft) list.push(slim(latest)); + } if (list.some(isLauncher)) return list; const refs = await get(`https://api.github.com/repos/${REPO}/git/matching-refs/tags/launcher-v`).catch(() => []); const tags = refs.map((r) => r.ref.replace("refs/tags/", "")).filter((t) => /^launcher-v\d+\.\d+\.\d+$/.test(t)).sort(newer); @@ -99,10 +106,8 @@ async function setUpDownload() { // --- Patch notes and the links from main --------------------------------- -const isGame = (tag) => /^v\d{4}\.\d{1,2}\.\d{1,2}/.test(tag); - async function setUpNotes() { - const list = (await releases).filter((r) => isGame(r.tag_name)); + const list = (await releases).filter((r) => isGame(r.tag_name) && !r.prerelease); if (list.length) document.getElementById("releases").innerHTML = releasesHtml(list.slice(0, 3)); } diff --git a/website/src/markdown.js b/website/src/markdown.js index a17ab4b96..252e554ec 100644 --- a/website/src/markdown.js +++ b/website/src/markdown.js @@ -9,15 +9,17 @@ export function escape(text) { return text.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); } -function href(url) { +function href(url, site) { url = url.trim(); if (/^(https?:|mailto:)/i.test(url)) return url; - if (url.startsWith("#")) return null; // README anchors have no target here + // The docs pages (`site`) link each other and their own headings; the README's anchors have no target here. + if (site && (/^\/(?!\/)/.test(url) || url.startsWith("#"))) return url; + if (url.startsWith("#")) return null; if (/^[a-z]+:/i.test(url)) return null; // javascript: and the like return REPO_BLOB + url.replace(/^\.?\//, ""); } -export function inline(text) { +export function inline(text, site = false) { const codes = []; let out = text.replace(/`([^`]+)`/g, (_, code) => { codes.push(code); @@ -35,8 +37,8 @@ export function inline(text) { .replace(/<(https?:\/\/[^\s&]+)>/g, (_, u) => `${u}`); out = out.replace(/\u0001(\d+)\u0001/g, (_, i) => { const [label, url] = links[i]; - const target = href(url); - const body = inline(label); + const target = href(url, site); + const body = inline(label, site); return target ? `${body}` : body; }); return out.replace(/\u0000(\d+)\u0000/g, (_, i) => `${escape(codes[i])}`); @@ -45,7 +47,7 @@ export function inline(text) { const indentOf = (line) => line.match(/^ */)[0].length; const ITEM = /^(\s*)([-*+]|\d+[.)])\s+(.*)$/; -function list(lines, start) { +function list(lines, start, site) { // Collects the items at this list's indentation; deeper lines belong to the item above. const base = indentOf(lines[start]); const ordered = /\d/.test(lines[start].match(ITEM)[2]); @@ -65,7 +67,7 @@ function list(lines, start) { if (m && indentOf(line) === base) { items.push({ text: [m[3]], children: [] }); } else if (m && indentOf(line) > base) { - const [html, end] = list(lines, i); + const [html, end] = list(lines, i, site); items[items.length - 1].children.push(html); i = end; continue; @@ -77,12 +79,24 @@ function list(lines, start) { i++; } const tag = ordered ? "ol" : "ul"; - const body = items.map((it) => `
  • ${inline(it.text.join(" "))}${it.children.join("")}
  • `).join(""); + const body = items.map((it) => `
  • ${inline(it.text.join(" "), site)}${it.children.join("")}
  • `).join(""); return [`<${tag}>${body}`, i]; } -/** Renders Markdown; `shift` moves headings down (a `#` becomes `h{1 + shift}`). */ -export function markdown(source, { shift = 0 } = {}) { +const slug = (text) => + text + .toLowerCase() + .replace(/`/g, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-|-$/g, ""); + +/** + * Renders Markdown; `shift` moves headings down (a `#` becomes `h{1 + shift}`). + * `site` is for the docs pages: links to the site's own pages and anchors stay as they are, `##` and `###` + * headings get an id (and are pushed onto `headings`, for a table of contents), and a line holding only + * `![caption](/media/…)` becomes a figure. + */ +export function markdown(source, { shift = 0, site = false, headings = null } = {}) { const lines = source.replace(/\r\n?/g, "\n").split("\n"); const out = []; let i = 0; @@ -95,7 +109,17 @@ export function markdown(source, { shift = 0 } = {}) { let m; if ((m = line.match(/^(#{1,6})\s+(.*?)\s*#*$/))) { const level = Math.min(6, m[1].length + shift); - out.push(`${inline(m[2])}`); + let id = ""; + if (site && (m[1].length === 2 || m[1].length === 3)) { + const base = slug(m[2]); + id = base; + for (let n = 2; headings && headings.some((h) => h.id === id); n++) id = `${base}-${n}`; + headings?.push({ level: m[1].length, text: m[2].replace(/`/g, ""), id }); + } + out.push(`${inline(m[2], site)}`); + i++; + } else if (site && (m = line.match(/^!\[([^\]]*)\]\((\/media\/[\w./-]+)\)\s*$/))) { + out.push(`
    ${escape(m[1])}
    ${inline(m[1], true)}
    `); i++; } else if ((m = line.match(/^\s*(```|~~~)/))) { const fence = m[1]; @@ -108,13 +132,13 @@ export function markdown(source, { shift = 0 } = {}) { out.push("
    "); i++; } else if (ITEM.test(line)) { - const [html, end] = list(lines, i); + const [html, end] = list(lines, i, site); out.push(html); i = end; } else if (line.startsWith(">")) { const quote = []; while (i < lines.length && lines[i].startsWith(">")) quote.push(lines[i++].replace(/^>\s?/, "")); - out.push(`
    ${markdown(quote.join("\n"), { shift })}
    `); + out.push(`
    ${markdown(quote.join("\n"), { shift, site })}
    `); } else { const para = []; while ( @@ -125,7 +149,7 @@ export function markdown(source, { shift = 0 } = {}) { ) { para.push(lines[i++].trim()); } - out.push(`

    ${inline(para.join(" "))}

    `); + out.push(`

    ${inline(para.join(" "), site)}

    `); } } return out.join("\n"); diff --git a/website/src/server.html b/website/src/server.html deleted file mode 100644 index 94f470678..000000000 --- a/website/src/server.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - Host a server · Horizon - - - - - - - - - - -
    -
    -

    ServerEarly version

    -

    Host a server.

    -

    horizon-server runs a Minecraft Java Edition 26.3 server with Horizon's own game as the engine: one native program, no Java, one settings file, a command line, a web panel and backups. Vanilla and Horizon clients can join. This page is docs/hosting.md, built into the site.

    -
    -{{SERVER_GUIDE}} -
    - -

    Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft.

    -
    -
    - - - diff --git a/website/src/style.css b/website/src/style.css index 8be518881..03004464b 100644 --- a/website/src/style.css +++ b/website/src/style.css @@ -431,3 +431,71 @@ figcaption span { font-family: var(--mono); font-size: var(--text-micro); letter .privacy h1 { margin-bottom: 16px; } .privacy .prose { margin: 40px 0; } .privacy .disclaimer { margin-top: 32px; } + +/* --- Documentation (/docs): a left navigation and one page at a time --------------------- */ + +.docs-bar { + position: sticky; top: 0; z-index: 20; height: 56px; + background: color-mix(in srgb, var(--page) 88%, transparent); + -webkit-backdrop-filter: blur(16px) saturate(1.2); backdrop-filter: blur(16px) saturate(1.2); + box-shadow: 0 1px 0 var(--rule); +} +.docs-bar-inner { display: flex; align-items: center; gap: 16px; height: 100%; max-width: var(--max); margin: 0 auto; padding: 0 var(--g); } +.docs-bar-title { padding-left: 16px; border-left: 1px solid var(--rule); color: var(--muted); font-size: var(--text-label); } +.docs-bar-end { margin-left: auto; display: flex; align-items: center; gap: 16px; } +.docs-bar-link { color: var(--muted); font-size: var(--text-label); } +.docs-bar-link:hover { color: var(--ink); } +.docs { + display: grid; grid-template-columns: 248px minmax(0, 1fr); gap: clamp(32px, 6vw, 96px); + max-width: var(--max); margin: 0 auto; padding: 48px var(--g) 0; align-items: start; +} +.docs-nav-wrap { position: sticky; top: 80px; max-height: calc(100vh - 104px); overflow-y: auto; padding-bottom: 24px; } +.docs-nav-wrap summary { display: none; } +.docs-nav-group { margin: 28px 0 8px; font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); } +.docs-nav-group:first-child { margin-top: 0; } +.docs-nav li a { display: block; padding: 6px 12px; margin-left: -12px; border-radius: var(--radius); color: var(--ink-soft); font-size: var(--text-ui); } +.docs-nav li a:hover { background: var(--plate-soft); color: var(--ink); } +.docs-nav li a[aria-current] { background: var(--plate-soft); color: var(--ink); font-weight: 500; } +.docs-main { min-width: 0; padding-bottom: 48px; } +.docs-main .title { margin-bottom: 16px; } +.docs-main .lede { max-width: 64ch; font-size: var(--text-heading); line-height: 1.45; } +.docs-toc { margin-top: 28px; max-width: 72ch; } +.docs-toc p { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); margin-bottom: 8px; } +.docs-toc ul { display: flex; flex-wrap: wrap; gap: 6px; } +.docs-toc a { display: block; padding: 4px 12px; border-radius: var(--radius-pill); background: var(--plate-soft); color: var(--ink-soft); font-size: var(--text-label); } +.docs-toc a:hover { background: var(--plate); color: var(--ink); } +.docs-prose { max-width: 72ch; margin-top: 40px; font-size: var(--text-body); } +.docs-prose > * + * { margin-top: 14px; } +.docs-prose h2 { margin-top: 56px; padding-top: 24px; border-top: 1px solid var(--rule); font-size: clamp(24px, 2.4vw, 30px); line-height: 1.2; letter-spacing: var(--text-title-tracking); scroll-margin-top: 80px; } +.docs-prose h2:first-child { margin-top: 0; padding-top: 0; border-top: 0; } +.docs-prose h3 { margin-top: 32px; scroll-margin-top: 80px; } +.docs-prose ol { list-style: decimal; } +.docs-prose pre { font: 0.86em/1.6 var(--mono); } +.docs-prose blockquote { padding: 2px 0 2px 16px; border-left: 2px solid var(--accent); color: var(--ink-soft); } +.docs-prose blockquote > * + * { margin-top: 8px; } +.docs-prose figure { margin: 28px 0; } +.docs-prose figure img { width: 100%; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); } +.docs-prose figcaption { margin-top: 10px; font-size: var(--text-caption); color: var(--muted); } +.docs-pager { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; max-width: 72ch; margin-top: 56px; } +.docs-pager a { display: flex; flex-direction: column; gap: 2px; padding: 14px 16px; border-radius: var(--radius-plate); box-shadow: 0 0 0 1px var(--rule); color: var(--ink); font-weight: 500; } +.docs-pager a:hover { background: var(--plate-soft); color: var(--ink); } +.docs-pager a span { font: var(--text-micro) / var(--text-micro-line) var(--mono); letter-spacing: var(--text-micro-tracking); text-transform: uppercase; color: var(--muted); font-weight: 400; } +.docs-pager-next { grid-column: 2; text-align: right; } +.docs-edit { margin-top: 32px; font-size: var(--text-caption); color: var(--muted); } +.docs-edit a { color: inherit; text-decoration: underline; text-decoration-color: var(--rule); text-underline-offset: 3px; } +.docs-main .disclaimer { margin-top: 24px; } + +@media (max-width: 900px) { + .docs { grid-template-columns: minmax(0, 1fr); gap: 0; padding-top: 12px; } + .docs-nav-wrap { position: static; max-height: none; overflow: visible; margin-bottom: 24px; border-bottom: 1px solid var(--rule); } + .docs-nav-wrap summary { display: flex; align-items: center; min-height: 44px; cursor: pointer; font-weight: 500; list-style: none; } + .docs-nav-wrap summary::-webkit-details-marker { display: none; } + .docs-nav-wrap summary::after { content: "+"; margin-left: auto; color: var(--muted); } + .docs-nav-wrap[open] summary::after { content: "\2212"; } + .docs-pager { grid-template-columns: minmax(0, 1fr); } + .docs-pager-next { grid-column: 1; } + .docs-bar-link { display: none; } +} +@media (pointer: coarse) { + .docs-nav li a, .docs-toc a, .docs-bar-title, .docs-bar-link { display: flex; align-items: center; min-height: 44px; } +}