Merge origin/main into perf/server-helpers-behind
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
+13
-38
@@ -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
|
||||
|
||||
@@ -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: |
|
||||
|
||||
@@ -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
|
||||
@@ -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}
|
||||
@@ -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 <branch> # 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: |
|
||||
|
||||
@@ -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 }}
|
||||
@@ -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
|
||||
|
||||
|
||||
Generated
+8
@@ -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"
|
||||
|
||||
+1
-1
@@ -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]
|
||||
|
||||
@@ -14,106 +14,64 @@
|
||||
<p align="center">
|
||||
<a href="https://playhorizon.dev"><b>Website</b></a> ·
|
||||
<a href="#download"><b>Download</b></a> ·
|
||||
<a href="#what-changed-in-v202610131"><b>What changed</b></a> ·
|
||||
<a href="#screenshots"><b>Screenshots</b></a> ·
|
||||
<a href="#project-status"><b>Parity status</b></a> ·
|
||||
<a href="docs/README.md"><b>Documentation</b></a>
|
||||
<a href="https://playhorizon.dev/docs/"><b>Documentation</b></a> ·
|
||||
<a href="https://github.com/ludovic111/horizon/releases"><b>Release notes</b></a> ·
|
||||
<a href="#project-status"><b>Project status</b></a> ·
|
||||
<a href="#contributing"><b>Contributing</b></a>
|
||||
</p>
|
||||
|
||||
# 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).
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/launcher-play.webp" alt="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 list"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page, showing the notes of Horizon 2026.10.14.1"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-play.webp" alt="The launcher's Play page: a version ready to play, its summary, Client and Server, the version picker and Play"></td>
|
||||
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
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
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="2"><img src="docs/media/menu-title.webp" alt="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"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/menu-worlds.webp" alt="The Singleplayer page: two worlds with their dates and game modes, and Create world and Play buttons"></td>
|
||||
<td width="50%"><img src="docs/media/settings.webp" alt="The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs"></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
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:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td colspan="2"><img src="docs/media/sunset.webp" alt="Sunset over a savanna river valley and a plains village"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/menu-title.webp" alt="Horizon's title screen over a veiled snowy landscape"></td>
|
||||
<td width="50%"><img src="docs/media/settings.webp" alt="The Video settings in their Simple view: a preset, render distance, field of view, framerate, VSync and GUI scale, each with what it costs"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/village.webp" alt="A plains village among savanna hills, with farms, villagers and an iron golem"></td>
|
||||
<td width="50%"><img src="docs/media/survival.webp" alt="Survival at dusk: a zombie walks up, with the hotbar, health, hunger and experience"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/nether.webp" alt="A crimson forest in the Nether with a zombified piglin"></td>
|
||||
<td width="50%"><img src="docs/media/night.webp" alt="Moonrise over a torch-lit village and river"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td width="50%"><img src="docs/media/underwater.webp" alt="Tropical fish over a warm-ocean coral reef"></td>
|
||||
<td width="50%" valign="middle">
|
||||
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.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## 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
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<String> = 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(())
|
||||
}
|
||||
@@ -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<String> = 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;
|
||||
|
||||
@@ -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<String> = serde_json::from_value(oracle["tools"].clone())?;
|
||||
|
||||
|
||||
@@ -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<StructureAt> {
|
||||
fn structures_at(
|
||||
&self,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
wanted: &dyn Fn(&str) -> bool,
|
||||
) -> Vec<StructureAt> {
|
||||
let (cx, cz) = (x >> 4, z >> 4);
|
||||
let mut out: Vec<StructureAt> = 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 {
|
||||
|
||||
@@ -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<ParticleOptions>)>,
|
||||
}
|
||||
|
||||
/// `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
|
||||
|
||||
@@ -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<horizon_client::lod::Lod>,
|
||||
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<Arc<horizon_client::chunk::Chunk>>,
|
||||
options: Options,
|
||||
player: Option<PlayerMotion>,
|
||||
spawn: Option<Vec3>,
|
||||
@@ -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<Vertex> {
|
||||
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<GameCpuResources>,
|
||||
) -> Result<Self> {
|
||||
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<horizon_client::mobs::Part>,
|
||||
dragon_model: Option<horizon_client::mobs::Part>,
|
||||
arrow_model: Option<horizon_client::mobs::Part>,
|
||||
trident_model: Option<horizon_client::mobs::Part>,
|
||||
creative_screen: Creative,
|
||||
}
|
||||
impl GameCpuResources {
|
||||
fn load(root: &std::path::Path) -> Result<Self> {
|
||||
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<GameCpuResources>,
|
||||
renderer_cpu: Option<horizon_client::gfx::PreparedTextures>,
|
||||
root: PathBuf,
|
||||
pack_error: Option<String>,
|
||||
resources: Arc<Resources>,
|
||||
@@ -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<Window>,
|
||||
offscreen: bool,
|
||||
pack: &PackResources,
|
||||
gui: &UiResources,
|
||||
previous: Option<&Renderer>,
|
||||
prepared: Option<horizon_client::gfx::PreparedTextures>,
|
||||
api: horizon_client::graphics::GraphicsApi,
|
||||
) -> Result<Renderer> {
|
||||
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<WorldRestLoader>,
|
||||
settings: Option<Settings>,
|
||||
prepared: Option<GameCpuResources>,
|
||||
) -> Result<Option<Game<'a>>> {
|
||||
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<String>,
|
||||
started: Instant,
|
||||
panorama_rotation: horizon_client::gfx::panorama::Rotation,
|
||||
progress: Progress,
|
||||
receiver: Receiver<LoaderMsg>,
|
||||
loaded: Option<std::result::Result<Loaded, String>>,
|
||||
@@ -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<Option<Game<'static>>> {
|
||||
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<Resources> = 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::*;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<StructureAt> {
|
||||
fn structures_at(
|
||||
&self,
|
||||
x: i32,
|
||||
y: i32,
|
||||
z: i32,
|
||||
wanted: &dyn Fn(&str) -> bool,
|
||||
) -> Vec<StructureAt> {
|
||||
self.game
|
||||
.structures_reaching([x, y, z])
|
||||
.structures_reaching_where([x, y, z], wanted)
|
||||
.into_iter()
|
||||
.map(|(id, in_piece)| StructureAt {
|
||||
id,
|
||||
|
||||
@@ -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<ItemStack>; 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<ItemStack>; 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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`.
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<SectionGpu>,
|
||||
lods: HashMap<crate::lod::TileKey, lod::Tile>,
|
||||
/// 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<SectionKey>,
|
||||
/// Finished tile meshes `upload_lods` has yet to upload.
|
||||
lod_pending: Option<lod::Pending>,
|
||||
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<u8>, u32)>,
|
||||
forcefield: (Vec<u8>, 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<PreparedTextures>,
|
||||
previous: Option<&Self>,
|
||||
api: GraphicsApi,
|
||||
) -> Result<Self> {
|
||||
@@ -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<wgpu::Texture> = (0..sprite_arrays)
|
||||
.map(|array| {
|
||||
let first = array * split;
|
||||
let sprite_textures: Vec<wgpu::Texture> = 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<Item = (i32, i32)> + '_ {
|
||||
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<u8> = (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] {
|
||||
|
||||
@@ -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<u32>,
|
||||
passes: Vec<PassGpu>,
|
||||
final_pass: Option<PassGpu>,
|
||||
directives: Directives,
|
||||
}
|
||||
|
||||
pub struct JavaStages {
|
||||
@@ -216,6 +230,10 @@ pub struct JavaStages {
|
||||
last: Option<std::time::Instant>,
|
||||
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::<Result<Vec<_>, _>>()?;
|
||||
@@ -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<String, Vec<f32>>,
|
||||
}
|
||||
|
||||
/// `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<Vec<f32>> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<f32>>, 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.
|
||||
|
||||
@@ -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<TileKey, SectionMesh>,
|
||||
removed: FxHashSet<TileKey>,
|
||||
cutout: Option<FxHashSet<(i32, i32)>>,
|
||||
}
|
||||
|
||||
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<TileKey>,
|
||||
cutout: Option<FxHashSet<(i32, i32)>>,
|
||||
) {
|
||||
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<TileKey>,
|
||||
cutout: Option<FxHashSet<(i32, i32)>>,
|
||||
) {
|
||||
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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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<T> Resident<T> {
|
||||
/// 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<T> Resident<T> {
|
||||
radius: i32,
|
||||
frustum: &Frustum,
|
||||
reachable: impl Fn(SectionKey) -> bool,
|
||||
beyond: impl Fn(i32, i32) -> bool,
|
||||
out: &mut Vec<Visible>,
|
||||
) {
|
||||
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<T> Resident<T> {
|
||||
}
|
||||
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]);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -83,7 +83,7 @@ pub fn rows(level: Level) -> Vec<Row> {
|
||||
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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1705,7 +1705,15 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_held_drop(slot: &mut Option<ItemStack>, all: bool) -> Option<ItemStack> {
|
||||
/// Minecraft.handleKeybinds: spectators cannot drop from the selected slot.
|
||||
pub fn take_held_drop(
|
||||
slot: &mut Option<ItemStack>,
|
||||
all: bool,
|
||||
spectator: bool,
|
||||
) -> Option<ItemStack> {
|
||||
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 }
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Program>,
|
||||
/// The targets whose alternate side holds the frame's last write.
|
||||
pub flipped_at_end: BTreeSet<u32>,
|
||||
/// `sunPathRotation` and `eyeBrightnessHalflife`.
|
||||
pub directives: Directives,
|
||||
}
|
||||
|
||||
/// A loaded Java pack.
|
||||
pub struct JavaPasses {
|
||||
pub folders: Vec<JavaFolder>,
|
||||
/// `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)]
|
||||
|
||||
@@ -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<u8> {
|
||||
(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<TileKey, Vec<Column>>,
|
||||
ready: &FxHashMap<TileKey, impl Sized>,
|
||||
out: &mut Vec<TileKey>,
|
||||
) -> 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<TileKey>,
|
||||
/// The active tiles' samples when the job began: a replan may drop them
|
||||
/// from `ready` before the job is sent.
|
||||
samples: FxHashMap<TileKey, Arc<Vec<Column>>>,
|
||||
keys: Vec<TileKey>,
|
||||
finer: FxHashMap<TileKey, Vec<TileKey>>,
|
||||
inputs: Vec<MeshInput>,
|
||||
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<Column>,
|
||||
/// The tile's samples, with `visited` replacing some of them (`columns`).
|
||||
samples: Arc<Vec<Column>>,
|
||||
visited: Vec<(usize, Column)>,
|
||||
neighbors: [Vec<mesh::EdgeColumn>; 4],
|
||||
finer: Vec<TileKey>,
|
||||
}
|
||||
@@ -375,6 +422,17 @@ struct ReducedColumns {
|
||||
columns: Arc<[Column; 256]>,
|
||||
levels: [Vec<Column>; 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<Column> {
|
||||
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<TileKey>,
|
||||
meshes: Vec<(TileKey, SectionMesh)>,
|
||||
covered: FxHashSet<(i32, i32)>,
|
||||
},
|
||||
}
|
||||
struct Shared {
|
||||
@@ -438,6 +497,12 @@ pub struct Lod {
|
||||
#[cfg(test)]
|
||||
context: Arc<WorkerContext>,
|
||||
meshing: bool,
|
||||
/// The next mesh job, while its inputs are gathered (`meshing` is set).
|
||||
gathering: Option<Gathering>,
|
||||
/// 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<TileKey, [u64; 4]>,
|
||||
detail_request_pending: bool,
|
||||
detail_request_at: std::time::Instant,
|
||||
ready: FxHashMap<TileKey, Vec<Column>>,
|
||||
/// 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<Vec<u8>>,
|
||||
/// Each tile's samples, shared with mesh jobs in flight.
|
||||
ready: FxHashMap<TileKey, Arc<Vec<Column>>>,
|
||||
active: FxHashSet<TileKey>,
|
||||
dirty: FxHashSet<TileKey>,
|
||||
removed: Vec<TileKey>,
|
||||
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<FxHashSet<(i32, i32)>>,
|
||||
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<TileKey> {
|
||||
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<FxHashSet<(i32, i32)>> {
|
||||
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<FxHashSet<(i32, i32)>>,
|
||||
) -> 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<FxHashSet<(i32, i32)>>) {
|
||||
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<TileKey>) -> Option<(Column, i32)> {
|
||||
for level in 0..=10 {
|
||||
fn neighbor(
|
||||
&self,
|
||||
wx: i32,
|
||||
wz: i32,
|
||||
active: &FxHashSet<TileKey>,
|
||||
samples: &FxHashMap<TileKey, Arc<Vec<Column>>>,
|
||||
) -> 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<TileKey>) -> MeshInput {
|
||||
fn mesh_input(
|
||||
&self,
|
||||
key: TileKey,
|
||||
active: &FxHashSet<TileKey>,
|
||||
samples: &FxHashMap<TileKey, Arc<Vec<Column>>>,
|
||||
finer: Vec<TileKey>,
|
||||
) -> 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<TileKey>,
|
||||
keys: &FxHashSet<TileKey>,
|
||||
) -> FxHashMap<TileKey, Vec<TileKey>> {
|
||||
let mut finer: FxHashMap<TileKey, Vec<TileKey>> = 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<TileKey, Vec<Column>> = 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")
|
||||
};
|
||||
|
||||
@@ -302,8 +302,34 @@ fn mesh_columns_with_edges(
|
||||
count += neighbors[side].len();
|
||||
start
|
||||
});
|
||||
let prepared: Vec<Vec<Segment<'_>>> = 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<Vec<Segment<'_>>> = 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<EdgeColumn>; 4],
|
||||
stride: i32,
|
||||
whole: impl Fn(usize, usize) -> bool,
|
||||
mut fluid: impl FnMut(&Span) -> bool,
|
||||
) -> Vec<std::borrow::Cow<'a, Column>> {
|
||||
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)];
|
||||
|
||||
@@ -177,6 +177,9 @@ pub struct Menu {
|
||||
pub sounds: Vec<&'static str>,
|
||||
/// Recipes whose result was taken (`awardUsedRecipes`), for the caller.
|
||||
pub crafted: Vec<String>,
|
||||
/// `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<ItemStack>)>,
|
||||
/// The merchant a merchant menu trades with.
|
||||
pub merchant: Option<Box<crate::merchant::Session>>,
|
||||
}
|
||||
@@ -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<ItemStack>) {
|
||||
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<ItemStack>,
|
||||
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<ItemStack> {
|
||||
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<ItemStack>)]| {
|
||||
e.iter()
|
||||
.map(|(slot, s)| format!("{slot}:{}", s.as_ref().map_or("-", |s| &*s.item)))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
// 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| {
|
||||
|
||||
@@ -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<SpawnCost>;
|
||||
/// 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<StructureAt>;
|
||||
/// 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<StructureAt>;
|
||||
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<String, HashMap<String, Override>>,
|
||||
/// Fx-hashed: natural spawning asks for every structure reaching every
|
||||
/// position it tries.
|
||||
pub overrides: FxHashMap<String, FxHashMap<String, Override>>,
|
||||
}
|
||||
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<String, Override> = v["spawn_overrides"]
|
||||
let map: FxHashMap<String, Override> = v["spawn_overrides"]
|
||||
.as_object()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
@@ -709,7 +718,14 @@ pub fn mobs_at<L: NaturalLevel>(
|
||||
y: i32,
|
||||
z: i32,
|
||||
) -> Vec<SpawnEntry> {
|
||||
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<L: NaturalLevel>(
|
||||
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<SpawnPlayer>,
|
||||
players_near: HashMap<(i32, i32), Vec<usize>>,
|
||||
player_counts: HashMap<usize, [i32; 8]>,
|
||||
players_near: FxHashMap<(i32, i32), Vec<usize>>,
|
||||
player_counts: FxHashMap<usize, [i32; 8]>,
|
||||
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 {
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
@@ -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<String, String> =
|
||||
serde_json::from_slice(&fs::read(root.join("worldgen/processor_lists.json")).unwrap())
|
||||
.unwrap();
|
||||
assert!(lists.contains_key("kaisyn:mossy"));
|
||||
let tags: BTreeMap<String, String> =
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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<bool> {
|
||||
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();
|
||||
|
||||
@@ -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::<Vec<_>>(),
|
||||
)
|
||||
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::<Vec<_>>(),
|
||||
),
|
||||
// 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<Row> {
|
||||
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<Row>| {
|
||||
rows.into_iter()
|
||||
.filter_map(|row| match row {
|
||||
Row::Header(key) => Some(key),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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] {
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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<list<u8>>;
|
||||
/// Errs on a malformed key or over quota (bytes for the whole mod).
|
||||
set: func(key: string, value: list<u8>) -> 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;
|
||||
}
|
||||
|
||||
@@ -3,9 +3,11 @@
|
||||
//! declares in `data/<id>/horizon/block/` and `data/<id>/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<String>,
|
||||
pub blocks: Vec<Block>,
|
||||
pub items: Vec<Item>,
|
||||
/// The namespaces it owns: the mod id, then the manifest's `namespaces`.
|
||||
pub namespaces: Vec<String>,
|
||||
}
|
||||
|
||||
/// 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<String> {
|
||||
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
|
||||
|
||||
@@ -13,6 +13,9 @@ pub const API: &str = "0.1";
|
||||
/// `assets/` and `data/` in the `.hmod`, with blocks and items declared in
|
||||
/// `data/<id>/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<Capability>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
#[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<Item = &str> {
|
||||
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()));
|
||||
|
||||
@@ -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<Snapshot>,
|
||||
out: Vec<Output>,
|
||||
panel: Option<Panel>,
|
||||
/// 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<Option<Running>, 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<String> = 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<Vec<u8>> {
|
||||
storage_key_ok(&key)
|
||||
.then(|| std::fs::read(self.data_dir.join(&key)).ok())
|
||||
.flatten()
|
||||
}
|
||||
fn set(&mut self, key: String, value: Vec<u8>) -> 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::DirEntry> = 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 != ".."
|
||||
}
|
||||
|
||||
@@ -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 <key> <text>` 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 <key> <text>")?;
|
||||
storage::set(key, text.as_bytes())?;
|
||||
Ok(Some("saved".into()))
|
||||
}
|
||||
_ => {
|
||||
chat::show(&format!("hello {args} after {} ticks", self.ticks));
|
||||
Ok(None)
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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<String>,
|
||||
/// Files outside what a content mod may hold (other namespaces, vanilla
|
||||
/// data other than tags), kept in `outside/` for review.
|
||||
pub outside: Vec<String>,
|
||||
@@ -25,6 +28,8 @@ pub struct Report {
|
||||
pub unreadable: BTreeMap<String, String>,
|
||||
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<String>) -> 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<String> {
|
||||
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<String> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `{"<key>": 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<bool> {
|
||||
/// 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<bool> {
|
||||
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<fs::File>,
|
||||
id: &str,
|
||||
pack_mod: &dyn Fn(&str) -> bool,
|
||||
) -> Vec<String> {
|
||||
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<u8>)> = 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> = [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<u8>) -> Option<String> {
|
||||
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<u8>) -> Option<String> {
|
||||
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<u8> {
|
||||
/// 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<String, Value>,
|
||||
) -> Result<Report, String> {
|
||||
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::<Value>(&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::<Value>(&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<String> = 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -157,6 +157,16 @@ fn carry_all(
|
||||
list: Vec<Value>,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
) -> (Vec<Value>, bool) {
|
||||
carry_at(list, data, carried, 0)
|
||||
}
|
||||
|
||||
/// [`carry_all`] for a list `depth` pillars deep (see [`pillar`]).
|
||||
fn carry_at(
|
||||
list: Vec<Value>,
|
||||
data: &ProcessorData,
|
||||
carried: &mut BTreeMap<String, usize>,
|
||||
depth: usize,
|
||||
) -> (Vec<Value>, 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<String, usize>,
|
||||
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<String, usize>) -> Value {
|
||||
@@ -383,6 +453,11 @@ fn referenced(lists: &Value, data: &ProcessorData) -> Option<Vec<Value>> {
|
||||
fn as_data(kind: &str, p: &Value, data: &ProcessorData) -> Option<Vec<Value>> {
|
||||
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<Vec<Value>> {
|
||||
"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<Vec<Value>> {
|
||||
let rule = |rules: &[(&str, Value)]| {
|
||||
let rules: Vec<Value> = 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<Value> = 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<Value> = 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::<usize>(), 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -401,6 +401,9 @@ fn drop_java_processors(list: &mut Value, dropped: &mut BTreeMap<String, usize>)
|
||||
.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<String, Vec<String>> = 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),
|
||||
])
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -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=
|
||||
@@ -0,0 +1,345 @@
|
||||
//! Signed release checksums (docs/security.md, "Signed updates").
|
||||
//!
|
||||
//! Every release carries `SHA256SUMS` (`sha256sum`'s format, `<hex> <file>` per line) and
|
||||
//! `SHA256SUMS.sig`: one base64 Ed25519 signature per line, each over `horizon release <tag>\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<PublicKey> {
|
||||
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<Vec<PublicKey>, 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<u8> {
|
||||
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 (`<hex> <name>` or `<hex> *<name>`).
|
||||
pub fn parse_sums(text: &str) -> Result<Vec<(String, String)>, 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 `<sha256> <file>`"))?;
|
||||
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 `<sha256> <file>`"));
|
||||
}
|
||||
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<Vec<(String, String)>, 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<String, String> {
|
||||
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<Self, String> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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 <base64>] [--publishing] <folder>
|
||||
//! 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<String> = 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 <tag> [--key <base64>]... [--publishing] \
|
||||
<folder> | keygen --public-out <file>"
|
||||
.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<String>, Vec<String>) {
|
||||
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>), String> {
|
||||
let (tags, rest) = options(args, "--tag");
|
||||
let tag = tags.into_iter().next().ok_or("--tag <tag> is needed")?;
|
||||
Ok((tag, rest))
|
||||
}
|
||||
|
||||
fn file_hash(path: &Path) -> Result<String, String> {
|
||||
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 <file>")?;
|
||||
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())
|
||||
}
|
||||
@@ -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<String> {
|
||||
[
|
||||
"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();
|
||||
}
|
||||
@@ -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<Value> = 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.");
|
||||
}
|
||||
|
||||
@@ -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<Vec<String>
|
||||
|
||||
/// 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<toml::Value> {
|
||||
}
|
||||
|
||||
/// 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),
|
||||
|
||||
@@ -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<NameAndId, String> {
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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] <command>
|
||||
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] <command>
|
||||
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..]),
|
||||
|
||||
@@ -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<String>,
|
||||
/// Those the running server took at once.
|
||||
pub applied: Vec<String>,
|
||||
/// Those that wait for the game's next start, while it runs.
|
||||
pub restart: Vec<String>,
|
||||
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<std::ops::RangeInclusive<i64>> {
|
||||
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<String> {
|
||||
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<Outcome, String> {
|
||||
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::<Result<Vec<_>, _>>()?;
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<String>, Vec<String>) {
|
||||
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<String> = 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())
|
||||
// `.<tag>.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<PathBuf, S
|
||||
.and_then(|mut z| z.extract(&scratch))
|
||||
.map_err(|e| format!("{}: {e}", archive.display()))?;
|
||||
} else if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
|
||||
// tar is on every Linux and macOS, and on Windows 10 and later.
|
||||
// tar is on every Linux and macOS, and on Windows 10 and later. The files are the
|
||||
// user's, not the archive's owners: as root in a user namespace (an unprivileged LXC
|
||||
// or rootless container) taking those fails, and as plain root they'd be strangers'.
|
||||
let status = Command::new("tar")
|
||||
.arg("--no-same-owner")
|
||||
.arg("-xzf")
|
||||
.arg(archive)
|
||||
.arg("-C")
|
||||
@@ -388,6 +458,7 @@ pub fn backup_name(tag: &str) -> 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<String> = 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() {
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<u32>,
|
||||
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<Item = &'a str>) -> 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::<f32>();
|
||||
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 = "\
|
||||
|
||||
@@ -307,6 +307,34 @@ fn parse_blend(value: &str) -> Result<Blend, String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `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<CloudSetting>,
|
||||
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.<program>`: the program's blend override.
|
||||
pub fn blend(&self, program: &str) -> Option<Result<Blend, String>> {
|
||||
self.preprocessed
|
||||
|
||||
@@ -0,0 +1,838 @@
|
||||
//! Custom uniforms: `uniform.<type>.<name> = <expression>` and
|
||||
//! `variable.<type>.<name> = <expression>` 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<Def>,
|
||||
/// Evaluation order (indices into `defs`): dependencies first.
|
||||
order: Vec<usize>,
|
||||
/// What couldn't be parsed or resolved, for the log.
|
||||
pub problems: Vec<String>,
|
||||
}
|
||||
|
||||
#[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<Expr>, usize),
|
||||
Not(Box<Expr>),
|
||||
Negate(Box<Expr>),
|
||||
Binary(Op, Box<Expr>, Box<Expr>),
|
||||
/// A function; `smooth` calls carry their own state slot.
|
||||
Call(String, Vec<Expr>, 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<SmoothFloat>,
|
||||
seed: u64,
|
||||
values: HashMap<String, Vec<f32>>,
|
||||
}
|
||||
|
||||
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<String, Vec<f32>> {
|
||||
&self.values
|
||||
}
|
||||
}
|
||||
|
||||
impl CustomUniforms {
|
||||
/// The definitions in `properties` (key, value), in file order.
|
||||
pub fn parse<'a>(properties: impl IntoIterator<Item = (&'a str, &'a str)>) -> 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<usize> {
|
||||
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<usize>,
|
||||
) -> 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<Vec<f32>>,
|
||||
) {
|
||||
let mut values: HashMap<&str, Vec<f32>> = 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<String>) {
|
||||
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<Vec<f32>>,
|
||||
values: &'a HashMap<&'a str, Vec<f32>>,
|
||||
broken: &'a [&'a str],
|
||||
smooth: &'a mut Vec<SmoothFloat>,
|
||||
seed: &'a mut u64,
|
||||
}
|
||||
|
||||
/// Apply `f` component by component, a scalar standing for every component.
|
||||
fn zip(args: &[Vec<f32>], f: impl Fn(&[f32]) -> f32) -> Vec<f32> {
|
||||
let n = args.iter().map(Vec::len).max().unwrap_or(1);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let a: Vec<f32> = 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<Vec<f32>> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<f32>> {
|
||||
// `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<Vec<f32>> = args.iter().map(|a| self.expr(a)).collect::<Option<_>>()?;
|
||||
let unary = |f: fn(f32) -> f32| {
|
||||
(v.len() == 1).then(|| v[0].iter().map(|&x| f(x)).collect::<Vec<f32>>())
|
||||
};
|
||||
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<f32> = 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<Vec<f32>> {
|
||||
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<f32>,
|
||||
}
|
||||
|
||||
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<Expr, String> {
|
||||
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<Vec<Token>, String> {
|
||||
let chars: Vec<char> = 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::<String>()
|
||||
};
|
||||
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::<f32>()
|
||||
.or_else(|_| s.trim_end_matches(['f', 'F']).parse::<f32>())
|
||||
.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<Token>,
|
||||
at: usize,
|
||||
smooth: &'a mut usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn next(&mut self) -> Option<Token> {
|
||||
let t = self.tokens.get(self.at).cloned();
|
||||
self.at += 1;
|
||||
t
|
||||
}
|
||||
|
||||
fn peek_op(&self) -> Option<Op> {
|
||||
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<Expr, String> {
|
||||
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<Expr, String> {
|
||||
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<Expr, String> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<f32>> {
|
||||
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<Vec<f32>> {
|
||||
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}");
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,6 +96,15 @@ impl<L: LevelAccess + ?Sized> 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,
|
||||
|
||||
@@ -255,7 +255,37 @@ fn int_bounds(v: &Value, value: i32) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
fn load_dir(dir: &Path, prefix: &str, out: &mut HashMap<String, Value>) -> 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<i64> {
|
||||
v.as_i64().or_else(|| v.as_f64().map(|f| f as i64))
|
||||
}
|
||||
|
||||
/// `data/<ns>/<kind>/` 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<String, Value>) -> io::Result<()> {
|
||||
let Ok(entries) = fs::read_dir(data) else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut namespaces: Vec<String> = 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<String, Value>,
|
||||
) -> 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<String, Value>) -> 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<Self> {
|
||||
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<String, Value> =
|
||||
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<R: RandomSource> 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<R: RandomSource> 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<R: RandomSource> 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<R: RandomSource> 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<R: RandomSource> 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<R: RandomSource> 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<R: RandomSource> 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<BoundBlockProperty, DecodeError> {
|
||||
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(
|
||||
|
||||
@@ -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<bool, PlacementQueryError> {
|
||||
self.region.water_at(position)
|
||||
}
|
||||
|
||||
@@ -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<Vec<bool>> {
|
||||
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]
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -308,6 +308,7 @@ mod tests {
|
||||
waterlogging: None,
|
||||
yung: None,
|
||||
enhanced_terrain: own.map(Arc::new),
|
||||
ground_level: 1,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Self, DecodeError> {
|
||||
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<Self, DecodeError> {
|
||||
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::<f64>() / 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<i32> = 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::<f64>() / d.len() as f64;
|
||||
(max, mean)
|
||||
}
|
||||
|
||||
fn find_height(
|
||||
placement: Placement,
|
||||
context: &mut impl StartContext,
|
||||
b: BoundingBox,
|
||||
random: &mut impl RandomSource,
|
||||
) -> Option<i32> {
|
||||
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<i32> {
|
||||
let min = context.min_y();
|
||||
let points = corners_and_center(b);
|
||||
let heights: Vec<i32> = 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<i32> {
|
||||
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<Vec<i32>> = 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<Vec<i32>> = 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);
|
||||
}
|
||||
}
|
||||
@@ -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<Arc<super::enhanced_terrain::Adaptation>>,
|
||||
/// 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> {
|
||||
|
||||
@@ -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]),
|
||||
|
||||
@@ -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<lithostitched::Conditional>),
|
||||
/// `horizon:set_block` (Lithostitched's `set_block`).
|
||||
SetBlock(Box<lithostitched::SetBlock>),
|
||||
/// `horizon:pillar` (Repurposed Structures' and Moog's pillars): a
|
||||
/// trigger block starts a column down to the ground.
|
||||
Pillar(Box<pillars::Pillar>),
|
||||
/// `horizon:bottom_pillar` (Repurposed Structures'): the bottom layer
|
||||
/// continues down to the ground.
|
||||
BottomPillar(Box<pillars::BottomPillar>),
|
||||
/// `horizon:close_off_fluid_sources` (Repurposed Structures' and Moog's):
|
||||
/// fluid sources beside open blocks are walled off.
|
||||
CloseOffFluidSources(Box<pillars::CloseOffFluidSources>),
|
||||
/// `horizon:yung_pillar` (YUNG's pillars: Better Fortresses, Better
|
||||
/// Jungle Temples).
|
||||
YungPillar(Box<pillars::YungPillar>),
|
||||
/// `horizon:stair_pillar` (Better Fortresses' stair supports).
|
||||
StairPillar(Box<pillars::StairPillar>),
|
||||
/// `horizon:flood_air` (Better Ocean Monuments'): air below sea level
|
||||
/// becomes water.
|
||||
FloodAir(Box<sea_level::FloodAir>),
|
||||
/// `horizon:waterlog` (Better Ocean Monuments'): blocks below sea level
|
||||
/// are waterlogged.
|
||||
Waterlog,
|
||||
/// `horizon:keep_world_block` (Better Ocean Monuments' structure void).
|
||||
KeepWorldBlock(Box<sea_level::KeepWorldBlock>),
|
||||
}
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ProcessorList(pub Vec<Processor>);
|
||||
@@ -327,6 +351,12 @@ pub struct Pick {
|
||||
block: String,
|
||||
picks: Vec<(f32, Outcome)>,
|
||||
default: Option<Outcome>,
|
||||
/// 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::<Result<_, DecodeError>>()?,
|
||||
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<Self, DecodeError> {
|
||||
// Lists name lists (a pillar's, Lithostitched's): a cycle of names
|
||||
// is refused rather than followed.
|
||||
thread_local!(static DEPTH: std::cell::Cell<u32> = 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<Self, DecodeError> {
|
||||
let value: Value = serde_json::from_str(json)?;
|
||||
let value = match &value {
|
||||
@@ -1109,8 +1186,32 @@ fn process_block<W: PlacementContext>(
|
||||
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<f32>| {
|
||||
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.
|
||||
|
||||
@@ -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<FluidStateTable>,
|
||||
can_occlude: BoundBlockProperty,
|
||||
/// BlockState.isSolid (legacy solidity), for blocksMotion.
|
||||
solid: BoundBlockProperty,
|
||||
occlusion: BoundOcclusionFaces,
|
||||
replaceable_by_trees: Arc<BTreeSet<BlockStateId>>,
|
||||
unbreakable: BTreeSet<BlockStateId>,
|
||||
/// Cobweb and bamboo sapling, which never block motion.
|
||||
no_motion: BTreeSet<BlockStateId>,
|
||||
structure_void: BTreeSet<BlockStateId>,
|
||||
}
|
||||
impl Blocks {
|
||||
fn decode(bindings: &FeatureBlockBindings<'_>) -> Result<Self, DecodeError> {
|
||||
let block_set = |names: &[&str]| -> BTreeSet<BlockStateId> {
|
||||
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<W: PlacementContext>(
|
||||
world: &mut W,
|
||||
blocks: &Blocks,
|
||||
pos: [i32; 3],
|
||||
) -> Result<BlockStateId, PlacementQueryError> {
|
||||
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<W: PlacementContext>(
|
||||
world: &mut W,
|
||||
blocks: &Blocks,
|
||||
pos: [i32; 3],
|
||||
) -> Result<i32, PlacementQueryError> {
|
||||
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<Direction, DecodeError> {
|
||||
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<Option<ProcessorList>, 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<W: PlacementContext>(
|
||||
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<i32>, Option<i32>)>,
|
||||
default: BlockStateId,
|
||||
}
|
||||
impl HeightRandomizer {
|
||||
fn decode(
|
||||
v: &Value,
|
||||
state: &impl Fn(&Value) -> Result<BlockStateId, DecodeError>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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::<Result<_, DecodeError>>()?;
|
||||
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<ProcessorList>,
|
||||
direction: Direction,
|
||||
original: Option<BlockStateId>,
|
||||
length: i32,
|
||||
forced: bool,
|
||||
randomizer: Option<HeightRandomizer>,
|
||||
blocks: Blocks,
|
||||
}
|
||||
impl Pillar {
|
||||
pub(super) fn decode(
|
||||
v: &Value,
|
||||
resources: &StructureResources,
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
state: impl Fn(&Value) -> Result<BlockStateId, DecodeError>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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::<Result<_, DecodeError>>()?;
|
||||
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<W: PlacementContext>(
|
||||
&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<ProcessorList>,
|
||||
length: i32,
|
||||
forced: bool,
|
||||
blocks: Blocks,
|
||||
}
|
||||
impl BottomPillar {
|
||||
pub(super) fn decode(
|
||||
v: &Value,
|
||||
resources: &StructureResources,
|
||||
bindings: &FeatureBlockBindings<'_>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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<W: PlacementContext>(
|
||||
&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<bool, PlacementQueryError> {
|
||||
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<Self, DecodeError> {
|
||||
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::<Result<Vec<_>, 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<W: PlacementContext>(
|
||||
&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<f64>, Option<f64>)>,
|
||||
default: BlockStateId,
|
||||
}
|
||||
impl YungRandomizer {
|
||||
fn decode(
|
||||
v: &Value,
|
||||
state: &impl Fn(&Value) -> Result<BlockStateId, DecodeError>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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::<Result<_, DecodeError>>()?;
|
||||
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<i32>) -> 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<BlockStateId, DecodeError>,
|
||||
) -> Result<Self, DecodeError> {
|
||||
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<W: PlacementContext>(
|
||||
&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<Self, DecodeError> {
|
||||
let id = |v: &Value| -> Result<String, DecodeError> {
|
||||
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::<Result<_, DecodeError>>()?;
|
||||
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<String, String>,
|
||||
facing: Option<&str>,
|
||||
) -> Option<BlockStateId> {
|
||||
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<W: PlacementContext>(
|
||||
&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<f32>);
|
||||
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<BlockStateId, DecodeError> {
|
||||
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));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user