Merge remote-tracking branch 'origin/main' into cg15/1909

This commit is contained in:
Ludovic Marie
2026-10-26 05:06:59 +01:00
325 changed files with 25588 additions and 4814 deletions
+32 -2
View File
@@ -3,7 +3,8 @@ name: checks
# 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); .github/workflows/parity.yml. A fork's pull
# maintainer's own Minecraft files (Horizon never downloads the game); .github/workflows/parity.yml. Only for a pull
# request that changes a harness, oracle, probe or the runner: the rest are checked on main by parity-main. 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:
@@ -72,8 +73,37 @@ jobs:
run: |
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack
parity:
# Most pull requests leave the harnesses to parity-main, which runs them on main a batch of merges at a time
# (.github/workflows/parity-main.yml; releases wait for it). A pull request still runs them itself when it changes
# a harness, an oracle, a probe or the runner, or carries the run-parity label (run-parity.yml, when it is added).
parity-scope:
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
outputs:
run: ${{ steps.scope.outputs.run }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
- id: scope
env:
BASE_SHA: ${{ github.event.pull_request.base.sha }}
LABELS: ${{ join(github.event.pull_request.labels.*.name, ' ') }}
run: |
changed=$(git diff --name-only "$(git merge-base "$BASE_SHA" HEAD)" HEAD)
harness=$(grep -E '^(tools/test_[a-z0-9_]+_parity\.py|tools/(parity[a-z_]*|lab)\.py|tools/parity_hosts\.json|mods/horizon/src/test/|crates/[^/]+/examples/|crates/horizon-client/src/game/[a-z_]*(fixture|harness)\.rs|\.github/workflows/parity[a-z-]*\.yml)' <<< "$changed" || true)
if [ -n "$harness" ] || [[ " $LABELS " == *" run-parity "* ]]; then
echo "run=true" >> "$GITHUB_OUTPUT"
echo "The pull request runs its harnesses: ${harness:-label run-parity}"
else
echo "run=false" >> "$GITHUB_OUTPUT"
echo "No harness, oracle, probe or runner change: parity-main checks this on main"
fi
parity:
needs: parity-scope
if: needs.parity-scope.outputs.run == 'true'
uses: ./.github/workflows/parity.yml
with:
base: ${{ github.event.pull_request.base.sha }}
+2 -1
View File
@@ -29,7 +29,8 @@ env:
jobs:
audit:
runs-on: [self-hosted, horizon-game]
# The Mac mini's runners only: the audit compares with the previous one, so it stays on one platform.
runs-on: [self-hosted, horizon-game, macOS]
timeout-minutes: 150
steps:
- name: 03:00 in Paris
+74
View File
@@ -0,0 +1,74 @@
name: parity-main
# The vanilla harnesses on main, a batch of merges at a time (docs/release-flow.md#parity-on-main), on the Mac mini's
# runner. One run at a time: merges that land while a run goes on wait in one pending run (GitHub keeps only the
# newest), which checks every merge since main's last green parity-main (tools/parity_main.py base). On a failure it
# bisects the failing harnesses over those merges and comments on the pull request that broke them. Releases ship
# only a commit whose parity-main passed (tools/release_train.py), so nothing a harness catches reaches players.
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
# The comment on the merge that broke a harness.
pull-requests: write
# tools/parity_main.py base reads earlier runs.
actions: read
concurrency:
group: parity-main
cancel-in-progress: false
env:
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
HORIZON_TELEMETRY_URL: "off"
jobs:
parity-main:
# The Mac mini's release runner (label added 2026-10-26), not the two `horizon-game` runners: behind PR parity jobs
# this run waited 2 h while every merge replaced the pending one, and releases wait for it. Releases need it green
# first, so the two never compete. Not the desktop: a job slowed down because the maintainer came back could time
# out, and a failure here bisects and comments on merges.
runs-on: [self-hosted, macOS, horizon-parity-main]
timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.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: Main's last green parity-main
id: base
env:
GH_TOKEN: ${{ github.token }}
run: echo "sha=$(python3 tools/parity_main.py base)" >> "$GITHUB_OUTPUT"
- name: The harnesses the merges since then can affect
env:
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
run: |
echo "Merges since ${BASE_SHA}:"
git log --first-parent --format=' %h %s' "$BASE_SHA..HEAD"
python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400
- name: The merge that broke them
if: failure()
env:
GH_TOKEN: ${{ github.token }}
PARITY_HOSTS: ''
BASE_SHA: ${{ steps.base.outputs.sha }}
run: |
rm -rf .local/parity-main-logs && cp -R .local/parity-runner/logs .local/parity-main-logs 2>/dev/null || true
python3 tools/parity_main.py bisect "$BASE_SHA" --comment
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
with:
name: parity-main-logs
path: .local/parity-main-logs/
if-no-files-found: ignore
retention-days: 7
+57 -2
View File
@@ -36,14 +36,69 @@ jobs:
- 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
env:
BASE_SHA: ${{ inputs.base }}
run: |
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
set -euo pipefail
if git rev-parse --verify -q origin/main >/dev/null \
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
bash "$RUNNER_TEMP/vanilla-data.sh"
else
bash tools/ci/vanilla-data.sh
fi
- name: The prepared output is the one the preparer's OUTPUT_VERSION says
env:
BASE_SHA: ${{ inputs.base }}
run: python3 tools/prepare_output.py check --cache --base "$BASE_SHA"
- name: The version constants are the pinned jar's
run: python3 tools/gen_version_consts.py --check
- 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
run: |
# main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
# branch made before a better selection landed gets it too; the head's own runner then runs those
# harnesses. A branch that changes the selection itself selects with its own code.
set -euo pipefail
own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
fork_point=$(git merge-base "$BASE_SHA" HEAD)
if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
own
exit
fi
had_reach=$(git ls-files tools/parity_reach.py)
git show origin/main:tools/parity.py > tools/parity.py
git show origin/main:tools/parity_reach.py > tools/parity_reach.py
status=0
python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
git checkout -- tools/parity.py
if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
cat .local/parity-selection.txt
if [ "$status" != 0 ]; then
echo "main's selection failed: the head's own selection runs"
own
exit
fi
names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
# The summary line says how many would run: a count that doesn't match the names read (a format change)
# must not let the job pass untested.
expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
count=$(printf '%s' "$names" | grep -c . || true)
if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
own
exit
fi
if [ "$count" = 0 ]; then
echo "Nothing to run."
exit 0
fi
# shellcheck disable=SC2086
python3 tools/parity.py $names --timeout 2400
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
+52 -5
View File
@@ -1,6 +1,7 @@
name: release
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every 10 minutes (so a
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides:
# release waiting for merges to settle goes out without another merge) and by hand, tools/release_train.py decides,
# for a commit whose checks and parity-main (the vanilla harnesses on main) both passed:
# a release when 5 pull requests merged since the last one changed what players run and the newest merged 5 minutes
# ago, or when the oldest has waited 6 hours, or at once for a pull request labelled release-now.
# RELEASES_PAUSED=1 (repository variable) stops them; so does an open issue labelled release-blocker, forced runs too.
@@ -18,7 +19,8 @@ name: release
# gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say
on:
workflow_run:
workflows: [checks]
# A game release ships a commit both passed on (parity-main runs on batches: the newest commit it passed on).
workflows: [checks, parity-main]
types: [completed]
branches: [main]
schedule:
@@ -64,8 +66,8 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }}
# The commit whose checks just passed; a dry run builds the branch it was started on; otherwise
# main's newest commit with green checks.
# The commit whose checks or parity-main just passed; a dry run builds the branch it was started on;
# otherwise main's newest commit with green checks and parity-main.
HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }}
FORCE: ${{ inputs.force && 'yes' || '' }}
run: |
@@ -77,9 +79,50 @@ jobs:
# A dry run builds whatever the decision, to test the builds.
if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then echo "release=true" >> "$GITHUB_OUTPUT"; fi
build:
exporters:
needs: decide
if: needs.decide.outputs.release == 'true'
# This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it.
runs-on: ${{ vars.MAC_RUNNER || 'ludovics-mac-mini' }}
# Three full preparations (two isolated, one batched) besides the compile.
timeout-minutes: 60
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.decide.outputs.head }}
persist-credentials: false
clean: true
- uses: dtolnay/rust-toolchain@stable
- run: bash tools/ci/runner-env.sh
- run: bash tools/ci/vanilla-data.sh
- name: Compile and validate original exporters against the pinned jars
shell: bash
run: |
set -euo pipefail
# target/ is gone after the clean checkout, and vanilla-data.sh builds the preparer only when it
# prepares afresh.
cargo build --release --locked -p horizon-prepare
# Compiled here, never taken from the runner's shared preparations: pull requests' parity jobs
# write those (vanilla-data.sh links .local/exporters to them).
rm -rf .local/exporters
bundle=$(target/release/horizon-prepare compile-exporters --root "$PWD" | tail -1)
mkdir -p exporters
cp -R "$bundle/server" "$bundle/client" "$bundle/manifest.json" exporters/
# Only our classes and their manifest leave this runner.
stray=$(find exporters -type f ! -path exporters/manifest.json \
! \( -name '*.class' \( -path 'exporters/server/dev/horizonlab/parity/*' -o -path 'exporters/client/dev/horizonlab/parity/*' \) \))
[ -z "$stray" ] || { echo "::error::not one of our classes: $stray"; exit 1; }
python3 tools/check_prepare_exporters.py --binary target/release/horizon-prepare
- uses: actions/upload-artifact@v4
with:
name: original-exporters
path: exporters/
if-no-files-found: error
retention-days: 3
build:
needs: [decide, exporters]
if: needs.decide.outputs.release == 'true'
name: build ${{ matrix.name }}
strategy:
fail-fast: false
@@ -218,6 +261,10 @@ jobs:
path: ${{ runner.temp }}/smoke-test.json
if-no-files-found: error
retention-days: 3
- uses: actions/download-artifact@v4
with:
name: original-exporters
path: exporters
- name: Package
run: |
set -euo pipefail
+3
View File
@@ -31,3 +31,6 @@
/.horizon-cache/
/crash-reports/
/debug/
# Release-only compiled original exporter bundle.
/exporters/
+1 -1
View File
@@ -82,7 +82,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it.
- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`).
- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude horizon-mods-test-guest`.
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude predator-missile --exclude horizon-mods-test-guest --exclude horizon-mods-test-ui-guest`.
Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`).
- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build).
- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game):
Generated
+328 -310
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -1,6 +1,6 @@
[workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "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-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "xtask"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "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/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "xtask"]
resolver = "2"
[workspace.package]
+1 -1
View File
@@ -31,7 +31,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that re
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 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).
**You need** Minecraft: Java Edition 26.3, played once (the official launcher, Prism, MultiMC and other launchers all work); a Java 25 runtime, 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>
+32 -13
View File
@@ -16,7 +16,7 @@ Horizon is Minecraft: Java Edition 26.3 rewritten from scratch in Rust, so it ru
- **Single player as a server: the last differences**: Single player now runs a small server in the background, as vanilla does. We are fixing what still behaves differently there; every fix also works for LAN and server players.
- **Horizon's mod registry**: One place for mods, modpacks and resource packs made for Horizon: browse them on the website and install them from the launcher in one click.
**Next**: Microsoft sign-in (coming soon); CurseForge in the mod browser (coming soon); Fresh benchmarks against vanilla; Pistons push players and mobs; Horizon on Intel Macs; Faster world creation and entry on small CPUs; Servers that hold 20 TPS with 50 to 100 players; Low-end computers: Steam Deck, old Macs, 8 GB; Native upscaling; A batch of targeted optimisations; A Convert to Rust button for what isn't rewritten yet; Mods with code: machines, magic, mobs; Data packs in the mod browser; Prepare a version without Java; Server console, bans and a full admin API; Hosting polish: Windows service, safe updates; Guided hosting with Tailscale and an invite button; An official Docker image for servers; One single-player path: remove the in-frame world; Villages and combat, exactly as in vanilla; Choose the audio output device; Mods that read and change the world; Machines and blocks with inventories (API 0.4); Lua and other languages for mods; Well-known shader looks, rewritten for Horizon; A visible beta label; Wayland and Hyprland polish; A versioned agent-control protocol; Port mods with your own AI agent; Horizon on X (coming soon); Pipeline protection and a GitHub App for agents; Signed updates everywhere, installers included.
**Next**: Microsoft sign-in (coming soon); CurseForge in the mod browser (coming soon); Fresh benchmarks against vanilla; Pistons push players and mobs; Horizon on Intel Macs; Faster world creation and entry on small CPUs; Servers that hold 20 TPS with 50 to 100 players; Low-end computers: Steam Deck, old Macs, 8 GB; Native upscaling; A batch of targeted optimisations; A Convert to Rust button for what isn't rewritten yet; Mods with code: machines, magic, mobs; Data packs in the mod browser; Prepare a version without Java; Server console, bans and a full admin API; Hosting polish: Windows service, safe updates; Guided hosting with Tailscale and an invite button; An official Docker image for servers; One single-player path: remove the in-frame world; Villages and combat, exactly as in vanilla; Choose the audio output device; Mods that read and change the world; Machines and blocks with inventories (API 0.4); Lua and other languages for mods; Well-known shader looks, rewritten for Horizon; A visible beta label; Wayland and Hyprland polish; A versioned agent-control protocol; Port mods with your own AI agent; Horizon on X (coming soon); Pipeline protection and a GitHub App for agents; Signed updates everywhere, installers included; A server you install with one command.
**How to help**: Play it and tell us what differs from vanilla (Discord or GitHub), run the benchmark on your computer, vote for what you want next, or pick one of the Help wanted items.
@@ -374,6 +374,16 @@ More: [docs/server.md](docs/server.md)
</details>
#### A server you install with one command
Install and run a Horizon dedicated server from a terminal with a single command, no launcher needed, for VPSes and headless machines.
<details><summary>Technical</summary>
A player's idea (#horizon-ideas). `horizon-server` already runs headless; left: an install script (Linux/macOS shell, Windows PowerShell) that fetches the signed release, checks it, asks for or points at the player's own game files and starts the server, documented in [docs/hosting.md](docs/hosting.md).
</details>
### Mods and API
#### Mods that read and change the world
@@ -790,18 +800,6 @@ Issue [#1709](https://github.com/ludovic111/horizon/issues/1709): aarch64 builds
</details>
#### OpenGL for old computers
A way to play on old PCs and Linux machines that have no Vulkan or DirectX 12, through OpenGL.
<details><summary>Technical</summary>
Players on older hardware ask whether Vulkan is the only way. Horizon draws with wgpu, which has an OpenGL backend; what is needed is to see which features hold up on it, how fast it runs, and a launcher switch like the DirectX 12 fallback that already ships.
More: [docs/graphics.md](docs/graphics.md)
</details>
#### Android, iOS and the browser
Versions of Horizon for Android, iOS and web browsers. Nothing official yet; contributors have started the first pieces.
@@ -812,6 +810,16 @@ No official build. Android was first closed as not planned, with touch controls,
</details>
#### AppImage and a Nix flake
Install Horizon on any Linux distribution as an AppImage, and on NixOS through a Nix flake.
<details><summary>Technical</summary>
A player's idea (#horizon-ideas). An AppImage of the launcher and game from the release workflow, and a flake.nix packaging the release binaries with their runtime libraries (Vulkan loader, X11/Wayland, ALSA), the way horizon-parity's NixOS setup runs them today.
</details>
### Horizon extras
#### A complete video studio inside the game
@@ -824,6 +832,16 @@ Three stages. Recording: capture gameplay in a keypress with an encoder thread a
</details>
#### Game menus in the launcher's style
An optional look for the game's own menus and options that matches the Horizon launcher. Off by default: the vanilla menus stay as they are.
<details><summary>Technical</summary>
A player's idea (#horizon-ideas). A built-in resource pack or a Horizon setting that restyles the title, pause and options screens with the launcher's design tokens (crates/horizon-theme), following [docs/design-system.md](docs/design-system.md); off by default because it changes the vanilla look.
</details>
### AI and agents
#### An optional AI teammate
@@ -936,6 +954,7 @@ Vanilla's `Chicken.aiStep` updates `flap` and `flapSpeed` when the chicken isn't
## Recently shipped
- **OpenGL for old computers** (v0.2.63): Horizon now starts on old PCs whose graphics card has no Vulkan or DirectX 12 driver: it switches to OpenGL by itself, and Options > Graphics can pick OpenGL by hand. [#1917](https://github.com/ludovic111/horizon/issues/1917) · [#1920](https://github.com/ludovic111/horizon/issues/1920) · [#1936](https://github.com/ludovic111/horizon/issues/1936)
- **Server resource packs** (v0.2.48): Servers can send you their resource pack: Horizon asks, downloads it and applies it, like vanilla. [#1562](https://github.com/ludovic111/horizon/issues/1562) · [#1569](https://github.com/ludovic111/horizon/issues/1569) · [#1570](https://github.com/ludovic111/horizon/issues/1570)
- **Single player on its own server thread** (v0.2.39): Single player runs on a server thread, as vanilla does, so the world keeps ticking smoothly while the window draws. [#1514](https://github.com/ludovic111/horizon/issues/1514) · [docs/server-levels.md](docs/server-levels.md)
- **GPU occlusion culling on Macs** (v0.2.17): On Macs the GPU now skips terrain hidden behind hills and caves: 8 to 48% more frames per second at 32 chunks on an M4 Pro. [#1434](https://github.com/ludovic111/horizon/issues/1434)
+13
View File
@@ -208,6 +208,9 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
game_time: t,
day_time: 1000 + t,
}),
// The GUI of a 1280 x 720 window at scale 3.
gui_size: (427.0, 240.0),
..Snapshot::default()
});
mods.tick(t);
for _ in 0..FRAMES_PER_TICK {
@@ -224,9 +227,19 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
Output::Feedback { text, error } => {
format!("{}: {text}", if error { "error" } else { "feedback" })
}
Output::Command { line } => format!("command: /{line}"),
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
});
}
let shapes = mods.hud_shapes().count();
if shapes > 0 {
report.output.push(format!("drew {shapes} HUD shape(s)"));
}
match failed(&mods) {
Some(reason) => Err(format!("it stopped: {reason}")),
None => Ok(()),
+5
View File
@@ -68,6 +68,11 @@ rustix = { version = "1", default-features = false, features = ["std", "time"] }
# on the PATH.
wgpu = { version = "30.0.1", default-features = false, features = ["dx12"] }
[target.'cfg(not(target_os = "macos"))'.dependencies]
# OpenGL (WGL on Windows, EGL on Linux), the last fallback, for GPUs with no Vulkan or
# DirectX 12 driver (`graphicsApi`, graphics.rs).
wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
[target.'cfg(windows)'.build-dependencies]
# The icon resource in the .exe (build.rs).
winresource = "0.1"
@@ -367,6 +367,7 @@ pub fn main() -> Result<()> {
lid: &|_| open,
sign: &|_| sign.as_ref(),
banner: &|_| layers.clone(),
skull: &|_| None,
glyph: &|c| atlas.glyph_cell(c),
};
let mut verts = Vec::new();
@@ -7,7 +7,7 @@
//! usage: chat_screen_fixture RESOURCES REGISTRIES CASES OUTPUT
use crate::pack_screen_fixture;
use horizon_client::{
chat::{ChatAction, ChatScreen, Commands},
chat::{ChatAbilities, ChatAction, ChatScreen, ChatVisibility, Commands},
command::vanilla,
hud::HudAtlas,
lang,
@@ -53,6 +53,7 @@ pub fn main() -> horizon_client::Result<()> {
history.len(),
w,
h,
ChatAbilities::new(ChatVisibility::Full),
);
screen.auto_suggestions = case["autoSuggest"] == true;
let mut closed = false;
@@ -319,6 +319,7 @@ fn chat(c: &Value, h: i32, atlas: &HudAtlas) -> Vec<GuiDraw> {
atlas,
comp(&m["text"]),
indicator,
horizon_client::chat::ChatSource::Client,
m["at"].as_u64().unwrap_or(0),
false,
);
@@ -0,0 +1,53 @@
//! Lore tooltip companion for tools/test_lore_tooltip_parity.py: the spans
//! `item_tooltip::lore_texts` gives each stack (SNBT, one per line).
use horizon_client::{
item_data::parse_stack,
item_tooltip::{TooltipDisplay, lore_texts},
};
use std::{error::Error, fmt::Write};
pub fn main() -> Result<(), Box<dyn Error>> {
let args: Vec<String> = crate::args().collect();
let input = std::fs::read_to_string(&args[1])?;
let mut output = String::new();
for line in input
.lines()
.filter(|l| !l.is_empty() && !l.starts_with('#'))
{
let stack = parse_stack(line)?.ok_or("empty stack")?;
let display = TooltipDisplay::for_stack(&stack);
if !display.shows("minecraft:lore") {
writeln!(output, "-")?;
continue;
}
let lines = lore_texts(&stack);
if lines.is_empty() {
writeln!(output, "-")?;
continue;
}
let mut rendered = Vec::new();
for text in lines {
let mut spans = Vec::new();
for span in &text.spans {
if span.text.is_empty() {
continue;
}
let style = &span.style;
spans.push(format!(
"{}\t{}\t{}\t{}\t{}\t{}\t{}",
span.text,
style.color.map(|c| c as i32).unwrap_or(-1),
style.bold == Some(true),
style.italic == Some(true),
style.underlined == Some(true),
style.strikethrough == Some(true),
style.obfuscated == Some(true),
));
}
rendered.push(spans.join(" | "));
}
writeln!(output, "{}", rendered.join(" || "))?;
}
std::fs::write(&args[2], output)?;
Ok(())
}
@@ -49,6 +49,7 @@ mod input_probe;
mod interaction_input_fixture;
mod lan_probe;
mod light_parity;
mod lore_tooltip_fixture;
mod marker_particles_probe;
mod menu_fixture;
mod mipmap_probe;
@@ -133,6 +134,7 @@ probes! {
interaction_input_fixture,
lan_probe,
light_parity,
lore_tooltip_fixture,
marker_particles_probe,
menu_fixture,
mipmap_probe,
@@ -169,6 +169,7 @@ pub fn main() -> horizon_client::Result<()> {
cooking_timer: menu.data[2],
cooking_total: menu.data[3],
speed: 1.0,
recipes_used: Default::default(),
});
menu.drops.clear();
menu.equipped.clear();
@@ -598,6 +598,7 @@ fn print(out: &mut String, t: i32, i: usize, m: &Mob, player_down: bool, now: i6
let _ = writeln!(out, " removed {reason}");
return;
}
let _ = write!(out, "\tleashed {}", u8::from(m.extra.leash.is_some()));
let p = m.position;
let v = m.velocity;
let _ = write!(
@@ -977,6 +978,7 @@ pub fn main() -> horizon_client::Result<()> {
}
// Set once the brain exists (below).
x if x.starts_with("cooldown=") => {}
"dead" => m.health = 0.0,
"leashed" => m.extra.leash = Some(horizon_client::mobs::leash::Holder::Player),
x if x.starts_with("leashto=") => {
let n: u32 = x[8..].parse().unwrap();
@@ -1097,6 +1099,7 @@ pub fn main() -> horizon_client::Result<()> {
}
};
}
let mut dropped_leads = 0;
for t in 1..=s.ticks {
world.game_time += 1;
if s.daycycle {
@@ -1208,6 +1211,16 @@ pub fn main() -> horizon_client::Result<()> {
if !alive {
m.removed = true;
}
// Apply the same detach/drop event as Game::break_leash.
for event in &events[from..] {
if let MobEvent::LeashBreak { mob, drop, .. } = event
&& let Some(m) = mobs.iter_mut().find(|m| m.id == *mob)
&& horizon_client::mobs::leash::remove(m).is_some()
&& *drop
{
dropped_leads += 1;
}
}
horizon_client::mobs::apply_brain_events(&mut mobs, &mut events, from);
villager_events(
&mut mobs,
@@ -1427,6 +1440,9 @@ pub fn main() -> horizon_client::Result<()> {
world.game_time,
);
}
if s.name.starts_with("leash_death_") {
let _ = writeln!(out, "{t} leads {dropped_leads}");
}
for e in &events {
if let MobEvent::Sound(name, _, volume, pitch) = e {
let _ = writeln!(
+50
View File
@@ -63,6 +63,10 @@ enum Animate {
SculkSensor,
/// Potent sulfur that is not dry.
PotentSulfur,
DriedGhast {
waterlogged: bool,
},
EndPortal,
}
fn step(facing: &str) -> [i32; 3] {
match facing {
@@ -137,6 +141,10 @@ fn classify(name: &str, prop: &dyn Fn(&str) -> Option<String>) -> Animate {
drag: prop("drag").as_deref() == Some("true"),
},
"fire" | "soul_fire" => Animate::Fire,
"dried_ghast" => Animate::DriedGhast {
waterlogged: prop("waterlogged").as_deref() == Some("true"),
},
"end_portal" => Animate::EndPortal,
"sculk_sensor" | "calibrated_sculk_sensor"
if prop("sculk_sensor_phase").as_deref() == Some("active") =>
{
@@ -180,6 +188,8 @@ pub struct AnimateTables {
impermeable: Vec<bool>,
power_provider: Vec<bool>,
power_transmitter: Vec<bool>,
/// `#triggers_ambient_dried_ghast_block_sounds` (soul sand, soul soil).
dried_ghast_sounds: Vec<bool>,
/// Biome id -> ambient particles and probabilities (`minecraft:visual/ambient_particles`).
ambient: Vec<Vec<(T, f32)>>,
}
@@ -237,6 +247,7 @@ impl AnimateTables {
impermeable: by_state("minecraft:impermeable"),
power_provider: by_state("minecraft:enchantment_power_provider"),
power_transmitter: by_state("minecraft:enchantment_power_transmitter"),
dried_ghast_sounds: by_state("minecraft:triggers_ambient_dried_ghast_block_sounds"),
ambient,
})
}
@@ -869,6 +880,45 @@ fn block_animate_tick(
];
add(engine, T::Smoke, p, [0.0; 3]);
}
Animate::DriedGhast { waterlogged } => {
// DriedGhastBlock.animateTick.
let c = [fx + 0.5, fy + 0.5, fz + 0.5];
if waterlogged {
if next_int(engine.random(), 40) == 0 {
let name = "minecraft:block.dried_ghast.ambient_water";
sound(engine, name, c, 1.0, 1.0);
}
let r = engine.random();
if next_int(r, 6) == 0 {
let x = c[0] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0);
let y = c[1] + 0.4;
let z = c[2] + f64::from((r.next_float() * 2.0 - 1.0) / 3.0);
let v = [0.0, f64::from(r.next_float()), 0.0];
add(engine, T::HappyVillager, [x, y, z], v);
}
} else {
let below = ctx.state([pos[0], pos[1] - 1, pos[2]]);
let triggers = || {
tables
.dried_ghast_sounds
.get(below.0 as usize)
.copied()
.unwrap_or(false)
};
if next_int(engine.random(), 40) == 0 && triggers() {
sound(engine, "minecraft:block.dried_ghast.ambient", c, 1.0, 1.0);
}
if next_int(engine.random(), 6) == 0 {
add(engine, T::WhiteSmoke, c, [0.0, 0.02, 0.0]);
}
}
}
Animate::EndPortal => {
// EndPortalBlock.animateTick: one smoke particle above the surface.
let r = engine.random();
let p = [fx + r.next_double(), fy + 0.8, fz + r.next_double()];
add(engine, T::Smoke, p, [0.0; 3]);
}
Animate::EnderChest => {
for _ in 0..3 {
let r = engine.random();
@@ -730,6 +730,10 @@ pub struct Scene<'a> {
pub sign: &'a dyn Fn([i32; 3]) -> Option<&'a crate::signs::SignData>,
/// Banner layers at a position: pattern texture and RGB tint, bottom first.
pub banner: &'a dyn Fn([i32; 3]) -> Vec<(String, u32)>,
/// The skin sprite a `player_head` shows at a position (`SkullBlockRenderer`
/// profile → skin): a downloaded `skins/<sha1>` slot or the profile's
/// `DefaultPlayerSkin` fallback; None keeps `SKIN_BY_TYPE` (`DefaultPlayerSkin.getDefaultTexture`, slim steve).
pub skull: &'a dyn Fn([i32; 3]) -> Option<&'a str>,
/// Font glyph cell (none for blank glyphs such as the space) and advance.
pub glyph: &'a dyn Fn(char) -> (Option<Rect>, f32),
}
@@ -1279,6 +1283,13 @@ impl BlockEntityRenderer {
SkullType::Piglin => ("piglin_head", "entity/piglin/piglin"),
SkullType::Player => ("player_head", "entity/player/slim/steve"),
};
// SkullBlockRenderer.getRenderType: the profile's skin when it
// resolves, `SKIN_BY_TYPE` (steve) otherwise.
let texture = if *kind == SkullType::Player {
(scene.skull)(pos).unwrap_or(texture)
} else {
texture
};
let (Some(model), Some(paint)) =
(self.models.get(model), paint(texture, 0xFFFFFF, packed))
else {
@@ -1886,6 +1897,7 @@ mod tests {
lid: &|_| 0.0,
sign: &|_| None,
banner: &|_| Vec::new(),
skull: &|_| None,
glyph: &|_| (None, 0.0),
};
// Compare the cached world path with the original model renderer,
+34
View File
@@ -87,6 +87,19 @@ fn filled(player: &mut dyn Player, new: ItemStack, limit_creative: bool) {
}
}
/// `LayeredCauldronBlock.handleEntityOnFireInside`: a burning entity in a
/// water cauldron lowers it a level; a powder snow cauldron becomes a water
/// cauldron of its level first, then lowers.
pub fn extinguished(cauldron: &BlockState) -> BlockState {
if cauldron.name == "minecraft:powder_snow_cauldron" {
let mut water = cauldron.clone();
water.name = "minecraft:water_cauldron".into();
lowered(&water)
} else {
lowered(cauldron)
}
}
/// `LayeredCauldronBlock.lowerFillLevel`.
fn lowered(cauldron: &BlockState) -> BlockState {
let level: u8 = cauldron
@@ -296,3 +309,24 @@ pub fn interact(
_ => pass(),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_burning_entity_lowers_water_and_melts_powder_snow() {
let water = |l| state("minecraft:water_cauldron", Some(l));
assert_eq!(extinguished(&water(3)), water(2));
assert_eq!(extinguished(&water(1)), state("minecraft:cauldron", None));
// Powder snow turns to water of its level, then lowers.
assert_eq!(
extinguished(&state("minecraft:powder_snow_cauldron", Some(3))),
water(2)
);
assert_eq!(
extinguished(&state("minecraft:powder_snow_cauldron", Some(1))),
state("minecraft:cauldron", None)
);
}
}
+167 -10
View File
@@ -19,6 +19,92 @@ mod tests;
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
/// `ChatVisiblity`: the Chat option's three values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChatVisibility {
Full,
System,
Hidden,
}
impl ChatVisibility {
/// Options.chatVisibility's saved value (0 full, 1 system, 2 hidden).
pub fn from_option(value: u8) -> Self {
match value {
0 => Self::Full,
1 => Self::System,
_ => Self::Hidden,
}
}
}
/// `ChatAbilities`: what the Chat option allows, as `Minecraft.computeChatAbilities`
/// derives it from the visibility alone (`ChatRestriction`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ChatAbilities {
pub send_messages: bool,
pub send_commands: bool,
pub receive_player_messages: bool,
pub receive_system_messages: bool,
}
impl ChatAbilities {
/// `ChatRestriction.CHAT_AND_COMMANDS_DISABLED_BY_OPTIONS` (Hidden) takes
/// chat, commands, player messages and system messages;
/// `CHAT_DISABLED_BY_OPTIONS` (System) takes the chat and player messages.
pub fn new(visibility: ChatVisibility) -> Self {
match visibility {
ChatVisibility::Full => Self {
send_messages: true,
send_commands: true,
receive_player_messages: true,
receive_system_messages: true,
},
ChatVisibility::System => Self {
send_messages: false,
send_commands: true,
receive_player_messages: false,
receive_system_messages: true,
},
ChatVisibility::Hidden => Self {
send_messages: false,
send_commands: false,
receive_player_messages: false,
receive_system_messages: false,
},
}
}
/// `visibleMessagesFilter`: the client's own lines always show.
pub fn shows(&self, source: ChatSource) -> bool {
match source {
ChatSource::Player => self.receive_player_messages,
ChatSource::Server => self.receive_system_messages,
ChatSource::Client => true,
}
}
/// Whether the chat screen may send `input` (`hasAllowedInput`).
pub fn allows(&self, input: &str) -> bool {
if input.starts_with('/') {
self.send_commands
} else {
self.send_messages
}
}
}
impl Default for ChatAbilities {
fn default() -> Self {
Self::new(ChatVisibility::Full)
}
}
/// Where a chat line came from (`GuiMessageSource`): the visibility filters
/// player messages and the server's, while the client's own always show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChatSource {
Player,
Server,
Client,
}
/// The chat options (doubles, as vanilla keeps them).
#[derive(Clone, Copy, Debug)]
pub struct ChatOptions {
@@ -71,6 +157,7 @@ struct Message {
added: u64,
content: Text,
indicator: Option<u32>,
source: ChatSource,
}
/// A wrapped line (`GuiMessage.Line`).
#[derive(Clone, Debug)]
@@ -105,6 +192,8 @@ pub struct Chat {
pub log: bool,
/// Messages added since the start, for the control socket's events.
pub received: u64,
/// The Chat option's `visibleMessageFilter` (`set_abilities`).
abilities: ChatAbilities,
}
impl Chat {
pub fn lines_per_page(&self, focused: bool) -> usize {
@@ -114,16 +203,32 @@ impl Chat {
fn max_width(&self) -> i32 {
(f64::from(self.options.width_px()) / self.options.scale).floor() as i32
}
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines.
/// ChatComponent.addMessage: wrap, prepend and trim to 100 lines. A
/// message the Chat option hides is dropped, unlogged.
pub fn add(
&mut self,
atlas: &HudAtlas,
content: Text,
indicator: Option<u32>,
source: ChatSource,
ticks: u64,
focused: bool,
) {
// ChatComponent.logChatMessage: every message is in the log.
self.add_message(&atlas.font, content, indicator, source, ticks, focused);
}
fn add_message(
&mut self,
font: &crate::font::Font,
content: Text,
indicator: Option<u32>,
source: ChatSource,
ticks: u64,
focused: bool,
) {
if !self.abilities.shows(source) {
return;
}
// ChatComponent.logChatMessage: every message shown is in the log.
crate::logging::write_only(log::Level::Info, &format!("[CHAT] {}", content.plain()));
if self.log {
println!("[CHAT] {}", content.plain());
@@ -132,16 +237,17 @@ impl Chat {
added: ticks,
content,
indicator,
source,
};
self.add_lines(atlas, &message, focused);
self.add_lines(font, &message, focused);
self.messages.insert(0, message);
self.messages.truncate(100);
self.received += 1;
}
fn add_lines(&mut self, atlas: &HudAtlas, message: &Message, focused: bool) {
fn add_lines(&mut self, font: &crate::font::Font, message: &Message, focused: bool) {
let width = self.max_width();
let content = self.displayed(&message.content);
for line in atlas.font.wrap_components(&content, width) {
for line in font.wrap_components(&content, width) {
if focused && self.scroll > 0 {
self.new_since_scroll = true;
self.scroll_by(1, focused);
@@ -167,16 +273,38 @@ impl Chat {
content.strip_legacy()
}
}
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat).
/// Re-wrap after a width or scale change (ChatComponent.rescaleChat),
/// keeping only the messages the Chat option shows.
pub fn rescale(&mut self, atlas: &HudAtlas) {
self.rewrap(&atlas.font);
}
fn rewrap(&mut self, font: &crate::font::Font) {
self.scroll = 0;
self.new_since_scroll = false;
self.lines.clear();
let messages: Vec<Message> = self.messages.iter().rev().cloned().collect();
let messages: Vec<Message> = self
.messages
.iter()
.rev()
.filter(|m| self.abilities.shows(m.source))
.cloned()
.collect();
for m in &messages {
self.add_lines(atlas, m, false);
self.add_lines(font, m, false);
}
}
/// `ChatComponent.setVisibleMessageFilter`: the Chat option changed;
/// the messages it now hides leave the chat, those it shows again return.
pub fn set_abilities(&mut self, font: &crate::font::Font, abilities: ChatAbilities) {
if self.abilities != abilities {
self.abilities = abilities;
self.rewrap(font);
}
}
/// Whether a message from `source` would show (`visibleMessagesFilter`).
pub fn shows(&self, source: ChatSource) -> bool {
self.abilities.shows(source)
}
pub fn clear(&mut self) {
self.messages.clear();
self.lines.clear();
@@ -437,6 +565,8 @@ pub struct ChatScreen {
allow_suggestions: bool,
keep_suggestions: bool,
pub auto_suggestions: bool,
/// `CommandSuggestions.setRestrictions`: what the Chat option allows.
pub abilities: ChatAbilities,
}
/// Local completions waiting for the server's reply to request `id`.
struct Awaiting {
@@ -482,6 +612,7 @@ impl ChatScreen {
history_len: usize,
width: i32,
height: i32,
abilities: ChatAbilities,
) -> Self {
let mut input = TextField::new(4, height - 12, width - 4, 12);
input.max_length = 256;
@@ -505,6 +636,7 @@ impl ChatScreen {
allow_suggestions: false,
keep_suggestions: false,
auto_suggestions: true,
abilities,
};
s.update_command_info(m, c);
s
@@ -522,7 +654,8 @@ impl ChatScreen {
if (width, height) != (self.width, self.height) {
let value = self.input.value.clone();
let auto = self.auto_suggestions;
*self = Self::new(m, c, &value, self.history_pos, width, height);
let abilities = self.abilities;
*self = Self::new(m, c, &value, self.history_pos, width, height, abilities);
self.auto_suggestions = auto;
}
}
@@ -604,6 +737,14 @@ impl ChatScreen {
self.pending = Some((range.0, list));
self.usage_width = 0;
self.usage_position = 0;
// CommandSuggestions.updateCommandInfo: the Chat option may take
// the messages.
if !self.abilities.send_messages {
let line =
Text::translate("chat_screen.messages_not_allowed", &[]).with_color(text::RED);
self.usage_width = m.width(&line);
self.usage.push(line);
}
} else {
self.awaiting = None;
self.pending = None;
@@ -708,6 +849,15 @@ impl ChatScreen {
}
self.usage.extend(entries);
}
// CommandSuggestions.updateUsageInfo: the Chat option may take the
// commands, under the usage. (Vanilla also counts a command with a
// message argument, `/say hi`, as a message; Horizon's parse keeps no
// argument kinds, so only a bare message does.)
if !self.abilities.send_commands {
self.usage.push(
Text::translate("chat_screen.commands_not_allowed", &[]).with_color(text::RED),
);
}
self.usage_width = self.usage.iter().map(|u| m.width(u)).max().unwrap_or(0);
self.usage_position = if self.usage.is_empty() {
0
@@ -842,7 +992,14 @@ impl ChatScreen {
}
match key {
K::Escape => return ChatAction::Close,
K::Enter | K::NumpadEnter => return ChatAction::Submit(self.normalized()),
K::Enter | K::NumpadEnter => {
// ChatScreen.keyPressed: without `hasAllowedInput` the input
// stays, unsent, and the screen stays open.
if !self.abilities.allows(&self.input.value) {
return ChatAction::None;
}
return ChatAction::Submit(self.normalized());
}
K::ArrowUp => self.move_in_history(m, c, history, -1),
K::ArrowDown => self.move_in_history(m, c, history, 1),
_ => {
+114 -5
View File
@@ -2,6 +2,11 @@ use super::*;
use crate::{font::Font, hud::Rect};
use std::{collections::HashMap, path::Path};
/// The Chat option's default: no restriction.
fn full() -> ChatAbilities {
ChatAbilities::new(ChatVisibility::Full)
}
fn font() -> Font {
// The missing-glyph metrics let these tests run without game assets.
Font::load(
@@ -139,7 +144,7 @@ fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
assert_eq!(link.component()["click_event"]["command"], expected);
let mut chat = Chat::default();
add(&mut chat, &font, Text::literal("Found at ").append(link));
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &commands, "draft", 0, 640, 360, full());
let x = 4.0 + f64::from(font.width("Found at "));
assert!(!screen.click(&m, &commands, x, 315.0));
let Some(ClickEvent::SuggestCommand(command)) = chat.click_at(&font, 360, x, 315.0) else {
@@ -176,7 +181,15 @@ fn history_arrows_recall_messages_and_restore_the_draft() {
registries: &registries,
};
let history = vec!["first message".to_owned(), "latest message".to_owned()];
let mut screen = ChatScreen::new(&m, &commands, "unfinished draft", history.len(), 640, 360);
let mut screen = ChatScreen::new(
&m,
&commands,
"unfinished draft",
history.len(),
640,
360,
full(),
);
for (key, expected) in [
(ArrowUp, "latest message"),
(ArrowUp, "first message"),
@@ -213,7 +226,7 @@ fn mod_commands_are_coloured_and_complete_like_vanilla_ones() {
dispatcher,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, line);
screen
};
@@ -259,7 +272,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
let tab = |screen: &mut ChatScreen| {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Tab, false, false);
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, "/bossbar get pt");
let (request, sent) = screen.take_request().expect("the server is asked");
assert_eq!(sent, "/bossbar get pt");
@@ -281,7 +294,7 @@ fn ask_server_nodes_wait_for_the_servers_completions() {
dispatcher: local,
registries: &registries,
};
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360);
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, full());
screen.type_text(&m, &c, "/bossbar get pt");
assert_eq!(screen.take_request(), None);
}
@@ -327,3 +340,99 @@ fn a_server_component_keeps_its_click_and_hover_events() {
let past = 4.0 + f64::from(font.width("CLICK")) + 20.0;
assert!(chat.hover_at(&font, 360, past, 315.0).is_none());
}
/// `ChatVisiblity`: Commands Only keeps the chat out, Hidden takes the
/// commands too (`ChatAbilities`), and Enter sends nothing the option hides.
#[test]
fn the_chat_option_decides_what_may_be_sent() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let c = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let enter = |screen: &mut ChatScreen| {
screen.key(&m, &c, &[], winit::keyboard::KeyCode::Enter, false, false)
};
for (visibility, chat, command) in [
(ChatVisibility::Full, true, true),
(ChatVisibility::System, false, true),
(ChatVisibility::Hidden, false, false),
] {
let abilities = ChatAbilities::new(visibility);
assert_eq!(abilities.allows("hi"), chat, "{visibility:?}");
assert_eq!(abilities.allows("/time set day"), command, "{visibility:?}");
for (line, allowed) in [("hi", chat), ("/time set day", command)] {
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, abilities);
screen.type_text(&m, &c, line);
match enter(&mut screen) {
ChatAction::Submit(sent) => {
assert!(allowed, "{visibility:?} sent {sent}");
assert_eq!(sent, line);
}
ChatAction::None => assert!(!allowed, "{visibility:?} kept {line}"),
ChatAction::Close => panic!("Enter does not close the chat"),
}
}
}
}
/// The restriction the option sets is a usage line: red, under the input, for
/// a command the Chat option takes and for a message it takes.
#[test]
fn restricted_input_says_why_it_will_not_send() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let c = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
let usage = |visibility, line: &str| {
let mut screen = ChatScreen::new(&m, &c, "", 0, 640, 360, ChatAbilities::new(visibility));
screen.type_text(&m, &c, line);
screen.usage.iter().map(|t| t.plain()).collect::<Vec<_>>()
};
assert_eq!(usage(ChatVisibility::Full, "hi"), Vec::<String>::new());
// The font has no language files here, so the line is its key.
assert_eq!(
usage(ChatVisibility::System, "hi"),
["chat_screen.messages_not_allowed"]
);
// A command the option allows says nothing about the restriction.
assert!(
!usage(ChatVisibility::System, "/time set day")
.iter()
.any(|line| line == "chat_screen.commands_not_allowed")
);
assert!(
usage(ChatVisibility::Hidden, "/time set day")
.iter()
.any(|line| line == "chat_screen.commands_not_allowed")
);
}
/// `ChatComponent.setVisibleMessageFilter`: a message the Chat option hides
/// on arrival is dropped; one already in the chat leaves it while the option
/// hides its kind and comes back when it shows it again.
#[test]
fn the_chat_option_filters_the_lines_both_ways() {
let font = font();
let mut chat = Chat::default();
let says = |chat: &mut Chat, text: &str, source| {
chat.add_message(&font, Text::literal(text), None, source, 0, false);
};
let shown =
|chat: &Chat| -> Vec<String> { chat.lines.iter().map(|l| l.content.plain()).collect() };
says(&mut chat, "player", ChatSource::Player);
says(&mut chat, "server", ChatSource::Server);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::System));
assert_eq!(shown(&chat), ["server"]);
says(&mut chat, "dropped", ChatSource::Player);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Hidden));
says(&mut chat, "client", ChatSource::Client);
assert_eq!(shown(&chat), ["client"]);
chat.set_abilities(&font, ChatAbilities::new(ChatVisibility::Full));
assert_eq!(shown(&chat), ["client", "server", "player"]);
}
+18
View File
@@ -92,6 +92,13 @@ impl<W: BlockCollisionWorld> BlockCollisionWorld for EntityCollisions<'_, W> {
) -> std::result::Result<bool, Self::Error> {
self.blocks.is_suffocating(chunk, block, p)
}
fn may_reach_out(
&mut self,
chunk: Self::Chunk,
section_y: i32,
) -> std::result::Result<bool, Self::Error> {
self.blocks.may_reach_out(chunk, section_y)
}
fn context_shape(
&mut self,
block: CollisionBlock,
@@ -262,6 +269,17 @@ impl<'w> BlockCollisionWorld for SceneCollisions<'w, '_> {
fn collision_block(&mut self, chunk: Self::Chunk, p: BlockPos) -> io::Result<CollisionBlock> {
self.binding.collision_block(chunk.block(p.x, p.y, p.z))
}
/// From the section's palette, without reading its blocks; a palette
/// of the whole registry reads every cell.
fn may_reach_out(&mut self, chunk: Self::Chunk, section_y: i32) -> io::Result<bool> {
let blocks = usize::try_from(section_y - (crate::chunk::MIN_Y >> 4))
.ok()
.and_then(|s| chunk.sections.get(s))
.map(|section| &section.blocks);
Ok(blocks.is_none_or(|blocks| {
blocks.is_global() || blocks.maybe_has(|v| self.binding.reaches_out(BlockStateId(v)))
}))
}
fn is_suffocating(
&mut self,
_: Self::Chunk,
@@ -592,3 +592,21 @@ fn mod_commands_join_the_tree_for_every_player() {
// The game's own tree is left as it was.
assert!(vanilla::game_dispatcher().find("where").is_none());
}
#[test]
fn horizon_commands_are_off_unless_the_server_turns_them_on() {
// By default the game runs vanilla's tree: /help lists no /pregen.
assert!(vanilla::game_dispatcher().find("pregen").is_none());
for dev in [false, true] {
let vanilla_tree = vanilla::game_tree(dev, false);
assert!(vanilla_tree.find("pregen").is_none());
let d = vanilla::game_tree(dev, true);
let parse = d.parse("pregen start 100 circle", &reg());
assert_eq!(parse.executable().unwrap().1, "pregen.start");
// Vanilla's commands are the same with or without it.
assert_eq!(
d.nodes[0].children.len(),
vanilla_tree.nodes[0].children.len() + 1
);
}
}
+62 -5
View File
@@ -538,12 +538,69 @@ fn apply_vanilla_order(d: &mut Dispatcher) {
}
/// The tree the game runs: a release integrated server's, or with
/// `HORIZON_DEV_COMMANDS` set the development one
/// (SharedConstants.DEBUG_DEV_COMMANDS).
/// (SharedConstants.DEBUG_DEV_COMMANDS), plus Horizon's own commands when
/// the server turned them on (`set_horizon_commands`).
pub fn game_dispatcher() -> &'static Dispatcher {
if std::env::var_os("HORIZON_DEV_COMMANDS").is_some() {
dispatcher()
} else {
release_dispatcher()
game_tree(
std::env::var_os("HORIZON_DEV_COMMANDS").is_some(),
HORIZON_COMMANDS.load(std::sync::atomic::Ordering::Relaxed),
)
}
/// Whether this process's server has Horizon's own commands (`/pregen`). Off
/// by default, so `/help` and the command tree are vanilla's; a dedicated
/// server turns them on with `horizon-pregen=true` in server.properties, the
/// game with `--pregen` (docs/pregeneration.md).
static HORIZON_COMMANDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
/// Turns Horizon's own commands on or off for the trees `game_dispatcher`
/// returns from now on.
pub fn set_horizon_commands(on: bool) {
HORIZON_COMMANDS.store(on, std::sync::atomic::Ordering::Relaxed);
}
/// The server.properties key that turns `/pregen` on (Horizon's own; vanilla
/// ignores keys it doesn't know).
pub const PREGEN_PROPERTY: &str = "horizon-pregen";
pub(crate) fn game_tree(dev: bool, horizon: bool) -> &'static Dispatcher {
static HORIZON: [std::sync::OnceLock<Dispatcher>; 2] =
[const { std::sync::OnceLock::new() }; 2];
match (dev, horizon) {
(true, false) => dispatcher(),
(false, false) => release_dispatcher(),
(dev, true) => HORIZON[usize::from(dev)].get_or_init(|| {
let mut d = build_with(dev);
horizon_commands(&mut d, 0);
d
}),
}
}
/// Commands vanilla doesn't have, after its own: `/pregen`
/// (docs/pregeneration.md).
fn horizon_commands(d: &mut Dispatcher, root: usize) {
let pregen = d.literal(root, "pregen");
d.requires(pregen, GAMEMASTERS);
let start = d.literal(pregen, "start");
let radius = d.argument(
start,
"radius",
ArgType::Integer {
min: 0,
max: 30_000_000,
},
);
d.executes(radius, "pregen.start");
for shape in ["square", "circle"] {
let shape = d.literal(radius, shape);
d.executes(shape, "pregen.start");
let center = d.argument(shape, "center", ArgType::ColumnPos);
d.executes(center, "pregen.start");
}
for (word, id) in [
("pause", "pregen.pause"),
("continue", "pregen.continue"),
("cancel", "pregen.cancel"),
("status", "pregen.status"),
] {
let w = d.literal(pregen, word);
d.executes(w, id);
}
}
pub fn dispatcher() -> &'static Dispatcher {
+116 -3
View File
@@ -44,6 +44,10 @@ pub struct Furnace {
pub cooking_timer: i32,
pub cooking_total: i32,
pub speed: f32,
/// `AbstractFurnaceBlockEntity.recipesUsed`: how many of each recipe this furnace has
/// made since a player last took from its output. The experience is owed per recipe
/// rather than per item, and a save keeps it as the `RecipesUsed` compound.
pub recipes_used: HashMap<String, u32>,
}
/// A hopper's slots: the only plain container with five.
pub const HOPPER_SLOTS: usize = 5;
@@ -79,6 +83,60 @@ pub enum BlockEntity {
Beehive(Box<crate::beehive::Beehive>),
/// `CommandBlockEntity` of the three command blocks (`crate::command_block`).
CommandBlock(Box<crate::command_block::CommandBlock>),
/// `SkullBlockEntity` of every skull and head block.
Skull(Skull),
}
/// `SkullBlockEntity`: the player profile the head shows (kept as loaded:
/// a compound, or a string when it names a player only), the note block
/// sound and `custom_name`.
#[derive(Clone, Debug, Default)]
pub struct Skull {
pub profile: Option<horizon_world::nbt::Tag>,
pub note_block_sound: Option<String>,
pub custom_name: Option<horizon_world::nbt::Tag>,
/// What `profile` draws, read from it once rather than every frame.
pub skin: Option<SkullSkin>,
}
impl Skull {
pub fn new(
profile: Option<horizon_world::nbt::Tag>,
note_block_sound: Option<String>,
custom_name: Option<horizon_world::nbt::Tag>,
) -> Self {
let skin = profile.as_ref().map(SkullSkin::of);
Self {
profile,
note_block_sound,
custom_name,
skin,
}
}
}
/// `SkullBlockRenderer.getPlayerSkin` of a head's profile: its skin's URL
/// with the `skins/<sha1>` sprite it downloads to, and the
/// `DefaultPlayerSkin` drawn until that sprite is there (steve for a
/// profile with no id).
#[derive(Clone, Debug)]
pub struct SkullSkin {
pub download: Option<(String, String)>,
pub fallback: &'static str,
}
impl SkullSkin {
pub fn of(profile: &horizon_world::nbt::Tag) -> Self {
let download = crate::skins::profile_skin_url_nbt(profile).and_then(|url| {
let location = crate::skins::skin_location(&crate::skins::texture_hash(&url)?);
Some((url, location))
});
// DefaultPlayerSkin.get(id), or getDefaultSkin (slim steve) without an id.
let fallback = crate::skins::profile_uuid_nbt(profile)
.map_or("entity/player/slim/steve", crate::tab_list::default_skin);
Self { download, fallback }
}
}
/// The skull and head blocks (`SkullBlock`, `WallSkullBlock`): every
/// `*_skull` and `*_head` but the piston's head.
fn is_skull(name: &str) -> bool {
name.ends_with("_skull") || (name.ends_with("_head") && name != "minecraft:piston_head")
}
/// `CrafterBlockEntity`: nine slots that can be disabled, the powered flag
/// and the ticks left in the crafting animation.
@@ -190,6 +248,7 @@ impl BlockEntity {
cooking_timer: 0,
cooking_total: 0,
speed: 1.0,
recipes_used: HashMap::new(),
}));
}
if name == "minecraft:creaking_heart" {
@@ -233,6 +292,9 @@ impl BlockEntity {
if name.ends_with("_banner") {
return Some(Self::Banner(Banner::default()));
}
if is_skull(name) {
return Some(Self::Skull(Skull::default()));
}
if name == "minecraft:beacon" {
return Some(Self::Beacon(Box::new(Beacon {
last_check_y: i32::MIN / 2,
@@ -278,6 +340,7 @@ impl BlockEntity {
Self::Vault(_) => "minecraft:vault",
Self::Beehive(_) => "minecraft:beehive",
Self::CommandBlock(_) => "minecraft:command_block",
Self::Skull(_) => "minecraft:skull",
}
}
pub fn contents(&self) -> Vec<ItemStack> {
@@ -293,7 +356,8 @@ impl BlockEntity {
| Self::TrialSpawner(_)
| Self::Vault(_)
| Self::Beehive(_)
| Self::CommandBlock(_) => Vec::new(),
| Self::CommandBlock(_)
| Self::Skull(_) => Vec::new(),
Self::Lectern(l) => l.book.iter().cloned().collect(),
Self::Sculk(_) => Vec::new(),
Self::Banner(_) => Vec::new(),
@@ -310,7 +374,8 @@ impl BlockEntity {
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &[],
| Self::Banner(_)
| Self::Skull(_) => &[],
Self::Crafter(c) => &c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
@@ -330,7 +395,8 @@ impl BlockEntity {
| Self::Beacon(_)
| Self::Lectern(_)
| Self::Sculk(_)
| Self::Banner(_) => &mut [],
| Self::Banner(_)
| Self::Skull(_) => &mut [],
Self::Crafter(c) => &mut c.items,
Self::CreakingHeart(_)
| Self::Spawner(_)
@@ -483,6 +549,14 @@ impl Furnace {
self.cooking_timer = 0;
}
}
/// `recipesUsed`, each recipe with its `experience` (0 for one this data pack does
/// not have), in the order `getRecipesToAwardAndPopExperience` pays them.
pub fn recipe_experience(&self, recipes: &Recipes) -> Vec<(u32, f32)> {
self.recipes_used
.iter()
.map(|(id, count)| (*count, recipes.cooking_experience(id)))
.collect()
}
/// A menu click wrote its slots into `items`, and `before` was the input
/// slot until then: the menu called `setItem` on it only if it changed
/// (`Slot.setByPlayer`; partial takes and merges keep the stack).
@@ -564,6 +638,7 @@ impl Furnace {
Some(out) => out.count += recipe.result.count,
None => self.items[2] = Some(recipe.result.clone()),
}
*self.recipes_used.entry(recipe.id.clone()).or_insert(0) += 1;
if let Some(i) = self.items[0].as_mut() {
i.count -= 1;
if i.count == 0 {
@@ -594,3 +669,41 @@ fn total_time(time: u32, speed: f32) -> i32 {
time as i32
}
}
/// `AbstractFurnaceBlockEntity.createExperience`: `count * experience`, floored, and one
/// more with the chance of what is left over (a level random draw only when there is some).
pub fn create_experience(
count: u32,
experience: f32,
random: &mut impl horizon_core::random::RandomSource,
) -> u32 {
let total = count as f32 * experience;
let whole = total.floor();
let fraction = total - whole;
let mut xp = whole.max(0.0) as u32;
if fraction != 0.0 && random.next_float() < fraction {
xp += 1;
}
xp
}
#[cfg(test)]
mod tests {
use super::*;
use horizon_core::random::{LegacyRandom, RandomSource};
/// A whole amount pays itself without a draw; a fraction is a chance of one more.
#[test]
fn create_experience_rounds_the_fraction_by_chance() {
let mut random = LegacyRandom::new(7);
let mut untouched = LegacyRandom::new(7);
assert_eq!(create_experience(4, 0.5, &mut random), 2);
assert_eq!(create_experience(3, 0.0, &mut random), 0);
assert_eq!(random.next_long(), untouched.next_long());
let paid: u32 = (0..1000)
.map(|_| create_experience(1, 0.35, &mut random))
.sum();
assert!((250..450).contains(&paid), "{paid}");
assert!((0..100).all(|_| (1..=2).contains(&create_experience(1, 1.7, &mut random))));
}
}
+174
View File
@@ -0,0 +1,174 @@
//! `Player.getCooldowns()` (`ItemCooldowns`) as the game keeps it: the
//! `use_cooldown` component's entries by cooldown group, counted down once a
//! tick, and the percent `GuiGraphicsExtractor.itemCooldown` shades a slot
//! by. The world crate's `item_cooldowns` models vanilla's hash map and its
//! observers for the parity harness; this is the same data with the lookup a
//! slot needs, and no observer (vanilla's own player uses the plain class).
use crate::items::ItemStack;
use horizon_world::nbt::Tag;
use std::collections::HashMap;
use std::sync::Arc;
/// A stack's `minecraft:use_cooldown` component.
#[derive(Clone, Debug, PartialEq)]
pub struct UseCooldown {
pub seconds: f32,
/// `cooldown_group`: the group the entry is filed under, else the item.
pub group: Option<Arc<str>>,
}
impl UseCooldown {
/// `UseCooldown.ticks`: the seconds in ticks, truncated.
pub fn ticks(&self) -> i32 {
(self.seconds * 20.0) as i32
}
/// The component as `items.json` holds it.
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
let seconds = v.get("seconds")?.as_f64()? as f32;
Some(Self {
seconds,
group: v
.get("cooldown_group")
.and_then(|g| g.as_str())
.map(Arc::from),
})
}
/// The component as a stack's saved `components` holds it.
pub fn from_tag(t: &Tag) -> Option<Self> {
let Tag::Compound(c) = t else {
return None;
};
let text = |k: &str| match c.get(&horizon_world::nbt::JavaString::from(k)) {
Some(Tag::String(s)) => Some(s.to_string_lossy()),
_ => None,
};
let seconds = match c.get(&horizon_world::nbt::JavaString::from("seconds")) {
Some(Tag::Float(bits)) => f32::from_bits(*bits),
Some(Tag::Double(bits)) => f64::from_bits(*bits) as f32,
_ => return None,
};
Some(Self {
seconds,
group: text("cooldown_group").map(Arc::from),
})
}
}
/// The component a stack carries: its own patch first (`ItemStack.get`), then
/// the item's default from `items.json` (`ItemInfo::use_cooldown`).
pub fn component(stack: &ItemStack, default: Option<&UseCooldown>) -> Option<UseCooldown> {
stack
.data()
.and_then(|d| d.other("minecraft:use_cooldown"))
.and_then(UseCooldown::from_tag)
.or_else(|| default.cloned())
}
/// `ItemCooldowns.getCooldownGroup`: the component's group, else the item id.
pub fn group(stack: &ItemStack, default: Option<&UseCooldown>) -> Arc<str> {
component(stack, default)
.and_then(|c| c.group)
.unwrap_or_else(|| Arc::clone(&stack.item))
}
/// `ItemCooldowns`: start and end ticks by group, and the tick counter.
#[derive(Clone, Debug, Default)]
pub struct Cooldowns {
tick_count: i32,
entries: HashMap<Arc<str>, (i32, i32)>,
}
impl Cooldowns {
/// `getCooldownPercent`: what is left of the entry, from 1 to 0.
pub fn percent(&self, group: &str, partial_tick: f32) -> f32 {
let Some((start, end)) = self.entries.get(group) else {
return 0.0;
};
let duration = end.wrapping_sub(*start) as f32;
let remaining = *end as f32 - (self.tick_count as f32 + partial_tick);
(remaining / duration).clamp(0.0, 1.0)
}
/// `isOnCooldown`: whether the group still has time to run.
pub fn is_on_cooldown(&self, group: &str) -> bool {
self.percent(group, 0.0) > 0.0
}
/// `addCooldown`.
pub fn add(&mut self, group: Arc<str>, ticks: i32) {
self.entries.insert(
group,
(self.tick_count, self.tick_count.wrapping_add(ticks)),
);
}
/// `ItemCooldowns.tick`: the counter, then every entry that has run out,
/// which it hands back (`onCooldownEnded`).
pub fn tick(&mut self) -> Vec<Arc<str>> {
self.tick_count = self.tick_count.wrapping_add(1);
let done: Vec<Arc<str>> = self
.entries
.iter()
.filter(|(_, (_, end))| *end <= self.tick_count)
.map(|(group, _)| Arc::clone(group))
.collect();
self.entries.retain(|_, (_, end)| *end > self.tick_count);
done
}
/// `removeCooldown`.
pub fn remove(&mut self, group: &str) {
self.entries.remove(group);
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn stack(item: &str) -> ItemStack {
ItemStack::new(item, 1)
}
#[test]
fn the_percent_falls_from_one_to_zero_over_the_entry() {
let mut c = Cooldowns::default();
c.add(Arc::from("minecraft:ender_pearl"), 20);
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 1.0);
for _ in 0..10 {
assert!(c.tick().is_empty());
}
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.5);
// The partial tick moves it within the tick.
assert_eq!(c.percent("minecraft:ender_pearl", 0.5), 0.475);
for _ in 0..9 {
c.tick();
}
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
// ItemCooldowns.tick drops the entry at its end tick, and says so.
assert_eq!(c.tick(), [Arc::<str>::from("minecraft:ender_pearl")]);
assert!(!c.is_on_cooldown("minecraft:ender_pearl"));
assert!(c.is_empty());
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.0);
}
#[test]
fn the_group_comes_from_the_stack_then_the_item() {
let pearl = stack("minecraft:ender_pearl");
let default = UseCooldown::from_json(&json!({"seconds": 1.0})).expect("the component");
assert_eq!(&*group(&pearl, Some(&default)), "minecraft:ender_pearl");
// A stack's own component overrides the item's, group included.
let mut grouped = stack("minecraft:ender_pearl");
grouped.data_mut().set_other(
"minecraft:use_cooldown",
Some(Tag::compound([
("seconds", Tag::Float(2.0f32.to_bits())),
("cooldown_group", Tag::String("minecraft:pearls".into())),
])),
);
let c = component(&grouped, Some(&default)).expect("the stack's component");
assert_eq!(c.ticks(), 40);
assert_eq!(&*group(&grouped, Some(&default)), "minecraft:pearls");
// An item without the component has no cooldown.
assert!(component(&stack("minecraft:dirt"), None).is_none());
}
}
+8
View File
@@ -1610,6 +1610,14 @@ impl Recipes {
}
out
}
/// The `experience` of the cooking recipe with this file name, and 0 for one this data
/// pack does not have (a save from another pack can name it).
pub fn cooking_experience(&self, id: &str) -> f32 {
self.cooking
.iter()
.find(|c| c.id == id)
.map_or(0.0, |c| c.experience)
}
pub fn cook(&self, kind: &str, input: &ItemStack) -> Option<&Cooking> {
let index = self.cook_index.get_or_init(|| {
let mut index = CookIndex::new();
+90 -2
View File
@@ -71,10 +71,52 @@ impl Names {
.cloned()
.unwrap_or_else(|| path.replace('_', " "))
}
/// An item's display name in the selected language: `item.*` then
/// `block.*`, then the pinned English map (`Names::item`).
pub fn display_item(&self, id: &str) -> String {
let (namespace, path) = id.split_once(':').unwrap_or(("minecraft", id));
if let Some(lang) = crate::lang::current() {
for prefix in ["item", "block"] {
if let Some(name) = lang.get(&format!("{prefix}.{namespace}.{path}")) {
return name.to_owned();
}
}
}
self.item(id)
}
/// A translation key's text in the selected language, else the pinned
/// English map (`HoverName` and tooltip keys such as potion names).
pub fn display_get(&self, key: &str) -> Option<String> {
crate::lang::current()
.and_then(|lang| lang.get(key).map(str::to_owned))
.or_else(|| self.get(key).map(str::to_owned))
}
pub fn get(&self, key: &str) -> Option<&str> {
self.map.get(key).map(String::as_str)
}
}
/// `CreativeModeTabs`' key for an exported tab id (`itemGroup.*`); the
/// export's `title` is the English fallback.
pub fn item_group_key(id: &str) -> Option<&'static str> {
Some(match id.trim_start_matches("minecraft:") {
"building_blocks" => "itemGroup.buildingBlocks",
"colored_blocks" => "itemGroup.coloredBlocks",
"natural_blocks" => "itemGroup.natural",
"functional_blocks" => "itemGroup.functional",
"redstone_blocks" => "itemGroup.redstone",
"hotbar" => "itemGroup.hotbar",
"search" => "itemGroup.search",
"tools_and_utilities" => "itemGroup.tools",
"combat" => "itemGroup.combat",
"food_and_drinks" => "itemGroup.foodAndDrink",
"ingredients" => "itemGroup.ingredients",
"spawn_eggs" => "itemGroup.spawnEggs",
"op_blocks" => "itemGroup.op",
"inventory" => "itemGroup.inventory",
_ => return None,
})
}
impl Creative {
pub const WIDTH: f32 = 195.0;
pub const HEIGHT: f32 = 136.0;
@@ -303,7 +345,17 @@ impl Creative {
.collect();
}
// FullTextSearchTree: tooltip lines, and the item id after a colon.
// The export's lines are English (they come from the vanilla jars);
// the hover name in the selected language is matched too, so a
// localized search finds the item. It is the whole name (a tipped
// arrow's potion, the ominous banner), as the first line is.
let text = java_lower(term);
let localized = |i: usize| {
java_lower(&crate::item_tooltip::name_line(
&self.search_items[i],
&|k| names.display_get(k),
))
};
all.filter(|&i| {
let e = &self.search_index[i];
let fallback;
@@ -314,11 +366,15 @@ impl Creative {
&e.lines
};
match text.split_once(':') {
None => any(lines.iter().map(String::as_str), &text),
None => {
any(lines.iter().map(String::as_str), &text) || localized(i).contains(&text)
}
Some((ns, path)) => {
let (ns, path) = (java_trim(ns), java_trim(path));
e.namespace.contains(ns)
&& (e.path.contains(path) || any(lines.iter().map(String::as_str), path))
&& (e.path.contains(path)
|| any(lines.iter().map(String::as_str), path)
|| localized(i).contains(path))
}
}
})
@@ -759,6 +815,24 @@ mod tests {
assert_eq!(q("#craft"), Vec::<usize>::new());
}
#[test]
fn search_matches_the_display_name_in_the_selected_language() {
let c = creative(0);
let names = Names {
map: HashMap::from([
("item.minecraft.anvil".to_owned(), "铁砧".to_owned()),
("item.minecraft.wooden_hoe".to_owned(), "木锄".to_owned()),
]),
};
let q = |s: &str| c.search_results(s, &names);
assert_eq!(q("铁砧"), [0]);
assert_eq!(q("木锄"), [2]);
// The English tooltip lines the export indexed still match.
assert_eq!(q("anvil"), [0]);
// A colon's path searches the display name too.
assert_eq!(q("minecraft:铁砧"), [0]);
}
#[test]
fn scrollbar_drag_follows_the_mouse_while_held() {
let mut c = creative(90);
@@ -794,6 +868,20 @@ mod tests {
assert!(!c.scrolling);
}
#[test]
fn creative_tab_titles_have_vanilla_keys() {
assert_eq!(
item_group_key("minecraft:building_blocks"),
Some("itemGroup.buildingBlocks")
);
assert_eq!(
item_group_key("minecraft:food_and_drinks"),
Some("itemGroup.foodAndDrink")
);
assert_eq!(item_group_key("minecraft:hotbar"), Some("itemGroup.hotbar"));
assert_eq!(item_group_key("minecraft:nonsense"), None);
}
#[test]
fn wheel_moves_one_row_per_notch() {
let mut c = creative(90);
+794
View File
@@ -0,0 +1,794 @@
//! Server dialogs (`net.minecraft.server.dialog`): what `Dialog.DIRECT_CODEC`
//! decodes from a `show_dialog` packet, the values its inputs hold, and the
//! click event an action makes of them (`Action.createAction`).
use crate::text::Text;
use horizon_world::nbt::Tag;
use serde_json::{Value, json};
/// `CommonDialogData` and the type's own fields.
#[derive(Clone, Debug)]
pub struct Dialog {
pub kind: Kind,
pub title: Text,
pub external_title: Option<Text>,
pub can_close_with_escape: bool,
pub pause: bool,
pub after_action: AfterAction,
pub body: Vec<Body>,
pub inputs: Vec<Input>,
}
/// The dialog types (`DialogTypes`).
#[derive(Clone, Debug)]
pub enum Kind {
/// `NoticeDialog`: one button, "OK" when the server names none.
Notice(Button),
Confirmation {
yes: Button,
no: Button,
},
MultiAction {
actions: Vec<Button>,
exit: Option<Button>,
columns: i32,
},
ServerLinks {
exit: Option<Button>,
columns: i32,
button_width: i32,
},
/// `DialogListDialog`: its dialogs as sent (ids, a tag or inline dialogs).
DialogList {
dialogs: Tag,
exit: Option<Button>,
columns: i32,
button_width: i32,
},
}
/// `DialogAction`: the screen after an action runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AfterAction {
Close,
None,
WaitForResponse,
}
/// `ActionButton`: `CommonButtonData` and what it does.
#[derive(Clone, Debug)]
pub struct Button {
pub label: Text,
pub tooltip: Option<Text>,
pub width: i32,
pub action: Option<Action>,
}
/// `Action`: a fixed click event, or one made from the inputs' values.
#[derive(Clone, Debug, PartialEq)]
pub enum Action {
/// `StaticAction`: a click event as it is.
Static(Click),
/// `CommandTemplate`: a command with `$(key)` replaced by input values.
RunCommand(String),
/// `CustomAll`: a custom click event whose payload is `additions` plus
/// every input's value under its key.
Custom { id: String, additions: Option<Tag> },
}
/// `ClickEvent`, the kinds a server may send (`isAllowedFromServer`).
#[derive(Clone, Debug, PartialEq)]
pub enum Click {
OpenUrl(String),
RunCommand(String),
SuggestCommand(String),
/// The dialog: an id of the `minecraft:dialog` registry or the dialog itself.
ShowDialog(Tag),
ChangePage(i32),
CopyToClipboard(String),
Custom {
id: String,
payload: Option<Tag>,
},
}
/// `DialogBody`.
#[derive(Clone, Debug)]
pub enum Body {
/// `PlainMessage`: centred text wrapped to `width`.
Message { contents: Text, width: i32 },
/// `ItemBody`: the item as `ItemStackTemplate` sent it.
Item {
item: Tag,
description: Option<(Text, i32)>,
show_decorations: bool,
show_tooltip: bool,
width: i32,
height: i32,
},
}
/// `Input`: the key its value goes by, and its control.
#[derive(Clone, Debug)]
pub struct Input {
pub key: String,
pub control: Control,
}
/// `InputControl`.
#[derive(Clone, Debug)]
pub enum Control {
Text {
width: i32,
label: Text,
label_visible: bool,
initial: String,
max_length: i32,
/// `MultilineOptions`: the most lines and the height, when set.
multiline: Option<(Option<i32>, Option<i32>)>,
},
Boolean {
label: Text,
initial: bool,
on_true: String,
on_false: String,
},
SingleOption {
width: i32,
/// Each option's id, its label and whether it is the initial one.
options: Vec<(String, Option<Text>, bool)>,
label: Text,
label_visible: bool,
},
NumberRange {
width: i32,
label: Text,
label_format: String,
start: f32,
end: f32,
initial: Option<f32>,
step: Option<f32>,
},
}
/// What an input holds while the dialog is open.
#[derive(Clone, Debug, PartialEq)]
pub enum InputValue {
Text(String),
Bool(bool),
/// The chosen option's index.
Option(usize),
/// The slider's position, 0 to 1.
Slider(f32),
}
fn text(t: &Tag) -> Text {
crate::scoreboard::comp_text(&crate::scoreboard::tag_to_json(t))
}
fn string(t: Option<&Tag>) -> Option<String> {
match t? {
Tag::String(s) => Some(s.to_string_lossy()),
_ => None,
}
}
fn number(t: Option<&Tag>) -> Option<f64> {
Some(match t? {
Tag::Byte(v) => f64::from(*v),
Tag::Short(v) => f64::from(*v),
Tag::Int(v) => f64::from(*v),
Tag::Long(v) => *v as f64,
Tag::Float(v) => f64::from(f32::from_bits(*v)),
Tag::Double(v) => f64::from_bits(*v),
_ => return None,
})
}
fn int(t: &Tag, key: &str, default: i32) -> i32 {
number(t.get(key)).map_or(default, |v| v as i32)
}
fn boolean(t: &Tag, key: &str, default: bool) -> bool {
number(t.get(key)).map_or(default, |v| v != 0.0)
}
fn list(t: Option<&Tag>) -> &[Tag] {
match t {
Some(Tag::List(items)) => items,
_ => &[],
}
}
/// A registry name without its default namespace.
fn path(id: &str) -> &str {
id.strip_prefix("minecraft:").unwrap_or(id)
}
impl Button {
/// `ActionButton.CODEC`.
fn parse(t: &Tag) -> Option<Self> {
Some(Self {
label: text(t.get("label")?),
tooltip: t.get("tooltip").map(text),
width: int(t, "width", 150),
action: t.get("action").and_then(Action::parse),
})
}
/// `NoticeDialog.DEFAULT_ACTION`.
fn ok() -> Self {
Self {
label: Text::translate("gui.ok", &[]),
tooltip: None,
width: 150,
action: None,
}
}
}
impl Click {
/// `ClickEvent.CODEC`, from its `action` (a click event in a component)
/// or `type` (an action) field.
pub fn parse(t: &Tag, kind: &str) -> Option<Self> {
let s = |key| string(t.get(key));
Some(match path(kind) {
"open_url" => Self::OpenUrl(s("url")?),
"run_command" => Self::RunCommand(s("command")?),
"suggest_command" => Self::SuggestCommand(s("command")?),
"show_dialog" => Self::ShowDialog(t.get("dialog")?.clone()),
"change_page" => Self::ChangePage(int(t, "page", 1)),
"copy_to_clipboard" => Self::CopyToClipboard(s("value")?),
"custom" => Self::Custom {
id: s("id")?,
payload: t.get("payload").cloned(),
},
_ => return None,
})
}
}
impl Action {
/// `Action.CODEC`, dispatched on `type`.
fn parse(t: &Tag) -> Option<Self> {
let kind = string(t.get("type"))?;
Some(match path(&kind) {
"dynamic/run_command" => Self::RunCommand(string(t.get("template"))?),
"dynamic/custom" => Self::Custom {
id: string(t.get("id"))?,
additions: t.get("additions").cloned(),
},
other => Self::Static(Click::parse(t, other)?),
})
}
/// `createAction`: the click event, given each input's key, control and value.
pub fn click(&self, inputs: &[Input], values: &[InputValue]) -> Option<Click> {
let values = || inputs.iter().zip(values);
Some(match self {
Self::Static(click) => click.clone(),
Self::RunCommand(template) => Click::RunCommand(substitute(template, &|key| {
values()
.find(|(i, _)| i.key == key)
.map(|(i, v)| i.control.substitution(v))
})),
Self::Custom { id, additions } => {
let mut tag = match additions {
Some(t @ Tag::Compound(_)) => t.clone(),
_ => Tag::Compound(Default::default()),
};
for (input, value) in values() {
if let Tag::Compound(map) = &mut tag {
map.insert(input.key.as_str().into(), input.control.tag(value));
}
}
Click::Custom {
id: id.clone(),
payload: Some(tag),
}
}
})
}
}
/// `ParsedTemplate.instantiate`: each `$(key)` replaced by its value, or by
/// nothing for a key no input has.
fn substitute(template: &str, value: &dyn Fn(&str) -> Option<String>) -> String {
let mut out = String::new();
let mut rest = template;
while let Some(at) = rest.find("$(") {
let Some(end) = rest[at..].find(')') else {
break;
};
out.push_str(&rest[..at]);
out.push_str(&value(&rest[at + 2..at + end]).unwrap_or_default());
rest = &rest[at + end + 1..];
}
out.push_str(rest);
out
}
/// `StringTag.escapeWithoutQuotes`.
fn escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' | '\'' | '\\' => {
out.push('\\');
out.push(c);
}
'\u{8}' => out.push_str("\\b"),
'\t' => out.push_str("\\t"),
'\n' => out.push_str("\\n"),
'\u{c}' => out.push_str("\\f"),
'\r' => out.push_str("\\r"),
c if c < ' ' => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out
}
impl Control {
/// `InputControl.MAP_CODEC`, dispatched on `type`.
fn parse(t: &Tag) -> Option<Self> {
let label = || t.get("label").map(text);
Some(match path(&string(t.get("type"))?) {
"text" => Self::Text {
width: int(t, "width", 200),
label: label()?,
label_visible: boolean(t, "label_visible", true),
initial: string(t.get("initial")).unwrap_or_default(),
max_length: int(t, "max_length", 32),
multiline: t.get("multiline").map(|m| {
let get = |key| number(m.get(key)).map(|v| v as i32);
(get("max_lines"), get("height"))
}),
},
"boolean" => Self::Boolean {
label: label()?,
initial: boolean(t, "initial", false),
on_true: string(t.get("on_true")).unwrap_or_else(|| "true".into()),
on_false: string(t.get("on_false")).unwrap_or_else(|| "false".into()),
},
"single_option" => Self::SingleOption {
width: int(t, "width", 200),
// SingleOptionInput.Entry.CODEC: a full entry or just its id.
options: list(t.get("options"))
.iter()
.filter_map(|o| match o {
Tag::String(id) => Some((id.to_string_lossy(), None, false)),
o => Some((
string(o.get("id"))?,
o.get("display").map(text),
boolean(o, "initial", false),
)),
})
.collect(),
label: label()?,
label_visible: boolean(t, "label_visible", true),
},
"number_range" => {
let float = |key| number(t.get(key)).map(|v| v as f32);
Self::NumberRange {
width: int(t, "width", 200),
label: label()?,
label_format: string(t.get("label_format"))
.unwrap_or_else(|| "options.generic_value".into()),
start: float("start")?,
end: float("end")?,
initial: float("initial"),
step: float("step"),
}
}
_ => return None,
})
}
/// The value it starts with.
pub fn initial(&self) -> InputValue {
match self {
Self::Text { initial, .. } => InputValue::Text(initial.clone()),
Self::Boolean { initial, .. } => InputValue::Bool(*initial),
Self::SingleOption { options, .. } => {
InputValue::Option(options.iter().position(|o| o.2).unwrap_or(0))
}
Self::NumberRange {
start,
end,
initial,
..
} => InputValue::Slider(to_slider(
initial.unwrap_or((start + end) / 2.0),
*start,
*end,
)),
}
}
/// `ValueGetter.asTemplateSubstitution`.
pub fn substitution(&self, value: &InputValue) -> String {
match (self, value) {
(Self::Text { .. }, InputValue::Text(s)) => escape(s),
(
Self::Boolean {
on_true, on_false, ..
},
InputValue::Bool(b),
) => if *b { on_true } else { on_false }.clone(),
(Self::SingleOption { options, .. }, InputValue::Option(i)) => {
options.get(*i).map(|o| o.0.clone()).unwrap_or_default()
}
(Self::NumberRange { .. }, InputValue::Slider(_)) => {
number_string(self.scaled(value).unwrap_or(0.0))
}
_ => String::new(),
}
}
/// `ValueGetter.asTag`.
pub fn tag(&self, value: &InputValue) -> Tag {
match (self, value) {
(Self::Boolean { .. }, InputValue::Bool(b)) => Tag::Byte(i8::from(*b)),
(Self::NumberRange { .. }, _) => {
Tag::Float(self.scaled(value).unwrap_or(0.0).to_bits())
}
(Self::Text { .. }, InputValue::Text(s)) => Tag::String(s.as_str().into()),
_ => Tag::String(self.substitution(value).as_str().into()),
}
}
/// `RangeInfo.computeScaledValue`: a number range's value at its slider position.
pub fn scaled(&self, value: &InputValue) -> Option<f32> {
let (
Self::NumberRange {
start,
end,
initial,
step,
..
},
InputValue::Slider(slider),
) = (self, value)
else {
return None;
};
let (start, end) = (*start, *end);
let in_range = start + slider * (end - start);
let Some(step) = step else {
return Some(in_range);
};
let first = initial.unwrap_or((start + end) / 2.0);
// Math.round: half up.
let steps = ((in_range - first) / step + 0.5).floor() as i32;
let result = first + steps as f32 * step;
let position = to_slider(result, start, end);
if (0.0..=1.0).contains(&position) {
return Some(result);
}
Some(first + (steps - steps.signum()) as f32 * step)
}
}
/// `RangeInfo.scaledValueToSlider`.
fn to_slider(value: f32, start: f32, end: f32) -> f32 {
if start == end {
0.5
} else {
(value - start) / (end - start)
}
}
/// `SliderImpl.valueToString`: whole numbers without a fraction, the rest as
/// Java's `Float.toString`.
pub fn number_string(v: f32) -> String {
if v == (v as i32) as f32 {
(v as i32).to_string()
} else {
crate::snbt::java_float(v)
}
}
impl Body {
/// `DialogBody.DIALOG_BODY_CODEC`.
fn parse(t: &Tag) -> Option<Self> {
let message = |t: &Tag| -> Option<(Text, i32)> {
// PlainMessage.CODEC: the full form or just its contents.
match t {
Tag::Compound(_) if t.get("contents").is_some() => {
Some((text(t.get("contents")?), int(t, "width", 200)))
}
t => Some((text(t), 200)),
}
};
Some(match path(&string(t.get("type"))?) {
"plain_message" => {
let (contents, width) = message(t)?;
Self::Message { contents, width }
}
"item" => Self::Item {
item: t.get("item")?.clone(),
description: t.get("description").and_then(message),
show_decorations: boolean(t, "show_decorations", true),
show_tooltip: boolean(t, "show_tooltip", true),
width: int(t, "width", 16),
height: int(t, "height", 16),
},
_ => return None,
})
}
}
impl Dialog {
/// `Dialog.DIRECT_CODEC`; `None` for a type or field it can't read
/// (vanilla fails the whole packet then).
pub fn parse(t: &Tag) -> Option<Self> {
let button = |key: &str| t.get(key).and_then(Button::parse);
let kind = match path(&string(t.get("type"))?) {
"notice" => Kind::Notice(match t.get("action") {
Some(b) => Button::parse(b)?,
None => Button::ok(),
}),
"confirmation" => Kind::Confirmation {
yes: button("yes")?,
no: button("no")?,
},
"multi_action" => Kind::MultiAction {
actions: list(t.get("actions"))
.iter()
.map(Button::parse)
.collect::<Option<Vec<_>>>()
.filter(|a| !a.is_empty())?,
exit: button("exit_action"),
columns: int(t, "columns", 2),
},
"server_links" => Kind::ServerLinks {
exit: button("exit_action"),
columns: int(t, "columns", 2),
button_width: int(t, "button_width", 150),
},
"dialog_list" => Kind::DialogList {
dialogs: t.get("dialogs")?.clone(),
exit: button("exit_action"),
columns: int(t, "columns", 2),
button_width: int(t, "button_width", 150),
},
_ => return None,
};
// DialogBody.COMPACT_LIST_CODEC: one body, or a list of them.
let body = match t.get("body") {
Some(Tag::List(items)) => items.iter().filter_map(Body::parse).collect(),
Some(one) => Body::parse(one).into_iter().collect(),
None => Vec::new(),
};
let inputs = list(t.get("inputs"))
.iter()
.filter_map(|i| {
Some(Input {
key: string(i.get("key"))?,
control: Control::parse(i)?,
})
})
.collect();
Some(Self {
kind,
title: text(t.get("title")?),
external_title: t.get("external_title").map(text),
can_close_with_escape: boolean(t, "can_close_with_escape", true),
pause: boolean(t, "pause", true),
after_action: match string(t.get("after_action")).as_deref() {
Some("none") => AfterAction::None,
Some("wait_for_response") => AfterAction::WaitForResponse,
_ => AfterAction::Close,
},
body,
inputs,
})
}
/// `onCancel`: what Escape (or closing it) does.
pub fn on_cancel(&self) -> Option<&Action> {
match &self.kind {
Kind::Notice(b) => b.action.as_ref(),
Kind::Confirmation { no, .. } => no.action.as_ref(),
Kind::MultiAction { exit, .. }
| Kind::ServerLinks { exit, .. }
| Kind::DialogList { exit, .. } => exit.as_ref().and_then(|b| b.action.as_ref()),
}
}
/// The buttons it draws, in order: the list, then the footer's.
pub fn buttons(&self) -> Vec<&Button> {
match &self.kind {
Kind::Notice(b) => vec![b],
Kind::Confirmation { yes, no } => vec![yes, no],
Kind::MultiAction { actions, exit, .. } => actions.iter().chain(exit).collect(),
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => exit.iter().collect(),
}
}
/// What `status` reports of it.
pub fn json(&self, values: &[InputValue]) -> Value {
let kind = match &self.kind {
Kind::Notice(_) => "notice",
Kind::Confirmation { .. } => "confirmation",
Kind::MultiAction { .. } => "multi_action",
Kind::ServerLinks { .. } => "server_links",
Kind::DialogList { .. } => "dialog_list",
};
let inputs: Vec<Value> = self
.inputs
.iter()
.zip(values)
.map(|(i, v)| {
let kind = match i.control {
Control::Text { .. } => "text",
Control::Boolean { .. } => "boolean",
Control::SingleOption { .. } => "single_option",
Control::NumberRange { .. } => "number_range",
};
json!({"key": i.key, "type": kind, "value": i.control.substitution(v)})
})
.collect();
json!({
"type": kind,
"title": self.title.plain(),
"body": self.body.iter().map(|b| match b {
Body::Message { contents, .. } => contents.plain(),
Body::Item { item, .. } => string(item.get("id")).unwrap_or_default(),
}).collect::<Vec<_>>(),
"inputs": inputs,
"buttons": self.buttons().iter().map(|b| b.label.plain()).collect::<Vec<_>>(),
"can_close_with_escape": self.can_close_with_escape,
"after_action": match self.after_action {
AfterAction::Close => "close",
AfterAction::None => "none",
AfterAction::WaitForResponse => "wait_for_response",
},
})
}
}
#[cfg(test)]
mod tests {
use super::*;
fn s(v: &str) -> Tag {
Tag::String(v.into())
}
/// The register dialog AuthMe 6 sends in configuration (the shape its
/// `show_dialog` packet has on the test bed).
fn register() -> Tag {
Tag::compound([
("type", s("minecraft:multi_action")),
("title", s("Register")),
("can_close_with_escape", Tag::Byte(0)),
("after_action", s("wait_for_response")),
(
"body",
Tag::compound([
("type", s("minecraft:plain_message")),
("contents", s("Choose a password")),
]),
),
(
"inputs",
Tag::List(vec![Tag::compound([
("type", s("minecraft:text")),
("key", s("password")),
("label", s("Password")),
])]),
),
(
"actions",
Tag::List(vec![
Tag::compound([
("label", s("Register")),
(
"action",
Tag::compound([
("type", s("minecraft:dynamic/custom")),
("id", s("authme:prejoin-register/submit")),
]),
),
]),
Tag::compound([
("label", s("Cancel")),
(
"action",
Tag::compound([
("type", s("minecraft:dynamic/run_command")),
("template", s("say $(password) $(missing)!")),
]),
),
]),
]),
),
])
}
#[test]
fn decodes_a_multi_action_dialog_with_defaults() {
let d = Dialog::parse(&register()).unwrap();
assert_eq!(d.title.plain(), "Register");
assert!(!d.can_close_with_escape);
assert!(d.pause);
assert_eq!(d.after_action, AfterAction::WaitForResponse);
assert!(matches!(&d.body[..], [Body::Message { width: 200, .. }]));
let Kind::MultiAction {
actions,
exit,
columns,
} = &d.kind
else {
panic!("{:?}", d.kind)
};
assert_eq!((actions.len(), exit.is_none(), *columns), (2, true, 2));
assert_eq!(actions[0].width, 150);
assert!(d.on_cancel().is_none());
let [
Input {
key,
control:
Control::Text {
max_length: 32,
width: 200,
..
},
},
] = &d.inputs[..]
else {
panic!("{:?}", d.inputs)
};
assert_eq!(key, "password");
}
#[test]
fn actions_carry_the_input_values() {
let d = Dialog::parse(&register()).unwrap();
let values = [InputValue::Text("p\"w".into())];
let Kind::MultiAction { actions, .. } = &d.kind else {
unreachable!()
};
let custom = actions[0]
.action
.as_ref()
.unwrap()
.click(&d.inputs, &values);
assert_eq!(
custom,
Some(Click::Custom {
id: "authme:prejoin-register/submit".into(),
payload: Some(Tag::compound([("password", s("p\"w"))])),
})
);
// The template escapes the text; a key no input has becomes nothing.
let command = actions[1]
.action
.as_ref()
.unwrap()
.click(&d.inputs, &values);
assert_eq!(command, Some(Click::RunCommand("say p\\\"w !".into())));
}
#[test]
fn a_notice_without_an_action_has_ok() {
let d = Dialog::parse(&Tag::compound([("type", s("notice")), ("title", s("Hi"))])).unwrap();
let Kind::Notice(b) = &d.kind else {
unreachable!()
};
assert_eq!(b.label, Text::translate("gui.ok", &[]));
// Without a title, or with an unknown type, there is no dialog.
assert!(Dialog::parse(&Tag::compound([("type", s("notice"))])).is_none());
assert!(Dialog::parse(&Tag::compound([("type", s("x")), ("title", s("Hi"))])).is_none());
}
#[test]
fn number_ranges_snap_to_their_step() {
let mut range = Control::NumberRange {
width: 200,
label: Text::literal("n"),
label_format: "options.generic_value".into(),
start: 0.0,
end: 10.0,
initial: Some(4.0),
step: Some(3.0),
};
assert_eq!(range.initial(), InputValue::Slider(0.4));
assert_eq!(range.scaled(&InputValue::Slider(0.62)), Some(7.0));
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(10.0));
let Control::NumberRange { step, .. } = &mut range else {
unreachable!()
};
*step = Some(4.0);
// 12 is out of range: one step less.
assert_eq!(range.scaled(&InputValue::Slider(1.0)), Some(8.0));
assert_eq!(range.substitution(&InputValue::Slider(0.0)), "0");
assert_eq!(number_string(2.5), "2.5");
}
}
+382
View File
@@ -0,0 +1,382 @@
//! `DialogScreen` and its kinds (`SimpleDialogScreen`, `MultiButtonDialogScreen`):
//! where a server dialog's title, body, inputs and buttons go in a
//! `HeaderAndFooterLayout` (a 33 high header, the body in a `ScrollableLayout`,
//! the footer), and the `WaitingForResponseScreen` an answer can leave open.
use crate::{
dialog::{Body, Control, Dialog, Kind},
font::Font,
text::Text,
};
/// `HeaderAndFooterLayout.DEFAULT_HEADER_AND_FOOTER_HEIGHT`.
const BAR: f32 = 33.0;
/// `Checkbox.getBoxSize`.
pub const BOX: f32 = 17.0;
/// `DialogScreen.WARNING_BUTTON_SPRITES`: normal, disabled, highlighted.
pub const WARNING_SPRITES: [&str; 3] = [
"gui/sprites/dialog/warning_button",
"gui/sprites/dialog/warning_button_disabled",
"gui/sprites/dialog/warning_button_highlighted",
];
/// One drawn piece; `y` is from the top of the body (before it scrolls) for
/// the body's parts, from the top of the screen for the footer's.
#[derive(Clone, Debug, PartialEq)]
pub enum Part {
/// A line of text and where it starts.
Line(Text, f32, f32),
/// A text input's box.
Field { input: usize, rect: [f32; 4] },
/// A boolean input: the box, its label right of it.
Check { input: usize, rect: [f32; 4] },
/// A button of `Dialog::buttons`.
Button { index: usize, rect: [f32; 4] },
}
#[derive(Clone, Debug)]
pub struct Layout {
/// The title and where it is drawn.
pub title: (f32, f32),
pub warning: [f32; 4],
/// The body's visible area (`ScrollableLayout`'s container): x, y, w, h.
pub area: [f32; 4],
/// The body's full height: more than the area's scrolls.
pub content: f32,
pub body: Vec<Part>,
pub footer: Vec<Part>,
}
/// A laid-out element of a `LinearLayout` before it is placed.
struct Element {
w: f32,
h: f32,
parts: Vec<Part>,
}
impl Element {
/// Its parts moved to `(x, y)`.
fn at(self, x: f32, y: f32) -> impl Iterator<Item = Part> {
self.parts.into_iter().map(move |p| match p {
Part::Line(t, px, py) => Part::Line(t, px + x, py + y),
Part::Field { input, rect } => Part::Field {
input,
rect: shift(rect, x, y),
},
Part::Check { input, rect } => Part::Check {
input,
rect: shift(rect, x, y),
},
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, x, y),
},
})
}
}
fn shift([x, y, w, h]: [f32; 4], dx: f32, dy: f32) -> [f32; 4] {
[x + dx, y + dy, w, h]
}
/// `FrameLayout.alignInDimension` at 0.5: the offset that centres `inner`.
fn centre(outer: f32, inner: f32) -> f32 {
((outer - inner) * 0.5).trunc()
}
/// `FocusableTextWidget` with the body's settings: `width` wide, the text
/// wrapped to `width - 8` and centred, 4 of padding all round.
fn message(font: &Font, contents: &Text, width: f32) -> Element {
let lines = font.split_lines(contents, width - 8.0);
let mid = (width / 2.0).trunc();
let parts = lines
.into_iter()
.enumerate()
.map(|(i, (line, _))| {
let x = mid - (font.width_text(&line) / 2.0).trunc();
Part::Line(line, x, 4.0 + 9.0 * i as f32)
})
.collect::<Vec<_>>();
Element {
w: width,
h: 9.0 * parts.len() as f32 + 8.0,
parts,
}
}
/// `InputControlHandlers`: the control for input `i`, if Horizon has it.
fn input(font: &Font, i: usize, control: &Control) -> Option<Element> {
Some(match control {
Control::Text {
width,
label,
label_visible,
..
} => {
let w = *width as f32;
if !label_visible {
return Some(Element {
w,
h: 20.0,
parts: vec![Part::Field {
input: i,
rect: [0.0, 0.0, w, 20.0],
}],
});
}
// CommonLayouts.labeledElement: the label, 4 below it the box,
// both on the left.
Element {
w: w.max(font.width_text(label)),
h: 9.0 + 4.0 + 20.0,
parts: vec![
Part::Line(label.clone(), 0.0, 0.0),
Part::Field {
input: i,
rect: [0.0, 13.0, w, 20.0],
},
],
}
}
Control::Boolean { label, .. } => {
let w = BOX + 4.0 + font.width_text(label);
Element {
w,
h: BOX,
parts: vec![Part::Check {
input: i,
rect: [0.0, 0.0, w, BOX],
}],
}
}
Control::SingleOption { .. } | Control::NumberRange { .. } => return None,
})
}
/// `DialogScreen.packControlsIntoColumns`: full rows in a grid 2 apart, what
/// is left in a centred row under them.
fn columns(widths: &[f32], columns: usize, first: usize) -> Element {
let columns = columns.max(1);
let full = widths.len() / columns * columns;
let row_width = |ws: &[f32]| ws.iter().sum::<f32>() + 2.0 * (ws.len().max(1) - 1) as f32;
let mut col = vec![0.0f32; columns];
for (i, w) in widths[..full].iter().enumerate() {
col[i % columns] = col[i % columns].max(*w);
}
let last = &widths[full..];
if !last.is_empty() {
// GridLayout spreads a cell over every column it spans (Divisor).
let spread = row_width(last) - 2.0 * (columns - 1) as f32;
let (each, extra) = ((spread / columns as f32).floor(), spread % columns as f32);
for (c, w) in col.iter_mut().enumerate() {
*w = w.max(each + f32::from(u8::from((c as f32) < extra)));
}
}
let x_of = |c: usize| col[..c].iter().sum::<f32>() + 2.0 * c as f32;
let mut parts = Vec::new();
for (i, w) in widths[..full].iter().enumerate() {
let (r, c) = (i / columns, i % columns);
parts.push(Part::Button {
index: first + i,
rect: [x_of(c) + centre(col[c], *w), 22.0 * r as f32, *w, 20.0],
});
}
let width = x_of(columns - 1) + col[columns - 1];
if !last.is_empty() {
let y = 22.0 * (full / columns) as f32;
let mut x = centre(width, row_width(last));
for (i, w) in last.iter().enumerate() {
parts.push(Part::Button {
index: first + full + i,
rect: [x, y, *w, 20.0],
});
x += w + 2.0;
}
}
let rows = full / columns + usize::from(!last.is_empty());
Element {
w: width,
h: (22.0 * rows as f32 - 2.0).max(0.0),
parts,
}
}
impl Layout {
/// `DialogScreen.init` and `repositionElements` on a `w` by `h` screen.
pub fn new(dialog: &Dialog, font: &Font, (w, h): (f32, f32)) -> Self {
// The header: the title, 10 right of it the warning button, both
// centred together.
let tw = font.width_text(&dialog.title);
let (hx, hy) = (centre(w, tw + 30.0), centre(BAR, 20.0));
let title = (hx, hy + centre(20.0, 9.0));
let warning = [hx + tw + 10.0, hy, 20.0, 20.0];
let mut elements: Vec<Element> = dialog
.body
.iter()
.filter_map(|b| match b {
Body::Message { contents, width } => Some(message(font, contents, *width as f32)),
Body::Item { .. } => None,
})
.collect();
elements.extend(
dialog
.inputs
.iter()
.enumerate()
.filter_map(|(i, input_)| input(font, i, &input_.control)),
);
let buttons = dialog.buttons();
let (listed, footer_buttons, footer_h) = match &dialog.kind {
Kind::MultiAction {
actions,
exit,
columns: n,
} => {
let widths: Vec<f32> = actions.iter().map(|b| b.width as f32).collect();
elements.push(columns(&widths, *n as usize, 0));
// ButtonListDialogScreen: the exit button in the footer, else a 5 high one.
let footer = exit.as_ref().map(|_| actions.len()).into_iter().collect();
(
actions.len(),
footer,
if exit.is_some() { BAR } else { 5.0 },
)
}
Kind::ServerLinks { exit, .. } | Kind::DialogList { exit, .. } => {
let footer = exit.as_ref().map(|_| 0).into_iter().collect();
(0, footer, if exit.is_some() { BAR } else { 5.0 })
}
// SimpleDialogScreen: the buttons side by side, 8 apart.
Kind::Notice(_) | Kind::Confirmation { .. } => {
(0, (0..buttons.len()).collect::<Vec<_>>(), BAR)
}
};
debug_assert!(listed + footer_buttons.len() <= buttons.len());
// The body: a column 10 apart, each element centred in it.
let body_w = elements.iter().map(|e| e.w).fold(0.0, f32::max);
let content = elements.iter().map(|e| e.h).sum::<f32>()
+ 10.0 * elements.len().saturating_sub(1) as f32;
// ScrollableLayout: 10 each side for the scrollbar (ReserveStrategy.BOTH),
// no higher than what the header and footer leave.
let area_w = body_w + 20.0;
let area_h = content.min(h - BAR - footer_h).max(0.0);
let area_y = (BAR + 30.0).min(h - footer_h - area_h);
let area_x = centre(w, area_w);
let mut body = Vec::new();
let mut y = 0.0;
for e in elements {
let (x, eh) = (area_x + 10.0 + centre(body_w, e.w), e.h);
body.extend(e.at(x, y));
y += eh + 10.0;
}
let widths: Vec<f32> = footer_buttons
.iter()
.map(|&i| buttons[i].width as f32)
.collect();
let row = widths.iter().sum::<f32>() + 8.0 * widths.len().saturating_sub(1) as f32;
let (mut x, fy) = (centre(w, row), h - footer_h + centre(footer_h, 20.0));
let mut footer = Vec::new();
for (&i, bw) in footer_buttons.iter().zip(&widths) {
footer.push(Part::Button {
index: i,
rect: [x, fy, *bw, 20.0],
});
x += bw + 8.0;
}
Self {
title,
warning: Self::in_bounds(warning, w, h),
area: [area_x, area_y, area_w, area_h],
content,
body,
footer,
}
}
/// `makeSureWarningButtonIsInBounds`.
fn in_bounds(r: [f32; 4], w: f32, h: f32) -> [f32; 4] {
if r[0] < 0.0 || r[1] < 0.0 || r[0] > w - 20.0 || r[1] > h - 20.0 {
[(w - 40.0).max(0.0), 5.0f32.min(h), 20.0, 20.0]
} else {
r
}
}
/// Every part where it is drawn with the body scrolled by `scroll`, and
/// whether it is in the body (clipped to its area).
pub fn placed(&self, scroll: f32) -> impl Iterator<Item = (Part, bool)> + '_ {
let dy = self.area[1] - scroll;
let body = self.body.iter().map(move |p| {
let p = match p.clone() {
Part::Line(t, x, y) => Part::Line(t, x, y + dy),
Part::Field { input, rect } => Part::Field {
input,
rect: shift(rect, 0.0, dy),
},
Part::Check { input, rect } => Part::Check {
input,
rect: shift(rect, 0.0, dy),
},
Part::Button { index, rect } => Part::Button {
index,
rect: shift(rect, 0.0, dy),
},
};
(p, true)
});
body.chain(self.footer.iter().map(|p| (p.clone(), false)))
}
}
/// `WaitingForResponseScreen`: its Back button's label after `ticks`, and
/// whether it shows and works (it shows after a second, works after five).
pub fn waiting_button(ticks: u32) -> (Text, bool, bool) {
let seconds = (ticks / 20).min(5);
let label = match seconds {
0 => Text::literal(""),
5 => Text::translate("gui.back", &[]),
s => Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal((5 - s).to_string())],
),
};
(label, seconds >= 1, seconds == 5)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grids_pack_full_rows_and_centre_the_rest() {
// AuthMe's two buttons: one row, 2 apart.
let two = columns(&[150.0, 150.0], 2, 0);
assert_eq!((two.w, two.h), (302.0, 20.0));
// Three in two columns: the third alone, centred under them.
let three = columns(&[150.0, 150.0, 150.0], 2, 0);
assert_eq!((three.w, three.h), (302.0, 42.0));
assert_eq!(
three.parts[2],
Part::Button {
index: 2,
rect: [76.0, 22.0, 150.0, 20.0]
}
);
// One in two columns spreads over both.
let one = columns(&[100.0], 2, 0);
assert_eq!(one.w, 100.0);
}
#[test]
fn the_waiting_screens_button_counts_down() {
assert!(!waiting_button(0).1);
assert_eq!(
waiting_button(20).0,
Text::translate(
"gui.waitingForResponse.button.inactive",
&[Text::literal("4")]
)
);
assert_eq!(
waiting_button(100),
(Text::translate("gui.back", &[]), true, true)
);
}
}
+50 -5
View File
@@ -33,7 +33,11 @@ impl Cost {
#[derive(Clone, Debug)]
pub struct Enchantment {
pub id: Arc<str>,
/// The name the pinned English map gave at load: the fallback for a
/// language that has no entry for the key below.
pub description: String,
/// `description`'s translation key (`enchantment.minecraft.<name>`).
pub description_key: String,
pub max_level: u32,
pub weight: u32,
pub anvil_cost: u32,
@@ -224,6 +228,7 @@ impl Enchantments {
.get(key)
.cloned()
.unwrap_or_else(|| id.trim_start_matches("minecraft:").replace('_', " ")),
description_key: key.to_owned(),
max_level: v["max_level"].as_u64().unwrap_or(1) as u32,
weight: v["weight"].as_u64().unwrap_or(1) as u32,
anvil_cost: v["anvil_cost"].as_u64().unwrap_or(0) as u32,
@@ -329,16 +334,26 @@ impl Enchantments {
}
/// `Enchantment.getFullname` as plain text and whether it is a curse (red).
pub fn full_name(&self, id: &str, level: u32) -> (String, bool) {
let language = crate::lang::current();
self.full_name_in(language.as_deref(), id, level)
}
/// `full_name` against `language`; `None` (no language loaded: a
/// dedicated server, the probes) keeps the English names loaded above.
pub fn full_name_in(
&self,
language: Option<&crate::lang::Language>,
id: &str,
level: u32,
) -> (String, bool) {
let tr = |key: &str| language.and_then(|l| l.get(key).map(str::to_owned));
let Some(e) = self.get(id) else {
return (format!("{id} {}", level_name(level)), false);
};
let mut name = e.description.clone();
let mut name = tr(&e.description_key).unwrap_or_else(|| e.description.clone());
if level != 1 || e.max_level != 1 {
name.push(' ');
name.push_str(
self.lang
.get(&format!("enchantment.level.{level}"))
.map_or(&level_name(level), |s| s),
&tr(&format!("enchantment.level.{level}")).unwrap_or_else(|| level_name(level)),
);
}
(name, self.is_curse(id))
@@ -771,7 +786,7 @@ pub(crate) mod tests {
let defs = [
(
"minecraft:sharpness",
json!({"anvil_cost":1,"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
json!({"anvil_cost":1,"description":{"translate":"enchantment.minecraft.sharpness"},"exclusive_set":"#minecraft:exclusive_set/damage","max_cost":{"base":21,"per_level_above_first":11},"max_level":5,"min_cost":{"base":1,"per_level_above_first":11},"primary_items":"#minecraft:enchantable/melee_weapon","supported_items":"#minecraft:enchantable/sharp_weapon","weight":10,"slots":["mainhand"],"effects":{"minecraft:damage":[{"effect":{"type":"minecraft:add","value":{"type":"minecraft:linear","base":1.0,"per_level_above_first":0.5}}}]}}),
),
(
"minecraft:smite",
@@ -795,6 +810,7 @@ pub(crate) mod tests {
.map(|(id, v)| Enchantment {
id: Arc::from(*id),
description: id.trim_start_matches("minecraft:").into(),
description_key: v["description"]["translate"].as_str().unwrap_or("").into(),
max_level: v["max_level"].as_u64().unwrap() as u32,
weight: v["weight"].as_u64().unwrap() as u32,
anvil_cost: v["anvil_cost"].as_u64().unwrap() as u32,
@@ -1088,4 +1104,33 @@ pub(crate) mod tests {
assert!(!e.compatible("minecraft:sharpness", "minecraft:smite"));
assert!(e.compatible("minecraft:sharpness", "minecraft:unbreaking"));
}
/// The enchantment's name and its level come from the selected language,
/// with the English name loaded above as the fallback.
#[test]
fn names_follow_the_language() {
struct Mem(HashMap<String, Vec<u8>>);
impl crate::lang::ResourceSource for Mem {
fn read(&self, path: &str) -> Option<Vec<u8>> {
self.0.get(path).cloned()
}
}
let ru = Mem(HashMap::from([(
"assets/minecraft/lang/ru_ru.json".to_owned(),
r#"{"enchantment.minecraft.sharpness":"Острота","enchantment.level.5":"V"}"#
.as_bytes()
.to_vec(),
)]));
let ru = crate::lang::Language::load(&[&ru], "ru_ru");
let e = sample();
assert_eq!(
e.full_name_in(Some(&ru), "minecraft:sharpness", 5).0,
"Острота V"
);
// mending carries no key in the fixture: the English name stays.
assert_eq!(
e.full_name_in(Some(&ru), "minecraft:mending", 1).0,
"mending"
);
}
}
+15 -5
View File
@@ -25,6 +25,20 @@ impl Culler {
vertices: &mut Vec<crate::mesher::Vertex>,
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
let hidden = self.hidden(vertices, start, opaque);
if hidden {
vertices.truncate(start);
}
hidden
}
/// Whether this entity's completed camera-relative mesh (`vertices[start..]`) is hidden.
pub fn hidden(
&self,
vertices: &[crate::mesher::Vertex],
start: usize,
opaque: impl FnMut([i32; 3]) -> bool,
) -> bool {
if start >= vertices.len() || self.remaining.get() == 0 {
return false;
@@ -42,11 +56,7 @@ impl Culler {
}
}
// Cover floating-point and rasterization edges as well as the vertices.
if self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque) {
vertices.truncate(start);
return true;
}
false
self.occluded(min.map(|v| v - 0.05), max.map(|v| v + 0.05), opaque)
}
/// Returns true only when a complete opaque block plane covers the bounds.
+18 -8
View File
@@ -617,9 +617,23 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.head_pitch = pitch;
m.on_ground = flag(tag, "OnGround");
m.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0);
if let Some(h) = float(tag.get("Health")) {
m.health = h as f32;
// LivingEntity.readAdditionalSaveData: the saved attribute bases, then
// the health, the max health when there is none.
if let Some(Tag::List(attrs)) = tag.get("attributes") {
for a in attrs {
let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else {
continue;
};
let v = f64::from_bits(*bits);
match id.as_str() {
"minecraft:max_health" => m.attrs.max_health = v as f32,
"minecraft:movement_speed" => m.attrs.speed = v,
"minecraft:attack_damage" => m.attrs.attack_damage = v as f32,
_ => {}
}
}
}
m.health = float(tag.get("Health")).map_or(m.attrs.max_health, |h| h as f32);
m.hurt_time = number(tag.get("HurtTime")).unwrap_or(0) as i32;
// What it holds (equipment.mainhand / offhand), when saved.
if let Some(eq) = tag.get("equipment") {
@@ -735,12 +749,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
let (Some(id), Some(Tag::Double(bits))) = (text(a.get("id")), a.get("base")) else {
continue;
};
let v = f64::from_bits(*bits);
match id.as_str() {
"minecraft:max_health" => m.attrs.max_health = v as f32,
"minecraft:movement_speed" => m.attrs.speed = v,
"minecraft:jump_strength" => m.extra.vector[0] = v,
_ => {}
if id == "minecraft:jump_strength" {
m.extra.vector[0] = f64::from_bits(*bits);
}
}
}
+4 -1
View File
@@ -891,8 +891,11 @@ impl Font {
}
s.chars().map(|c| self.glyph(c).advance).sum::<f32>().ceil()
}
/// Font.width of a component: `§` codes in the spans are formatting,
/// not glyphs.
pub fn width_text(&self, t: &Text) -> f32 {
t.chars()
t.resolved()
.chars()
.map(|(c, s)| self.advance(c, s))
.sum::<f32>()
.ceil()
File diff suppressed because it is too large Load Diff
+23 -2
View File
@@ -392,6 +392,9 @@ impl Game<'_> {
Ok(())
}
pub(super) fn screen_label(&self) -> &'static str {
if self.dialog_open() {
return "dialog";
}
if self.title.is_some() {
return "title";
}
@@ -418,6 +421,7 @@ impl Game<'_> {
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
Screen::Mod => "mod",
}
}
pub(super) fn inventory_counts(&self) -> BTreeMap<String, i64> {
@@ -486,6 +490,7 @@ impl Game<'_> {
})
});
json!({
"dialog": self.dialog_status(),
"screen": self.screen_label(),
"menu": self.title.as_ref().map(|_| self.title_value()),
"world": (self.title.is_none()).then(|| match &self.integrated {
@@ -684,6 +689,18 @@ impl Game<'_> {
v["craft_size"] = json!(self.craft_size);
v["station"] = json!(self.station.as_ref().map(|s| format!("{:?}", s.kind)));
v["container"] = json!(self.container);
// The title a server gave the menu, span by span as it is drawn.
if let Some(title) = self.remote_menu_title() {
let spans = title.spans.iter().map(|s| {
json!({
"text": s.text,
"color": s.style.color.map(|c| format!("#{c:06X}")),
"bold": s.style.is_bold(),
"italic": s.style.is_italic(),
})
});
v["title"] = json!(spans.collect::<Vec<_>>());
}
// The recipe book's buttons (GUI pixels): the book button, then
// the recipe buttons of the page, page arrows, filter and tabs.
let book = self.recipe_book_targets();
@@ -1602,8 +1619,12 @@ impl Game<'_> {
if self.screen != Screen::Dead {
return Err("respawn needs the death screen".into());
}
let label =
horizon_client::text::Text::translate("deathScreen.respawn", &[]).plain();
let key = if self.level.hardcore {
"deathScreen.spectate"
} else {
"deathScreen.respawn"
};
let label = horizon_client::text::Text::translate(key, &[]).plain();
let w = widgets::find(&widgets::last(), &label)?;
if !w.enabled {
// DeathScreen enables its buttons after 20 ticks.
+6 -1
View File
@@ -519,7 +519,12 @@ impl Game<'_> {
self.draw_tooltip_lines(batch, &lines, self.cursor.0, self.cursor.1);
} else if let Some(key) = tooltip {
let text = self.translate(&key, &key);
self.draw_tooltip_lines(batch, &[(text, u32::MAX)], self.cursor.0, self.cursor.1);
self.draw_tooltip_lines(
batch,
&[(horizon_client::text::Text::literal(text), u32::MAX)],
self.cursor.0,
self.cursor.1,
);
}
}
/// `BeaconRenderer`: each section's rotating solid beam and its glow.
@@ -8,8 +8,10 @@ use horizon_client::{
block_entity_anim::{BellEntity, EndGateway, Shulker, ShulkerStatus, Ticker},
block_entity_render::BlockAnim,
collisions::{SceneCollisions, no_collision_empty},
containers::BlockEntity,
particles::{ParticleOptions, ParticleType},
save::number,
skins,
};
use horizon_core::geometry::{Aabb, Vec3};
use horizon_world::nbt::Tag;
@@ -392,4 +394,25 @@ impl Game<'_> {
pub(super) fn chest_lid(&self, pos: [i32; 3], partial: f32) -> f32 {
self.be_anims.lid(pos, partial)
}
/// `SkullBlockRenderer.getPlayerSkin`: the skin sprite of the profile of
/// the player head at `pos`. The skin download is started here; while it
/// is in flight (or when it cannot be got) the profile's default skin
/// stands in. A head with no profile answers None: `SKIN_BY_TYPE`.
pub(super) fn skull_skin_at(&self, pos: [i32; 3]) -> Option<&str> {
let Some(BlockEntity::Skull(skull)) =
self.world.block_entities.get(&(pos[0], pos[1], pos[2]))
else {
return None;
};
let skin = skull.skin.as_ref()?;
if let Some((url, location)) = &skin.download {
self.skin_downloads
.borrow_mut()
.state(skins::Kind::Skin, url);
if self.gui.atlas.sprites.contains_key(location) {
return Some(location);
}
}
Some(skin.fallback)
}
}
@@ -13,7 +13,7 @@ use horizon_client::{
use horizon_core::geometry::{Aabb, Vec3};
/// `Entity.boardingCooldown` once a mob leaves its boat.
const BOARDING_COOLDOWN: i32 = 60;
pub(super) const BOARDING_COOLDOWN: i32 = 60;
/// `Player.DEFAULT_VEHICLE_ATTACHMENT`: how far below the seat a player's
/// feet are.
const PLAYER_RIDING_OFFSET: f64 = 0.6;
+40 -10
View File
@@ -2,7 +2,10 @@
//! (game rules, the world clock, difficulty), bound to the game.
use super::{Game, Screen};
use horizon_client::{
chat::{Chat, ChatAction, ChatScreen, Commands, SYSTEM_INDICATOR},
chat::{
Chat, ChatAbilities, ChatAction, ChatScreen, ChatSource, ChatVisibility, Commands,
SYSTEM_INDICATOR,
},
command::Registries,
gamerules::GameRules,
hud::HudBatch,
@@ -18,7 +21,7 @@ fn chat_tree<'a>(
mods: &'a super::mods::ModsState,
) -> &'a horizon_client::command::Dispatcher {
match remote.as_ref().and_then(|r| r.commands.as_ref()) {
Some(tree) => tree,
Some(tree) => mods.remote_dispatcher().unwrap_or(tree),
None => mods.dispatcher(),
}
}
@@ -99,6 +102,8 @@ pub struct UiState {
/// Death screen cause and when the player died (buttons wait 20 ticks).
pub death_text: Option<Text>,
pub died_at: Option<std::time::Instant>,
/// `LivingEntity.deathTime` of the window's player: ticks since it died.
pub death_time: u32,
}
impl Game<'_> {
@@ -423,6 +428,7 @@ impl Game<'_> {
self.ui.chat.recent.len(),
b.width as i32,
b.height as i32,
self.chat_abilities(),
);
screen.auto_suggestions = self.settings.auto_suggestions;
self.ui.chat_screen = Some(screen);
@@ -441,6 +447,10 @@ impl Game<'_> {
self.capture(true);
}
}
/// `Minecraft.computeChatAbilities` from the Chat option.
pub(super) fn chat_abilities(&self) -> ChatAbilities {
ChatAbilities::new(ChatVisibility::from_option(self.settings.chat_visibility))
}
/// A chat message from the game (ChatComponent.addServerSystemMessage).
pub(super) fn system_message(&mut self, text: Text) {
if let Some(capture) = self.chat_capture.as_mut() {
@@ -450,7 +460,11 @@ impl Game<'_> {
// Connected to a server (single player's own included), the chat on
// screen is the connection's: the game's own messages join it.
if self.remote.is_some() {
self.chat_line(text);
self.chat_line(text, ChatSource::Server);
return;
}
// The Chat option's Hidden level takes the server's messages too.
if !self.ui.chat.shows(ChatSource::Server) {
return;
}
let focused = self.screen == Screen::Chat;
@@ -459,6 +473,7 @@ impl Game<'_> {
&self.gui.atlas,
text,
Some(SYSTEM_INDICATOR),
ChatSource::Server,
self.ticks,
focused,
);
@@ -568,7 +583,12 @@ impl Game<'_> {
}
}
/// ChatScreen.handleChatInput: history, then a command or a chat line.
/// The Chat option's restrictions stop the message here too, so a
/// control-socket `chat` cannot send what the player's setting hides.
pub(super) fn handle_chat_input(&mut self, message: &str) {
if !self.chat_abilities().allows(message) {
return;
}
self.ui.chat.add_recent(message);
// On a server (single player's own included) the server runs it,
// unless a client mod owns the command.
@@ -586,13 +606,18 @@ impl Game<'_> {
} else {
let line = Text::translate(
"chat.type.text",
&[Text::literal(PLAYER_NAME), Text::literal(message)],
&[self.player_display_name(), Text::literal(message)],
);
let focused = self.screen == Screen::Chat;
let heard = self.mods.running().then(|| line.plain());
self.ui
.chat
.add(&self.gui.atlas, line, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
line,
None,
ChatSource::Player,
self.ticks,
focused,
);
if let Some(line) = heard {
self.mods_chat(&line);
}
@@ -896,9 +921,14 @@ impl Game<'_> {
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
};
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.gui.atlas, message, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
message,
None,
ChatSource::Client,
self.ticks,
focused,
);
}
}
/// `yyyy-MM-dd_HH.mm.ss[_n].png` (Util.getFilenameFormattedDateTime, local time
@@ -0,0 +1,37 @@
//! The window's own ambient effects of entities, which a client makes for
//! itself (`level().isClientSide()` branches): endermen's and endermites'
//! portal particles, blazes' smoke and burn, eyes of ender's trail. They run
//! on the game that has the window, in-frame or following a server, never on
//! a server: nothing of them goes over the network.
use super::Game;
use horizon_client::mobs::{MobEvent, ambient};
use horizon_client::particles::{ParticleOptions, ParticleType};
impl Game<'_> {
pub(super) fn tick_client_ambient(&mut self) {
if self.serving.is_some() || self.options.dedicated.is_some() {
return;
}
let mut events = Vec::new();
for m in self.mobs.iter_mut().filter(|m| !m.removed) {
ambient::client_ai_step(m, &mut events);
}
for event in events {
match event {
MobEvent::ParticleAt { kind, at, velocity } => {
if let Some(ty) = ParticleType::from_name(kind) {
self.particles
.add(&ParticleOptions::simple(ty), at, velocity);
}
}
// Each guest of a LAN host makes its own.
MobEvent::LocalSound(name, at, volume, pitch) => {
self.audio
.play_unshared(&format!("minecraft:{name}"), Some(at), volume, pitch)
}
_ => {}
}
}
self.eye_particles();
}
}
+16 -6
View File
@@ -97,15 +97,25 @@ impl Game<'_> {
self.creative_screen.scroll = 0.0;
}
}
/// Typing or a backspace in the creative search box.
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>, backspace: bool) {
/// A backspace in the creative search box: with Ctrl, the whole word
/// before the caret (`EditBox.deleteWords(-1)`), otherwise one character.
/// A Select All selection is what it deletes, as in `EditBox.keyPressed`.
pub(super) fn creative_search_backspace(&mut self, ctrl: bool) {
let search = &mut self.creative_screen.search;
let cleared = self.text_selection.take(CREATIVE_SEARCH, search);
if backspace {
if !cleared {
if !self.text_selection.take(CREATIVE_SEARCH, search) {
if ctrl {
horizon_client::ui::delete_words(search, -1);
} else {
search.pop();
}
} else if let Some(text) = typed {
}
self.creative_screen.scroll = 0.0;
}
/// Typing in the creative search box.
pub(super) fn creative_search_edit(&mut self, typed: Option<&str>) {
let search = &mut self.creative_screen.search;
self.text_selection.take(CREATIVE_SEARCH, search);
if let Some(text) = typed {
clipboard::append_limited(search, text, CREATIVE_SEARCH_CHARS);
}
self.creative_screen.scroll = 0.0;
+5 -1
View File
@@ -191,8 +191,12 @@ impl Game<'_> {
}
/// `CombatTracker.getDeathMessage`.
pub(super) fn combat_death_message(&mut self) -> Text {
self.combat_death_message_for(Text::literal(PLAYER_NAME))
}
/// `CombatTracker.getDeathMessage` for a player whose display name is
/// `me`: a server's guest is not `PLAYER_NAME`.
pub(super) fn combat_death_message_for(&mut self, me: Text) -> Text {
self.recheck_combat();
let me = Text::literal(PLAYER_NAME);
let entries = std::mem::take(&mut self.combat.entries);
self.combat.in_combat = false;
let Some(killing) = entries.last() else {
+114 -27
View File
@@ -1,6 +1,7 @@
//! Headless command runner for `tools/test_command_exec_parity.py`: with
//! `HORIZON_COMMAND_SCRIPT` and `HORIZON_COMMAND_OUTPUT` set, the opened world
//! runs without a window. Each script line is a JSON operation: `cmd` runs a
//! runs on its server thread with a connected, headless client. Each script
//! line is a JSON operation: `cmd` runs a
//! command as the player (Commands.performPrefixedCommand) and records every
//! system message it produced, as styled spans, with the results reported to
//! the player's `CommandResultCallback`; `tick` advances the game; `settle`
@@ -41,30 +42,100 @@ pub(super) fn spans(text: &Text) -> Value {
}
impl Game<'_> {
/// Pump the real client's connection, without predicting movement: the
/// oracle's player stays where commands put it. Errors cross the server
/// boundary through Integrated::stop, including script and save failures.
pub(super) fn wait_command_harness(&mut self) -> Result<()> {
let server = self.integrated.take().ok_or("command harness: no server")?;
while !server.stopped() {
self.poll_stationary_client()?;
std::thread::sleep(Duration::from_millis(2));
}
server.stop()
}
/// The owner's authoritative body and level, using the same swaps as a
/// server command. Always put them back, also when a script operation fails.
fn harness_owner<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T>) -> Result<T> {
let owner = self
.serving
.as_ref()
.ok_or("command harness: not a server")?
.owner;
let mut host = self.lan.take().ok_or("command harness: no hub")?;
let guest = host.hub.guests.iter().find(|g| g.uuid == owner && g.placed);
let Some(guest) = guest else {
self.lan = Some(host);
return Err("command harness: owner is not connected".into());
};
let (conn, dim, back) = (guest.conn, super::Dim::from_id(&guest.dimension), self.dim);
if let Err(error) = self.enter_level(Some(&mut host), dim) {
self.lan = Some(host);
return Err(error);
}
let swap = self
.enter_guest(&mut host, conn)
.expect("the owner is not already acting");
self.lan = Some(host);
let result = f(self);
let mut host = self.lan.take().expect("the operation puts the hub back");
self.leave_guest(&mut host, swap);
host.hub.sync_all_effects();
self.run_level_teleports(&mut host);
let restored = self.enter_level(Some(&mut host), back);
self.lan = Some(host);
restored?;
result
}
/// The player's portal process finished in the nether portal it stands
/// in (the oracle's player is not ticked, so neither is the wait).
fn harness_portal(&mut self) -> Result<()> {
let Some(p) = &self.player else {
return Err("command harness: portal without a player".into());
};
let entry = horizon_core::position::BlockPos::containing(p.position);
let block = self.world.block(entry.x, entry.y, entry.z);
if &*self.res.facts().get(block).name != "minecraft:nether_portal" {
return Err("command harness: the player is not in a nether portal".into());
}
self.player_through_nether_portal(entry)
let (conn, plan) = self.harness_owner(|g| {
let p = g
.player
.as_ref()
.ok_or("command harness: portal without a player")?;
let entry = horizon_core::position::BlockPos::containing(p.position);
let block = g.world.block(entry.x, entry.y, entry.z);
if &*g.res.facts().get(block).name != "minecraft:nether_portal" {
return Err("command harness: the player is not in a nether portal".into());
}
let plan = g.portal_plan(
entry,
p.position,
p.dimensions.width,
p.dimensions.height,
true,
);
Ok((
g.lan_acting.ok_or("command harness: no acting owner")?,
plan,
))
})?;
// Start travel after restoring the owner's body: change_level updates
// its hub record, which leave_guest would otherwise overwrite.
self.in_owner_level(|g| {
let mut host = g.lan.take().ok_or("command harness: no hub")?;
g.start_server_trip(&mut host, conn, plan.dim, Some(plan));
g.lan = Some(host);
Ok(())
})
}
/// Load terrain until the player stands in lit chunks.
fn harness_settle(&mut self, deadline: Instant) -> Result<()> {
loop {
self.update_world();
self.spawn_player()?;
if let Some(p) = &self.player {
let (cx, cz) = (
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
);
if (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
// Finish requested terrain before inspecting it, so worker
// timing cannot change which command positions are loaded.
if !self.streaming.busy()
&& (-1..=1).all(|dz| (-1..=1).all(|dx| self.streaming.is_lit(cx + dx, cz + dz)))
{
// The oracle's settle also waits for the entities saved
// in those chunks (areEntitiesActuallyLoadedAndTicking):
// after a dimension change they come back from the save.
@@ -95,7 +166,19 @@ impl Game<'_> {
.and_then(|v| v.parse().ok())
.unwrap_or(600),
);
self.harness_settle(deadline)?;
// Join/configuration uses the normal hub, but never advances the world.
while !self
.lan
.as_ref()
.is_some_and(|h| h.hub.guests.iter().any(|g| g.placed && g.loaded))
{
self.tick_server(true)?;
if Instant::now() > deadline {
return Err("command harness: owner did not connect".into());
}
std::thread::sleep(Duration::from_millis(2));
}
self.harness_owner(|g| g.harness_settle(deadline))?;
let mut out = String::new();
for line in std::fs::read_to_string(script)?.lines() {
if line.trim().is_empty() {
@@ -107,9 +190,12 @@ impl Game<'_> {
let command = op["cmd"].as_str().unwrap_or("");
self.chat_capture = Some(Vec::new());
self.cmds.results = Some(Vec::new());
self.as_console(|g| {
g.run_command(command.strip_prefix('/').unwrap_or(command))
});
self.harness_owner(|g| {
g.as_console(|g| {
g.run_command(command.strip_prefix('/').unwrap_or(command))
});
Ok(())
})?;
let messages = self.chat_capture.take().unwrap_or_default();
let results = self.cmds.results.take().unwrap_or_default();
if op["record"].as_bool() != Some(false) {
@@ -124,17 +210,8 @@ impl Game<'_> {
}
"tick" => {
self.chat_capture = Some(Vec::new());
// The oracle's player has no client moving it: hold the
// player where commands put it while the game ticks.
let held = self.player.as_ref().map(|p| p.position);
for _ in 0..op["n"].as_u64().unwrap_or(1) {
self.update_world();
self.tick()?;
if let (Some(p), Some(at)) = (self.player.as_mut(), held) {
p.position = at;
p.velocity = horizon_core::geometry::Vec3::new(0.0, 0.0, 0.0);
p.fall_distance = 0.0;
}
self.tick_server(false)?;
}
let messages = self.chat_capture.take().unwrap_or_default();
if op["record"].as_bool() == Some(true) {
@@ -147,7 +224,17 @@ impl Game<'_> {
out.push('\n');
}
}
"settle" => self.harness_settle(deadline)?,
"settle" => {
// Finish portal arrivals using connection-only passes too.
while !self.server_trips.is_empty() {
self.tick_server(true)?;
if Instant::now() > deadline {
return Err("command harness: portal did not arrive".into());
}
std::thread::sleep(Duration::from_millis(2));
}
self.harness_owner(|g| g.harness_settle(deadline))?;
}
"portal" => self.harness_portal()?,
other => return Err(format!("command harness: unknown op {other}").into()),
}
+23 -12
View File
@@ -10,6 +10,7 @@ mod items;
mod misc;
mod place;
mod players;
pub(super) mod pregen;
mod raid;
mod terrain_cmds;
mod text_commands;
@@ -214,7 +215,7 @@ impl Game<'_> {
}
/// Player.getDisplayName: the name (team-formatted), suggesting a
/// `/tell`, showing the player on hover, inserting the name.
fn player_display_name(&self) -> Text {
pub(super) fn player_display_name(&self) -> Text {
let name = self.acting_player_name().to_owned();
let Some(uuid) = self.lan_acting_uuid else {
return self.target_name(Target::Player);
@@ -444,7 +445,7 @@ impl Game<'_> {
.find(|i| i.id == id)
.map(|i| i.stack.item.to_string())
.unwrap_or_default();
Text::literal(self.pack.names.item(&item))
Text::literal(self.pack.names.display_item(&item))
}
Target::Mob(id)
if self
@@ -751,13 +752,15 @@ impl Game<'_> {
&& !id.ends_with("get")
&& let Ok(t) = self.entities(ctx, "target", false)
{
self.cmds.waypoint_dirty.push(t[0]);
let target = self.waypoint_target(t[0]);
self.cmds.waypoint_dirty.push(target);
}
result
}
"ride.mount" | "ride.dismount" => self.cmd_ride(id, ctx),
"spreadplayers" => self.cmd_spreadplayers(ctx),
id if id.starts_with("forceload.") => self.cmd_forceload(id, ctx),
id if id.starts_with("pregen.") => self.cmd_pregen(id, ctx),
"fillbiome" => self.cmd_fillbiome(ctx),
id if id.starts_with("worldborder.") => self.cmd_worldborder(id, ctx),
id if id.starts_with("loot.") => self.cmd_loot(id, ctx),
@@ -2499,12 +2502,14 @@ impl Game<'_> {
};
let max = Self::int(ctx, "maxCount").unwrap_or(-1);
let counting = max == 0;
// Inventory.clearOrCountMatchingItems: main, armor, crafting grid, carried.
// Inventory slots 0..40: main, armor feet to head, off hand;
// then clearOrCountMatchingItems visits the crafting grid and carried stack.
let mut removed = 0i32;
let mut budget = if max < 0 { i32::MAX } else { max };
let all = |g: &Self| -> Vec<Option<ItemStack>> {
let mut v: Vec<Option<ItemStack>> = g.inventory.clone();
v.extend(g.armor.iter().cloned());
v.extend(g.armor.iter().rev().cloned());
v.push(g.offhand.clone());
v.extend(g.craft_grid.iter().cloned());
v.push(g.carried.clone());
v
@@ -2518,7 +2523,8 @@ impl Game<'_> {
.collect();
let mut slots: Vec<&mut Option<ItemStack>> = Vec::new();
slots.extend(self.inventory.iter_mut());
slots.extend(self.armor.iter_mut());
slots.extend(self.armor.iter_mut().rev());
slots.push(&mut self.offhand);
slots.extend(self.craft_grid.iter_mut());
slots.push(&mut self.carried);
for (slot, matches) in slots.into_iter().zip(matching) {
@@ -2809,7 +2815,7 @@ impl Game<'_> {
let name = match self.command_source.map(|s| s.entity) {
Some(Some(t)) => self.target_name(t),
Some(None) => Text::literal("Server"),
None => Text::literal(self.acting_player_name()),
None => self.player_display_name(),
};
let line = match id {
"say" => Text::translate("chat.type.announcement", &[name, message]),
@@ -2819,14 +2825,14 @@ impl Game<'_> {
// Whispering to yourself: the incoming and outgoing lines.
let out = Text::translate(
"commands.message.display.outgoing",
&[Text::literal(self.acting_player_name()), message.clone()],
&[self.player_display_name(), message.clone()],
)
.with_color(text::GRAY)
.italic();
self.system_message(out);
Text::translate(
"commands.message.display.incoming",
&[Text::literal(self.acting_player_name()), message],
&[self.player_display_name(), message],
)
.with_color(text::GRAY)
.italic()
@@ -2836,9 +2842,14 @@ impl Game<'_> {
capture.push(line.clone());
}
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.gui.atlas, line, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
line,
None,
horizon_client::chat::ChatSource::Player,
self.ticks,
focused,
);
Ok(1)
}
/// MessageArgument: `@p`-style selectors in a message become names.
@@ -606,10 +606,7 @@ impl Game<'_> {
.collect(),
_ => Vec::new(),
},
Some("vehicle") => match entity {
Target::Player => self.riding.map(Target::Mob).into_iter().collect(),
_ => Vec::new(),
},
Some("vehicle") => self.ride_vehicle(entity).into_iter().collect(),
Some("controller") | Some("passengers") => match entity {
Target::Mob(id) if self.mobs.iter().any(|m| m.id == id && m.rider.is_some()) => {
vec![Target::Player]
@@ -57,6 +57,8 @@ pub(in crate::game) struct CommandExtras {
/// The `CommandResultCallback` results of the outermost source, when a
/// harness records them.
pub results: Option<Vec<(bool, i32)>>,
/// The running `/pregen` task.
pub pregen: Option<super::pregen::PregenTask>,
}
use horizon_core::version::{BUILD_TIME, DATA_VERSION, STABLE, VANILLA_VERSION, VERSION_ID};
@@ -212,8 +214,22 @@ impl Game<'_> {
// ---- /waypoint ------------------------------------------------------
/// A guest's body is only `Player` during its turn; retained command state
/// must use its connection so the next server tick still finds that body.
pub(super) fn waypoint_target(&self, t: Target) -> Target {
match t {
Target::Player => self.lan_acting.map_or(t, Target::Guest),
_ => t,
}
}
/// A living entity's `waypoint_transmit_range` (`isTransmittingWaypoint`).
fn transmit_range(&mut self, t: Target) -> f64 {
if matches!(t, Target::Guest(_)) {
return self
.for_player(t, |g| g.transmit_range(Target::Player))
.unwrap_or(0.0);
}
if t == Target::Player {
return self
.player
@@ -242,7 +258,7 @@ impl Game<'_> {
fn waypoint_transmitters(&mut self) -> Vec<Target> {
if self.cmds.waypoints.is_none() {
let tracked = if self.transmit_range(Target::Player) > 0.0 {
vec![Target::Player]
vec![self.waypoint_target(Target::Player)]
} else {
Vec::new()
};
@@ -255,6 +271,12 @@ impl Game<'_> {
.collect();
self.cmds.waypoints = Some(alive.clone());
alive
.into_iter()
.map(|t| match t {
Target::Guest(conn) if self.lan_acting == Some(conn) => Target::Player,
_ => t,
})
.collect()
}
/// The waypoint part of a living entity's tick: dirty transmit ranges
/// track or untrack it.
@@ -277,7 +299,7 @@ impl Game<'_> {
fn waypoint_icon(&self, t: Target) -> WaypointIcon {
self.cmds
.waypoint_icons
.get(&t)
.get(&self.waypoint_target(t))
.cloned()
.unwrap_or_default()
}
@@ -387,6 +409,7 @@ impl Game<'_> {
&[Text::colored(name, rgb)],
)
};
let t = self.waypoint_target(t);
self.cmds.waypoint_icons.insert(t, icon);
// WaypointCommand.mutateIcon: untrack, change, track again.
self.waypoint_transmitters();
@@ -606,6 +629,7 @@ impl Game<'_> {
.hub
.guests
.iter()
.filter(|g| lan.hub.singleplayer_owner != Some(g.uuid))
.filter(|g| match &s.player_name {
Some(name) => g.name.eq_ignore_ascii_case(name),
None => s.kind == 'a' || s.kind == 'e',
@@ -617,7 +641,7 @@ impl Game<'_> {
if host.is_empty() && guests.is_empty() {
return Err(err("argument.entity.notfound.player", &[]));
}
if self.lan.is_none() {
if self.lan.is_none() || (self.serving() && self.published_port().is_none()) {
return Err(err("commands.kick.singleplayer.failed", &[]));
}
let reason_raw = match ctx.get("reason") {
@@ -0,0 +1,276 @@
//! `/pregen`, Horizon's own command: generate, light and save every chunk of a
//! square or a circle ahead of the players (docs/pregeneration.md). The task
//! lives on the server and hands its band to the level's streaming, whose
//! workers do the work; chunks behind the band unload and are saved as any
//! chunk the players leave.
use super::{CommandError, Context, Dim, Game, R};
use horizon_client::{
lan::data::component_nbt,
pregen::{Pregen, Shape},
text::{self, Text},
};
use horizon_protocol::packets::play::{self, Clientbound as C};
use std::time::{Duration, Instant};
/// How often the progress is reported.
const REPORT_EVERY: Duration = Duration::from_secs(5);
/// How long the band may stay put before the task looks for what holds it.
const STALL: Duration = Duration::from_secs(30);
pub(in crate::game) struct PregenTask {
pregen: Pregen,
dim: Dim,
paused: bool,
/// Time spent running, up to the last pause, and when it last resumed.
ran: Duration,
resumed: Instant,
reported: Instant,
/// When the band last moved, to notice a task that stopped advancing.
moved: Instant,
/// The player who started it, told the progress too (a guest's connection).
owner: Option<u32>,
}
impl PregenTask {
fn running_for(&self) -> Duration {
if self.paused {
self.ran
} else {
self.ran + self.resumed.elapsed()
}
}
fn progress(&self) -> Text {
let p = &self.pregen;
let seconds = self.running_for().as_secs_f64();
let rate = p.done as f64 / seconds.max(1e-3);
let left = p.total - p.done;
let eta = if rate > 0.0 {
duration(left as f64 / rate)
} else {
"unknown".into()
};
Text::literal(format!(
"Pregenerating {}: {} of {} chunks ({:.1}%), {rate:.1} chunks/s, {} left",
self.dim.id(),
p.done,
p.total,
100.0 * p.done as f64 / p.total.max(1) as f64,
if p.done == p.total {
"nothing".into()
} else {
eta
},
))
}
}
fn failure(message: &str) -> CommandError {
CommandError::new(Text::literal(message))
}
/// `1h 02m 03s`.
fn duration(seconds: f64) -> String {
let s = seconds.round() as u64;
match (s / 3600, s / 60 % 60, s % 60) {
(0, 0, s) => format!("{s}s"),
(0, m, s) => format!("{m}m {s:02}s"),
(h, m, s) => format!("{h}h {m:02}m {s:02}s"),
}
}
impl Game<'_> {
pub(super) fn cmd_pregen(&mut self, id: &str, ctx: &Context) -> R<i32> {
match id {
"pregen.start" => {
if self.cmds.pregen.is_some() {
return Err(failure(
"Pregeneration is already running: /pregen cancel stops it",
));
}
let radius = Self::int(ctx, "radius").unwrap_or(0);
let shape = if ctx.literals.iter().any(|l| l == "circle") {
Shape::Circle
} else {
Shape::Square
};
let [x, z] = if ctx.get("center").is_some() {
self.column_arg(ctx, "center")?
} else {
let p = self.source_position();
[p[0].floor() as i32, p[2].floor() as i32]
};
let pregen = Pregen::new((x >> 4, z >> 4), radius >> 4, shape);
let now = Instant::now();
let total = pregen.total;
self.feedback(Text::literal(format!(
"Pregenerating {total} chunks of {}: a {} of radius {radius} around {x} {z}",
self.dim.id(),
match shape {
Shape::Square => "square",
Shape::Circle => "circle",
},
)));
self.cmds.pregen = Some(PregenTask {
pregen,
dim: self.dim,
paused: false,
ran: Duration::ZERO,
resumed: now,
reported: now,
moved: now,
owner: self.lan_acting,
});
Ok(total as i32)
}
"pregen.pause" | "pregen.continue" => {
let pause = id == "pregen.pause";
let task = self
.cmds
.pregen
.as_mut()
.ok_or_else(|| failure("No pregeneration is running"))?;
if task.paused != pause {
task.paused = pause;
if pause {
task.ran += task.resumed.elapsed();
} else {
task.resumed = Instant::now();
}
}
let (progress, dim) = (task.progress(), task.dim);
if pause && self.dim == dim {
self.streaming.set_band(None);
}
self.feedback(
Text::literal(if pause { "Paused. " } else { "Continuing. " }).append(progress),
);
Ok(1)
}
"pregen.cancel" => {
let task = self
.cmds
.pregen
.take()
.ok_or_else(|| failure("No pregeneration is running"))?;
if self.dim == task.dim {
self.streaming.set_band(None);
}
self.feedback(Text::literal("Cancelled. ").append(task.progress()));
Ok(task.pregen.done as i32)
}
_ => {
let task = self
.cmds
.pregen
.as_ref()
.ok_or_else(|| failure("No pregeneration is running"))?;
let progress = task.progress();
let done = task.pregen.done as i32;
self.feedback(progress);
Ok(done)
}
}
}
/// Move the task's band past the rows that are lit and hand it to the
/// level's streaming, and report the progress now and then. Runs before
/// each streaming update of the level in place.
pub(in crate::game) fn tick_pregen(&mut self) {
let Some(task) = self.cmds.pregen.as_mut() else {
return;
};
if task.dim != self.dim || task.paused {
return;
}
// A row is done once its chunks are lit and post-processed
// (`postprocess_chunks`, on the tick), as vanilla's are by the time
// they are FULL: then they may unload and be saved.
let (streaming, chunks) = (&mut self.streaming, &self.world.chunks);
if task.pregen.advance(|x, z| {
streaming.is_lit(x, z)
&& chunks
.get(&(x, z))
.is_some_and(|c| c.postprocess.is_empty())
}) {
task.moved = Instant::now();
}
streaming.set_band(task.pregen.band());
if task.moved.elapsed() >= STALL {
// Nothing advanced for a while: say what the first row waits
// for, and queue light again for chunks that lost their job.
task.moved = Instant::now();
let row = task.pregen.first_row();
let waiting = row
.iter()
.filter(|k| chunks.get(k).is_some_and(|c| !c.postprocess.is_empty()))
.count();
let [missing, lighting, unlit] = streaming.unstick_light(&mut self.world, &row);
log::warn!(
"Horizon: pregeneration waits on row {:?}: {missing} not loaded, {lighting} being lit, \
{unlit} unlit with no light job (queued again), {waiting} not post-processed; {:?}",
row.first(),
streaming.stages()
);
}
let finished = task.pregen.finished();
if finished || task.reported.elapsed() >= REPORT_EVERY {
task.reported = Instant::now();
let (owner, mut message) = (task.owner, task.progress());
if finished {
message = Text::literal("Done. ")
.append(message)
.with_color(text::GREEN);
self.cmds.pregen = None;
}
self.pregen_report(owner, message);
}
}
/// Whether the level in place has a running task, which the server pumps
/// between its ticks (`pump_pregen`).
pub(in crate::game) fn pregen_runs_here(&self) -> bool {
self.cmds
.pregen
.as_ref()
.is_some_and(|t| t.dim == self.dim && !t.paused)
}
/// The level a running task needs ticked, whoever is in it.
pub(in crate::game) fn pregen_level(&self) -> Option<Dim> {
self.cmds.pregen.as_ref().map(|t| t.dim)
}
/// Keep the workers fed until `until`: collect what they finished and
/// hand them the next jobs as soon as each one is done, rather than once
/// a tick.
pub(in crate::game) fn pump_pregen(&mut self, until: Instant) {
while self.pregen_runs_here() {
let now = Instant::now();
if now >= until {
break;
}
self.streaming
.wait((until - now).min(Duration::from_millis(5)));
self.update_world();
}
}
/// The console and the player who started the task get the progress.
fn pregen_report(&mut self, owner: Option<u32>, message: Text) {
if self.options.dedicated.is_some() {
super::super::dedicated::log("INFO", &message.plain());
} else {
log::info!("{}", message.plain());
}
if let Some(host) = &self.lan {
if let Some(g) = owner.and_then(|c| host.hub.guest(c)) {
g.send(&C::SystemChat(play::SystemChat {
content: component_nbt(&message.component()),
overlay: false,
}));
}
} else if self.options.dedicated.is_none() {
self.system_message(message);
}
}
}
@@ -30,7 +30,7 @@ fn ticks_to_seconds(ticks: i64) -> String {
impl Game<'_> {
// ---- /forceload ----------------------------------------------------------
fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
pub(super) fn column_arg(&self, ctx: &Context, name: &str) -> R<[i32; 2]> {
let c = self
.coords(ctx, name)
.ok_or_else(|| err("argument.pos2d.incomplete", &[]))?;
@@ -1074,15 +1074,15 @@ impl Game<'_> {
};
let name = self.target_name(target);
if id == "ride.dismount" {
let vehicle = match target {
Target::Player => self.riding.map(Target::Mob),
_ => None,
};
let Some(v) = vehicle else {
let Some(v) = self.ride_vehicle(target) else {
return Err(err("commands.ride.not_riding", &[&name.plain()]));
};
let vehicle_name = self.target_name(v);
self.dismount_mount();
match target {
Target::Player => self.dismount_mount(),
Target::Mob(rider) => self.dismount_mob(rider),
_ => {}
}
self.feedback(Text::translate(
"commands.ride.dismount.success",
&[name, vehicle_name],
@@ -1094,11 +1094,8 @@ impl Game<'_> {
return Ok(0);
};
let vehicle_name = self.target_name(vehicle);
if target == Target::Player && self.riding.is_some() {
let current = self
.riding
.map(Target::Mob)
.map_or_else(Text::empty, |v| self.target_name(v));
if let Some(current) = self.ride_vehicle(target) {
let current = self.target_name(current);
return Err(err(
"commands.ride.already_riding",
&[&name.plain(), &current.plain()],
@@ -1107,22 +1104,42 @@ impl Game<'_> {
if vehicle == Target::Player {
return Err(err("commands.ride.mount.failure.cant_ride_players", &[]));
}
if target == vehicle {
return Err(err("commands.ride.mount.failure.loop", &[]));
// getSelfAndPassengers: the vehicle is the target or rides it.
let mut up = Some(vehicle);
while let Some(v) = up {
if v == target {
return Err(err("commands.ride.mount.failure.loop", &[]));
}
up = self.ride_vehicle(v);
}
// The player can ride mobs that carry a rider.
// Players and mobs can ride mobs.
let Target::Mob(mob_id) = vehicle else {
return Err(err(
"commands.ride.mount.failure.generic",
&[&name.plain(), &vehicle_name.plain()],
));
};
if target != Target::Player || !self.mobs.iter().any(|m| m.id == mob_id && m.alive()) {
let rider = match target {
Target::Mob(id) => Some(id),
_ => None,
};
if !(target == Target::Player || rider.is_some())
|| !self.mobs.iter().any(|m| m.id == mob_id && m.alive())
{
return Err(err(
"commands.ride.mount.failure.generic",
&[&name.plain(), &vehicle_name.plain()],
));
}
if let Some(rider) = rider {
// Entity.startRiding.
self.mount_mob(rider, mob_id);
self.feedback(Text::translate(
"commands.ride.mount.success",
&[name, vehicle_name],
));
return Ok(1);
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == mob_id) {
m.extra.flag = false;
m.extra.counter = 0;
@@ -1138,6 +1155,47 @@ impl Game<'_> {
Ok(1)
}
/// Entity.getVehicle: the player's mount, or a mob's.
pub(super) fn ride_vehicle(&self, t: Target) -> Option<Target> {
let id = match t {
Target::Player => return self.riding.map(Target::Mob),
Target::Mob(id) => self.mobs.iter().find(|m| m.id == id)?.extra.mount?,
_ => return None,
};
Some(if self.boats.iter().any(|b| b.id == id) {
Target::Boat(id)
} else {
Target::Mob(id)
})
}
/// LivingEntity.stopRiding for a mob: off its vehicle
/// (Entity.removePassenger), then to where the vehicle lets it out
/// (LivingEntity.dismountVehicle).
fn dismount_mob(&mut self, rider: u32) {
let Some(i) = self.mobs.iter().position(|m| m.id == rider) else {
return;
};
let Some(v) = self.mobs[i].extra.mount.take() else {
return;
};
let (width, yaw) = (f64::from(self.mobs[i].width()), self.mobs[i].yaw);
let at = if let Some(b) = self.boats.iter().position(|b| b.id == v) {
self.boat_dismount_target(b, width, yaw)
} else if let Some(m) = self.mobs.iter_mut().find(|m| m.id == v) {
m.extra.rider = None;
// Entity.getDismountLocationForPassenger: on top of the vehicle.
let p = m.position;
horizon_core::geometry::Vec3::new(p.x, p.y + f64::from(m.height()), p.z)
} else {
self.mobs[i].position
};
let m = &mut self.mobs[i];
m.extra.passenger = false;
m.extra.boarding_cooldown = super::super::boat_passengers::BOARDING_COOLDOWN;
m.position = at;
m.previous = at;
}
// ---- /spreadplayers -----------------------------------------------------------------------
pub(super) fn cmd_spreadplayers(&mut self, ctx: &Context) -> R<i32> {
+19 -2
View File
@@ -285,6 +285,13 @@ impl Game<'_> {
"pad" => Ok(Some(self.pad_command(&words)?)),
"key" => {
let key = key_code(arg(1)?).ok_or_else(|| format!("unknown key {}", words[1]))?;
// A server's dialog takes the keys, in configuration too.
if self.dialog_open() {
if arg(2)? != "up" {
self.dialog_key(key, None, None)?;
}
return ok();
}
self.require_world()?;
// The sign editor takes raw presses (Enter, arrows, Backspace, Escape).
if self.sign_edit.is_some() {
@@ -338,6 +345,11 @@ impl Game<'_> {
if action == "tap" {
self.extras_key(physical, false, false);
}
// So do mods' keys (capability `input`).
self.mod_key(physical, action != "up", action == "repeat");
if action == "tap" {
self.mod_key(physical, false, false);
}
// Text screens consume raw presses; releases follow key binds.
let typing = matches!(self.screen, Screen::Chat | Screen::Options);
let key = if typing && arg(2)? != "up" {
@@ -590,13 +602,17 @@ impl Game<'_> {
))
}
"type" => {
self.require_world()?;
let text = line
.trim_start()
.strip_prefix("type")
.unwrap_or("")
.strip_prefix(' ')
.unwrap_or("");
// A server's dialog, in configuration too.
if self.dialog_type(text) {
return ok();
}
self.require_world()?;
if self.book.is_some() {
self.book_type(text);
return ok();
@@ -626,7 +642,7 @@ impl Game<'_> {
}
Screen::Creative if self.creative_screen.tab().search => {
// As typed: replaces a selected query, keeps the length limit.
self.creative_search_edit(Some(text), false)
self.creative_search_edit(Some(text))
}
_ => {
return Err(
@@ -856,6 +872,7 @@ impl Game<'_> {
Screen::Friends => "friends",
Screen::CommandBlock => "command-block",
Screen::Win => "win",
Screen::Mod => "mod",
}
}
+37 -16
View File
@@ -43,10 +43,6 @@ fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32
#[derive(Default)]
pub(super) struct Creatures {
pub projectiles: Vec<Projectile>,
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
pub pearl_cooldown: u32,
/// The wind charge's use cooldown (ticks).
pub wind_cooldown: u32,
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
pub wind_bursts: Vec<super::wind::Burst>,
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
@@ -645,7 +641,6 @@ impl Game<'_> {
self.tick_allays();
self.tick_breeze_effects();
self.tick_sniffer_effects();
self.tick_player_effects();
self.piglin_pickups();
self.sulfur_cube_pickups();
// Hurt and death sounds of damage dealt outside the mob ticks.
@@ -1565,12 +1560,15 @@ impl Game<'_> {
id, ticks, amplifier,
));
}
/// Burning applied to the player by mobs.
fn tick_player_effects(&mut self) {
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
if self.creatures.pearl_cooldown > 0 {
self.creatures.pearl_cooldown -= 1;
/// `WitherRoseBlock.entityInside` for the player: on a server level that
/// isn't peaceful, `getBeeInteractionEffect` (Wither, 40 ticks) unless the
/// player is invulnerable to wither damage (creative, spectator). A
/// server's player gets it from the server.
pub(super) fn wither_rose_contact(&mut self) {
if self.remote.is_some() || self.ui.difficulty == 0 {
return;
}
self.give_player_effect("minecraft:wither", 40, 0);
}
pub(super) fn hurt_player_by(&mut self, damage_type: &str, amount: f32) {
if self.creative {
@@ -1701,7 +1699,26 @@ impl Game<'_> {
targets: targets_guests,
};
let guest_entities = self.lan_guest_entities();
// ThrownEnderpearl.tick: a dead player's pearl is discarded in
// place of its tick while ender_pearls_vanish_on_death is on.
let vanish = self.ui.rules.bool("ender_pearls_vanish_on_death");
let host_dead = self.player_view().is_some_and(|p| !p.alive);
let dead_guests: Vec<u32> = self.lan.as_ref().map_or_else(Vec::new, |h| {
h.hub
.guests
.iter()
.filter(|g| g.dead)
.map(|g| g.conn)
.collect()
});
projectiles.retain_mut(|p| {
if vanish
&& matches!(p.kind, ProjectileKind::EnderPearl)
&& p.owner == Some(Who::Player)
&& p.guest.map_or(host_dead, |c| dead_guests.contains(&c))
{
return false;
}
let mob_shot = !matches!(p.owner, Some(Who::Player));
// A player's arrows, snowballs and eggs meet every player; a
// guest's flies from that guest (Projectile.getOwner), not
@@ -2853,14 +2870,14 @@ impl Game<'_> {
let kind = match item {
"minecraft:snowball" => ProjectileKind::Snowball,
"minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg,
"minecraft:ender_pearl" => {
if self.creatures.pearl_cooldown > 0 {
return Ok(true);
"minecraft:ender_pearl" => ProjectileKind::EnderPearl,
"minecraft:wind_charge" => {
let thrown = self.throw_wind_charge()?;
if thrown {
self.apply_use_cooldown(stack);
}
self.creatures.pearl_cooldown = 20;
ProjectileKind::EnderPearl
return Ok(thrown);
}
"minecraft:wind_charge" => return self.throw_wind_charge(),
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
_ => return Ok(false),
};
@@ -2885,6 +2902,9 @@ impl Game<'_> {
);
self.creatures.projectiles.push(proj);
self.player_projectile_shot();
// ItemStack.use's applyAfterUseComponentSideEffects: the pearl's
// second is the `use_cooldown` component, as for any thrown item.
self.apply_use_cooldown(stack);
let sound = match kind {
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
ProjectileKind::Egg => "minecraft:entity.egg.throw",
@@ -3005,6 +3025,7 @@ impl Game<'_> {
continue;
}
}
self.mark_entity(entity_start, &mob.kind.id);
let light = self.world.light(
mob.position.x.floor() as i32,
(mob.position.y + mob.eye_height()).floor() as i32,
+11 -1
View File
@@ -155,6 +155,14 @@ pub(super) fn preflight(options: &mut Options) -> Result<bool> {
for w in &props.warnings {
log("WARN", w);
}
// Horizon's own commands are the owner's choice, off as on vanilla.
if props
.raw
.get(horizon_client::command::vanilla::PREGEN_PROPERTY)
.is_some_and(|v| v.trim().eq_ignore_ascii_case("true"))
{
horizon_client::command::vanilla::set_horizon_commands(true);
}
props.store(&settings)?;
let eula_file = PathBuf::from("eula.txt");
let agreed = match eula::agreed(&eula_file) {
@@ -667,7 +675,9 @@ impl Game<'_> {
self.poll_server_control(&mut state);
let players = self.lan.as_ref().map_or(0, |h| h.hub.guests.len());
if pause_after > 0 {
if players == 0 {
// A `/pregen` task keeps the server busy as a player would:
// paused, nothing would post-process its chunks.
if players == 0 && self.pregen_level().is_none() {
state.empty_ticks += 1;
} else {
state.empty_ticks = 0;
+611
View File
@@ -0,0 +1,611 @@
//! A server's dialogs bound to the game (`ClientCommonPacketListenerImpl.
//! showDialog` and `clearDialog`, `DialogScreen`, its `WarningScreen` and the
//! `WaitingForResponseScreen`): the screen over whatever is open (the
//! connecting screen in configuration), its inputs, and the actions its
//! buttons send back.
use super::Game;
use horizon_client::{
Result,
clipboard::EditShortcut,
confirm_screen::Confirm,
dialog::{AfterAction, Click, Control, Dialog, InputValue},
dialog_screen::{BOX, Layout, Part, WARNING_SPRITES, waiting_button},
hud::{HudBatch, rgba},
text::Text,
ui,
};
use horizon_world::nbt::Tag;
use std::time::Instant;
use winit::keyboard::KeyCode;
/// An open `DialogScreen`.
struct Open {
dialog: Dialog,
values: Vec<InputValue>,
/// The box of each text input.
fields: Vec<Option<ui::EditBox>>,
focus: Option<usize>,
scroll: ui::Scroll,
}
/// The dialog screens a server can open.
#[derive(Default)]
pub(super) struct DialogState {
open: Option<Open>,
/// `WaitingForResponseScreen`, since when.
waiting: Option<Instant>,
/// `DialogScreen.WarningScreen`, over the dialog.
warning: bool,
}
fn warning_texts() -> (Text, Text, [Text; 2]) {
let t = |key: &str| Text::translate(key, &[]);
(
t("menu.custom_screen_info.title"),
t("menu.custom_screen_info.contents"),
[t("menu.disconnect"), t("gui.back")],
)
}
impl Game<'_> {
/// Whether a dialog screen takes the input.
pub(super) fn dialog_open(&self) -> bool {
let d = &self.dialogs;
d.open.is_some() || d.waiting.is_some() || d.warning
}
/// `showDialog`: the dialog replaces an open one (and a waiting screen);
/// under the warning screen, it is what Back returns to.
pub(super) fn show_dialog(&mut self, tag: &Tag) {
let Some(dialog) = Dialog::parse(tag) else {
log::warn!("Horizon: failed to show dialog for data {tag:?}");
return;
};
let values = dialog.inputs.iter().map(|i| i.control.initial()).collect();
let fields = dialog
.inputs
.iter()
.map(|i| match &i.control {
Control::Text {
width,
initial,
max_length,
..
} => {
let mut edit = ui::EditBox::new(0.0, 0.0, *width as f32, 20.0);
edit.max_length = (*max_length).max(1) as usize;
edit.set_value(initial);
edit.focused = false;
Some(edit)
}
_ => None,
})
.collect();
self.dialogs.open = Some(Open {
dialog,
values,
fields,
focus: None,
scroll: ui::Scroll::default(),
});
self.dialogs.waiting = None;
self.capture(false);
}
/// `clearDialog`: the dialog closes (under the warning screen, Back then
/// returns to what was open before it).
pub(super) fn clear_dialog(&mut self) {
if self.dialogs.open.take().is_some() && !self.dialog_open() {
self.dialog_closed();
}
}
/// Every dialog screen goes (a disconnect, or the level loading screen).
pub(super) fn close_dialogs(&mut self) {
self.dialogs = DialogState::default();
}
fn dialog_closed(&mut self) {
if self.player.is_some() && self.screen == super::Screen::Playing && self.title.is_none() {
self.capture(true);
}
}
/// The input values as the controls hold them now.
fn dialog_values(open: &mut Open) {
for (value, field) in open.values.iter_mut().zip(&open.fields) {
if let Some(f) = field {
*value = InputValue::Text(f.value.clone());
}
}
}
/// `DialogScreen.runAction`: the click event, then the screen the dialog's
/// `after_action` leaves.
fn run_dialog_action(&mut self, click: Option<Click>, after: AfterAction) -> Result<()> {
match after {
AfterAction::None => {}
AfterAction::Close => self.dialogs.open = None,
AfterAction::WaitForResponse => {
self.dialogs.open = None;
self.dialogs.waiting = Some(Instant::now());
}
}
match click {
Some(Click::Custom { id, payload }) => {
if let Some(r) = &self.remote {
r.session.send_custom_click(&id, payload);
}
}
Some(Click::RunCommand(command)) => {
// In configuration there is nothing to run it (vanilla warns).
if self.player.is_some() {
let command = command.strip_prefix('/').unwrap_or(&command);
self.send_chat(&format!("/{command}"));
} else {
log::warn!(
"Horizon: commands are not supported in configuration, trying to run '{command}'"
);
}
}
Some(Click::ShowDialog(dialog)) => self.show_dialog_ref(&dialog),
Some(Click::CopyToClipboard(value)) => {
use horizon_client::clipboard::Clipboard;
self.clipboard.set(&value);
}
Some(other) => log::info!("Horizon: dialog action {other:?} is not supported yet"),
None => {}
}
if !self.dialog_open() {
self.dialog_closed();
}
Ok(())
}
/// A `show_dialog` click event's dialog: a registry id or the dialog itself.
fn show_dialog_ref(&mut self, dialog: &Tag) {
match dialog {
Tag::String(id) => {
let id = id.to_string_lossy();
let name = if id.contains(':') {
id.clone()
} else {
format!("minecraft:{id}")
};
let found = self.remote.as_ref().and_then(|r| {
let entries = r.registries.registries.get("minecraft:dialog")?;
entries.iter().find(|(n, _)| *n == name)?.1.clone()
});
match found {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
tag => self.show_dialog(tag),
}
}
/// `ClientboundShowDialogPacket` in play: a registry entry or the dialog.
pub(super) fn show_play_dialog(
&mut self,
dialog: &horizon_protocol::packets::play::DialogHolder,
) {
use horizon_protocol::packets::play::DialogHolder;
match dialog {
DialogHolder::Direct(tag) => self.show_dialog(tag),
DialogHolder::Registry(id) => {
let tag = self
.remote
.as_ref()
.and_then(|r| r.registries.data("minecraft:dialog", *id).cloned());
match tag {
Some(tag) => self.show_dialog(&tag),
None => log::warn!("Horizon: unknown dialog {id}"),
}
}
}
}
fn dialog_layout(&self) -> Option<Layout> {
let open = self.dialogs.open.as_ref()?;
Some(Layout::new(
&open.dialog,
&self.gui.atlas.font,
self.gui_size(),
))
}
pub(super) fn draw_dialog(&mut self, batch: &mut HudBatch) {
if !self.dialog_open() {
return;
}
let (w, h) = (batch.width, batch.height);
let cursor = self.cursor;
let atlas = &self.gui.atlas;
if self.player.is_none() {
// In place of the connecting screen, on its background.
batch.fill(atlas, 0.0, 0.0, w, h, rgba(20, 20, 20, 255));
}
ui::menu_background(batch, atlas, 0.0, 0.0, w, h, self.player.is_some());
if self.dialogs.warning {
let (title, message, [disconnect, back]) = warning_texts();
Confirm::new(&atlas.font, (w, h), &title, &message).draw(
batch,
atlas,
cursor,
[&disconnect, &back],
);
return;
}
if let Some(since) = self.dialogs.waiting {
// HeaderAndFooterLayout(33, 0) centred: the title, the button 33 below.
let ticks = (since.elapsed().as_millis() / 50) as u32;
let (label, visible, active) = waiting_button(ticks);
let title = Text::translate("gui.waitingForResponse.title", &[]);
let top = ((h - 53.0) / 2.0).trunc();
let tw = atlas.font.width_text(&title);
batch.text_styled(
atlas,
&title,
((w - tw) / 2.0).trunc(),
top + 12.0,
u32::MAX,
true,
);
if visible {
let (bx, by) = (((w - 200.0) / 2.0).trunc(), top + 33.0);
let hover = ui::hovered(cursor, bx, by, 200.0, 20.0);
ui::button(batch, atlas, bx, by, 200.0, 20.0, &label, active, hover);
}
return;
}
let Some(layout) = self.dialog_layout() else {
return;
};
let Some(open) = self.dialogs.open.as_mut() else {
return;
};
let atlas = &self.gui.atlas;
let [ax, ay, aw, ah] = layout.area;
open.scroll.clamp(ay, ay + ah, layout.content);
batch.text_styled(
atlas,
&open.dialog.title,
layout.title.0,
layout.title.1,
u32::MAX,
true,
);
let [wx, wy, ww, wh] = layout.warning;
let warn_hover = ui::hovered(cursor, wx, wy, ww, wh);
horizon_client::widgets::record("warning", layout.warning, true);
batch.sprite_scaled(
atlas,
WARNING_SPRITES[if warn_hover { 2 } else { 0 }],
wx,
wy,
ww,
wh,
u32::MAX,
);
let buttons = open.dialog.buttons();
let in_area = |y: f32| y >= ay && y < ay + ah;
let mut tooltip = None;
let mut start = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && start.is_none() {
start = Some(batch.vertices.len());
} else if !clipped && let Some(s) = start.take() {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
match part {
Part::Line(text, x, y) => {
batch.text_styled(atlas, &text, x, y, u32::MAX, true);
}
Part::Field { input, rect } => {
if let Some(Some(edit)) = open.fields.get_mut(input) {
[edit.x, edit.y, edit.width, edit.height] = rect;
edit.focused = open.focus == Some(input);
edit.draw(batch, atlas, None);
}
}
Part::Check { input, rect } => {
let [x, y, cw, ch] = rect;
let hover = in_area(cursor.1) && ui::hovered(cursor, x, y, cw, ch);
let on = open.values.get(input) == Some(&InputValue::Bool(true));
let sprite = match (on, hover) {
(true, true) => "gui/sprites/widget/checkbox_selected_highlighted",
(true, false) => "gui/sprites/widget/checkbox_selected",
(false, true) => "gui/sprites/widget/checkbox_highlighted",
(false, false) => "gui/sprites/widget/checkbox",
};
let Control::Boolean { label, .. } = &open.dialog.inputs[input].control else {
continue;
};
horizon_client::widgets::record(&label.plain(), rect, true);
batch.sprite_scaled(atlas, sprite, x, y, BOX, BOX, u32::MAX);
batch.text_styled(
atlas,
label,
x + BOX + 4.0,
y + 4.0,
rgba(224, 224, 224, 255),
true,
);
}
Part::Button { index, rect } => {
let [x, y, bw, bh] = rect;
let hover =
(!clipped || in_area(cursor.1)) && ui::hovered(cursor, x, y, bw, bh);
let b = buttons[index];
ui::button(batch, atlas, x, y, bw, bh, &b.label, true, hover);
if hover && let Some(t) = &b.tooltip {
tooltip = Some(t.clone());
}
}
}
}
if let Some(s) = start {
batch.clip_since(s, ax, ay, ax + aw, ay + ah);
}
if layout.content > ah {
ui::scrollbar(
batch,
atlas,
ax + aw - 6.0,
ay,
ay + ah,
layout.content,
open.scroll.amount,
);
}
if warn_hover {
tooltip = Some(Text::translate("menu.custom_screen_info.tooltip", &[]));
}
if let Some(t) = tooltip {
let lines: Vec<Text> = atlas
.font
.split_lines(&t, 170.0)
.into_iter()
.map(|l| l.0)
.collect();
ui::tooltip(batch, atlas, &lines, cursor);
}
}
/// A left click on a dialog screen.
pub(super) fn dialog_click(&mut self) -> Result<()> {
let cursor = self.cursor;
if self.dialogs.warning {
let (title, message, _) = warning_texts();
let answer = Confirm::new(&self.gui.atlas.font, self.gui_size(), &title, &message)
.answer_at(cursor);
match answer {
Some(true) => {
self.audio.play_button_click();
let reason = Text::translate("menu.custom_screen_info.disconnect", &[]);
return self.leave_server(Some(reason.plain()));
}
Some(false) => {
self.audio.play_button_click();
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
None => {}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
let (w, h) = self.gui_size();
let active = waiting_button((since.elapsed().as_millis() / 50) as u32).2;
let (bx, by) = (
((w - 200.0) / 2.0).trunc(),
((h - 53.0) / 2.0).trunc() + 33.0,
);
if active && ui::hovered(cursor, bx, by, 200.0, 20.0) {
self.audio.play_button_click();
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let Some(layout) = self.dialog_layout() else {
return Ok(());
};
let [wx, wy, ww, wh] = layout.warning;
if ui::hovered(cursor, wx, wy, ww, wh) {
self.audio.play_button_click();
self.dialogs.warning = true;
return Ok(());
}
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
let [_, ay, _, ah] = layout.area;
let mut action = None;
open.focus = None;
for (part, clipped) in layout.placed(open.scroll.amount) {
if clipped && !(cursor.1 >= ay && cursor.1 < ay + ah) {
continue;
}
match part {
Part::Field {
input,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
open.focus = Some(input);
if let Some(Some(edit)) = open.fields.get_mut(input) {
edit.focused = true;
edit.click(&self.gui.atlas, cursor.0, false, false);
}
}
Part::Check {
input,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
if let Some(InputValue::Bool(b)) = open.values.get_mut(input) {
*b = !*b;
}
action = Some(None);
}
Part::Button {
index,
rect: [x, y, w, h],
} if ui::hovered(cursor, x, y, w, h) => {
action = Some(Some(index));
}
_ => {}
}
}
let Some(action) = action else {
return Ok(());
};
self.audio.play_button_click();
let Some(index) = action else {
return Ok(());
};
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
Self::dialog_values(open);
let d = &open.dialog;
let click = d.buttons()[index]
.action
.as_ref()
.and_then(|a| a.click(&d.inputs, &open.values));
let after = d.after_action;
self.run_dialog_action(click, after)
}
/// The mouse wheel over a dialog: its body scrolls 10 a step.
pub(super) fn dialog_scroll(&mut self, delta: f32) {
let Some(layout) = self.dialog_layout() else {
return;
};
if let Some(open) = self.dialogs.open.as_mut() {
let [_, ay, _, ah] = layout.area;
open.scroll.wheel(delta, 10.0, ay, ay + ah, layout.content);
}
}
/// A key pressed on a dialog screen: Escape closes what allows it, Tab
/// moves between the text inputs, the rest goes to the focused one
/// (`shortcut`: the press as an edit shortcut; `text`: what it types).
pub(super) fn dialog_key(
&mut self,
key: KeyCode,
shortcut: Option<EditShortcut>,
text: Option<&str>,
) -> Result<()> {
let escape = key == KeyCode::Escape;
if self.dialogs.warning {
if escape {
self.dialogs.warning = false;
if !self.dialog_open() {
self.dialog_closed();
}
}
return Ok(());
}
if let Some(since) = self.dialogs.waiting {
// shouldCloseOnEsc: once Back works.
if escape && waiting_button((since.elapsed().as_millis() / 50) as u32).2 {
self.dialogs.waiting = None;
self.dialog_closed();
}
return Ok(());
}
let ctrl = self.modifiers.control_key() || self.modifiers.super_key();
let shift = self.modifiers.shift_key();
let Some(open) = self.dialogs.open.as_mut() else {
return Ok(());
};
if escape {
if !open.dialog.can_close_with_escape {
return Ok(());
}
// onClose: the cancel action, and the screen closes.
Self::dialog_values(open);
let d = &open.dialog;
let click = d.on_cancel().and_then(|a| a.click(&d.inputs, &open.values));
return self.run_dialog_action(click, AfterAction::Close);
}
if key == KeyCode::Tab {
let texts: Vec<usize> = (0..open.fields.len())
.filter(|&i| open.fields[i].is_some())
.collect();
if !texts.is_empty() {
let at = open.focus.and_then(|f| texts.iter().position(|&i| i == f));
let next = match at {
None if shift => texts.len() - 1,
None => 0,
Some(p) if shift => (p + texts.len() - 1) % texts.len(),
Some(p) => (p + 1) % texts.len(),
};
open.focus = Some(texts[next]);
}
return Ok(());
}
let Some(Some(edit)) = open.focus.and_then(|f| open.fields.get_mut(f)) else {
return Ok(());
};
if let Some(shortcut) = shortcut {
edit.shortcut(shortcut, &mut self.clipboard);
return Ok(());
}
if edit.key(key, ctrl, shift) {
return Ok(());
}
let typed: String = text
.unwrap_or_default()
.chars()
.filter(|c| !c.is_control())
.collect();
if !typed.is_empty() {
edit.insert_text(&typed);
}
Ok(())
}
/// `type TEXT` with a dialog open: into the focused text input, or the
/// first one.
pub(super) fn dialog_type(&mut self, text: &str) -> bool {
let Some(open) = self.dialogs.open.as_mut() else {
return false;
};
let focus = open
.focus
.or_else(|| open.fields.iter().position(Option::is_some));
let Some(Some(edit)) = focus.and_then(|f| open.fields.get_mut(f)) else {
return false;
};
open.focus = focus;
edit.insert_text(text);
true
}
/// What `state` reports: the open dialog and its values, or the waiting
/// and warning screens.
pub(super) fn dialog_status(&self) -> serde_json::Value {
let d = &self.dialogs;
let screen = if d.warning {
Some("warning")
} else if d.waiting.is_some() {
Some("waiting_for_response")
} else {
None
};
let open = d.open.as_ref().map(|open| {
let mut values = open.values.clone();
for (value, field) in values.iter_mut().zip(&open.fields) {
if let Some(f) = field {
*value = InputValue::Text(f.value.clone());
}
}
open.dialog.json(&values)
});
serde_json::json!({ "open": open, "screen": screen })
}
}
@@ -90,6 +90,10 @@ enum Target {
impl Game<'_> {
/// Run every case of `spec` ("CASES,OUTPUT") and write the results.
pub(super) fn dispense_fixture(&mut self, spec: &str) -> Result<()> {
assert!(
!self.options.execution_role.is_client(),
"fixture requires a server Game"
);
let (input, output) = spec
.split_once(',')
.ok_or("HORIZON_DISPENSE_FIXTURE=CASES,OUTPUT")?;
+24 -15
View File
@@ -336,6 +336,12 @@ enum StrafeRequest {
/// Anything else: the player nearest the crystal.
Nearest(Vec3),
}
/// Whether `EndCrystal.hurtServer` creates a blast before notifying the fight.
#[derive(Clone, Copy, PartialEq)]
enum CrystalDamage {
Direct,
Explosion,
}
/// What `EnderDragon.hurt` made of a hit.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Hurt {
@@ -867,27 +873,29 @@ impl Game<'_> {
}
}
}
/// A crystal took damage: `EndCrystal.hurtServer` blows it up (power 6).
fn destroy_crystal(&mut self, index: usize, by: Option<FightWho>) {
/// `EndCrystal.hurtServer`: remove it, blast only for non-explosion damage,
/// then notify the dragon fight even when no blast was created.
fn destroy_crystal(&mut self, index: usize, by: Option<FightWho>, damage: CrystalDamage) {
if index >= self.crystals.len() || self.crystals[index].invulnerable {
return;
}
let c = self.crystals.remove(index);
if self.fight.respawn.is_some()
// Read before the blast, which can take other respawn crystals.
let respawn_crystal = self.fight.respawn.is_some()
&& self
.fight
.respawn_crystals
.iter()
.any(|p| p.distance_squared(c.position) < 0.01)
{
.any(|p| p.distance_squared(c.position) < 0.01);
if damage == CrystalDamage::Direct {
let at = [c.position.x, c.position.y, c.position.z];
let _ =
self.server_explode(at, 6.0, super::explosion::BlockInteraction::Destroy, false);
}
if respawn_crystal {
self.abort_respawn();
return;
}
let at = [c.position.x, c.position.y, c.position.z];
let _ = self.server_explode(at, 6.0, super::explosion::BlockInteraction::Destroy, false);
// EnderDragonFight.onCrystalDestroyed.
self.count_crystals();
if let Some(d) = self.dragon.as_mut() {
@@ -962,7 +970,7 @@ impl Game<'_> {
return Hurt::Refused;
}
let by = by_player.then(|| self.acting_player());
self.destroy_crystal(index, by);
self.destroy_crystal(index, by, CrystalDamage::Direct);
Hurt::Landed { full: true }
} else if id >= SPECIAL {
self.hurt_dragon((id - SPECIAL) as usize, amount, by_player, arrow)
@@ -1963,9 +1971,10 @@ impl Game<'_> {
self.spawn_orbs([p.x, p.y, p.z], (xp as f32 * 0.08) as u32);
}
if t == 1 {
// Level event 1028: the death roar, heard everywhere.
self.audio
.play("minecraft:entity.ender_dragon.death", None, 5.0, 1.0);
// EnderDragon.tickDeath: global level event 1028, the death
// roar, heard everywhere.
let at = [p.x, p.y, p.z].map(|v| v.floor() as i32);
self.global_level_event(1028, at, 0);
}
if let Some(d) = self.dragon.as_mut() {
d.position.y += 0.1;
@@ -2634,8 +2643,8 @@ impl Crystal {
}
}
impl Game<'_> {
/// `ServerExplosion.hurtEntities` on the end crystals (each in reach
/// blows up in turn) and the dragon (explosions always hurt dragons).
/// `ServerExplosion.hurtEntities`: crystals in reach are removed without
/// another blast; explosions always hurt dragons.
pub(super) fn explosion_hits_special(&mut self, center: [f64; 3], radius: f32) {
let diameter = f64::from(radius * 2.0);
let in_reach = |p: Vec3| {
@@ -2651,9 +2660,9 @@ impl Game<'_> {
.map(|c| c.position)
.collect();
for at in crystals {
// One blowing up may already have taken the next.
// Look up the current index after each removal.
if let Some(i) = self.crystals.iter().position(|c| c.position == at) {
self.destroy_crystal(i, None);
self.destroy_crystal(i, None, CrystalDamage::Explosion);
}
}
let Some(d) = self.dragon.as_ref() else {
+39 -4
View File
@@ -4,7 +4,12 @@
//! inactive until the dragon dies.
use super::{Dim, Game};
use horizon_client::{
Result, environment::Environment, items::ItemStack, mesher::Vertex, motion::PlayerMotion,
Result,
environment::Environment,
items::ItemStack,
mesher::Vertex,
motion::PlayerMotion,
particles::{ParticleOptions, ParticleType},
vanillagen::VanillaTerrain,
};
use horizon_core::{
@@ -311,9 +316,10 @@ impl Game<'_> {
)?;
}
}
// Global LevelEvent 1038: END_PORTAL_SPAWN.
self.audio
.play("minecraft:block.end_portal.spawn", None, 1.0, 1.0);
// EnderEyeItem.useOn: global level event 1038 (END_PORTAL_SPAWN),
// heard by every player (vanilla places it at the frame's corner
// + (1, 0, 1); only its direction matters).
self.global_level_event(1038, c, 0);
}
Ok(true)
}
@@ -1122,6 +1128,35 @@ impl Game<'_> {
self.end.eyes = eyes;
}
/// `EyeOfEnder.tick` on a client: behind each eye (a quarter of its last
/// move back), four bubbles in water, else a portal particle.
pub(super) fn eye_particles(&mut self) {
for i in 0..self.end.eyes.len() {
let e = &self.end.eyes[i];
let movement = (e.position - e.previous).to_array();
let origin = (e.position - (e.position - e.previous) * 0.25).to_array();
let block = origin.map(|v| v.floor() as i32);
let water = self
.res
.facts()
.get(self.world.block(block[0], block[1], block[2]))
.fluid
== horizon_client::blocks::Fluid::Water;
if water {
let bubble = ParticleOptions::simple(ParticleType::Bubble);
for _ in 0..4 {
self.particles.add(&bubble, origin, movement);
}
} else {
let r = self.particles.random();
let x = origin[0] + r.next_double() * 0.6 - 0.3;
let z = origin[2] + r.next_double() * 0.6 - 0.3;
let portal = ParticleOptions::simple(ParticleType::Portal);
self.particles
.add(&portal, [x, origin[1] - 0.5, z], movement);
}
}
}
/// ThrownItemRenderer: the ender eye item facing the camera.
fn eye_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let Some(r) = self.gui.atlas.sprites.get("item/ender_eye").copied() else {
@@ -15,6 +15,11 @@ fn opaque(facts: &StateFacts) -> bool {
impl Game<'_> {
pub(super) fn prepare_entity_culling(&mut self, camera: glam::DVec3) {
// Spans tell the pack's passes which entities are hidden; without them, nothing changes.
self.pack_shadow_casters = match (&self.renderer, &self.pack_ids) {
(Some(r), Some(_)) => r.pack_shadow_casters(),
_ => (false, false),
};
let at = camera.to_array().map(|v| v.floor() as i32);
self.entity_culler = (self.settings.horizon.entity_culling
// Packs can replace an opaque block's model or texture.
@@ -28,24 +33,29 @@ impl Game<'_> {
/// Use complete generated geometry so equipment, animation and custom
/// models cannot stick out of an assumed collision-sized culling box.
pub(super) fn cull_entity_vertices(&self, vertices: &mut Vec<Vertex>, start: usize) {
if let Some(culler) = &self.entity_culler {
culler.cull_vertices(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
let Some(culler) = &self.entity_culler else {
return;
};
let hidden = culler.hidden(vertices, start, |pos| {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !opaque(self.res.facts().get(state)) {
return false;
}
let Some(y) = pos[1].checked_sub(MIN_Y) else {
return false;
};
let section = (pos[0] >> 4, y.div_euclid(16), pos[2] >> 4);
// Newly edited or not-yet-uploaded terrain is not an occluder.
self.renderer
.as_ref()
.is_some_and(|r| r.has_section(section))
&& !self.world.dirty_sections.contains(&section)
&& !self.streaming.is_meshing(section)
&& !self.pending_uploads.iter().any(|(key, _)| *key == section)
});
// A shader pack's shadow pass still draws what the camera cannot see.
if hidden && !(self.pack_shadow_casters.0 && self.hide_spans_from(start, vertices.len())) {
vertices.truncate(start);
}
}
}
+18 -2
View File
@@ -70,7 +70,8 @@ impl Game<'_> {
_ => return,
};
self.extras.mouse[i] = pressed;
if pressed && self.settings.extras.keystrokes {
// Mods read the clicks too (`input.clicks-per-second`).
if pressed && (self.settings.extras.keystrokes || self.mods.running()) {
let now = self.extras_now();
self.extras.cps[i].click(now);
}
@@ -87,13 +88,28 @@ impl Game<'_> {
self.extras.mouse = [false; 2];
}
self.update_minimap();
if self.settings.extras.fps {
// Mods read the counter too (`render.frame-stats`).
if self.settings.extras.fps || self.mods.running() {
let now = self.extras_now();
self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0);
} else {
self.extras.fps.clear();
}
}
/// The frame counter for mods: fps, min, 1% low.
#[cfg(feature = "mods")]
pub(super) fn frame_reading(&self) -> (u32, u32, u32) {
let r = self.extras.fps.reading();
(r.fps, r.min, r.low)
}
/// Attack and use clicks in the last second, and whether each is held.
#[cfg(feature = "mods")]
pub(super) fn mouse_reading(&mut self) -> ((u32, u32), [bool; 2]) {
let now = self.extras_now();
let [l, r] = &mut self.extras.cps;
let cps = (l.per_second(now) as u32, r.per_second(now) as u32);
(cps, self.extras.mouse)
}
/// Auto-reconnect: a connection to `address` as `name` starts.
pub(super) fn extras_connecting(&mut self, address: &str, name: &str) {
self.extras.reconnect.connecting(address, name);
+38 -5
View File
@@ -25,9 +25,15 @@ pub(super) struct Rocket {
pub(super) velocity: Vec3,
life: i32,
lifetime: i32,
explosions: Vec<FireworkExplosion>,
pub(super) explosions: Vec<FireworkExplosion>,
/// Boosting the player (attachedToEntity).
pub(super) attached: bool,
/// On a server, the player it boosts when not this game's own: a guest's
/// connection.
pub(super) guest: Option<u32>,
/// `DATA_ATTACHED_TO_TARGET`: the server entity the rocket follows;
/// boosting happens when it is the local player.
pub(super) attached_to: Option<u32>,
/// `DATA_SHOT_AT_ANGLE` (dispensers): constant velocity, exploding on
/// the first block it hits.
pub(super) angled: bool,
@@ -48,6 +54,8 @@ impl Rocket {
lifetime: i32::MAX,
explosions,
attached: false,
guest: None,
attached_to: None,
angled: false,
item,
}
@@ -63,7 +71,7 @@ impl Rocket {
(self.position, self.velocity)
}
}
fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
pub(super) fn fireworks_of(stack: &ItemStack) -> (u8, Vec<FireworkExplosion>) {
// The item's default component: flight 1, no explosions.
stack
.data()
@@ -89,6 +97,8 @@ impl Game<'_> {
lifetime,
explosions,
attached,
guest: None,
attached_to: None,
angled: false,
item: stack.clone(),
}
@@ -127,7 +137,8 @@ impl Game<'_> {
return false;
}
let at = self.player.as_ref().map_or(Vec3::ZERO, |p| p.position);
let rocket = self.new_rocket(at, stack, true);
let mut rocket = self.new_rocket(at, stack, true);
rocket.guest = self.lan_acting;
self.rockets.push(rocket);
if !self.creative {
self.consume_held();
@@ -140,7 +151,18 @@ impl Game<'_> {
while i < self.rockets.len() {
let mut r = self.rockets.remove(i);
r.previous = r.position;
if r.attached {
if r.attached
&& let Some(conn) = r.guest
{
// A guest's rocket follows them; their own client boosts them.
let guest = self
.lan
.as_ref()
.and_then(|host| host.hub.guests.iter().find(|g| g.conn == conn));
if let Some(g) = guest {
r.position = Vec3::new(g.position[0], g.position[1], g.position[2]);
}
} else if r.attached {
if let Some(p) = self.player.as_mut() {
if p.fall_flying {
let look = view_vector(self.yaw, self.pitch);
@@ -229,8 +251,19 @@ impl Game<'_> {
let at = [r.position.x, r.position.y, r.position.z];
if !r.explosions.is_empty() {
let damage = 5.0 + r.explosions.len() as f32 * 2.0;
// The player it boosts takes the full damage, a guest as well.
if r.attached {
self.hurt_player_by("minecraft:fireworks", damage);
match r.guest {
None => self.hurt_player_by("minecraft:fireworks", damage),
Some(conn) => {
if let Some(mut host) = self.lan.take() {
self.as_guest(&mut host, conn, |g| {
g.hurt_player_by("minecraft:fireworks", damage);
});
self.lan = Some(host);
}
}
}
}
let from = r.position;
let hits: Vec<(u32, f32)> = {
@@ -45,7 +45,8 @@ pub(super) struct RulesScreen {
initial: GameRules,
/// IntegerRuleEntry's boxes, by rule.
numbers: Vec<(&'static str, EditBox)>,
scroll: f32,
/// RuleList's scrolling: the wheel and the held scrollbar.
scroll: ui::Scroll,
/// ConfirmScreen "Game Rule Changes" in its place.
confirm: bool,
}
@@ -120,7 +121,7 @@ impl RulesScreen {
values: rules.clone(),
initial: rules.clone(),
numbers,
scroll: 0.0,
scroll: ui::Scroll::default(),
confirm: false,
}
}
@@ -156,12 +157,17 @@ impl RulesScreen {
})
.collect()
}
fn max_scroll(rows: usize, h: f32) -> f32 {
(ROW * rows as f32 + 4.0 - (h - HEADER - FOOTER)).max(0.0)
}
/// Entry `i`'s top: 2 under the list's top, less the scroll.
fn row_top(&self, i: usize) -> f32 {
HEADER + 2.0 - self.scroll.trunc() + ROW * i as f32
HEADER + 2.0 - self.scroll.amount.trunc() + ROW * i as f32
}
/// The list's scrollbar column (AbstractSelectionList: 6 pixels right of
/// the entries) and the pixels it scrolls.
fn bar(w: f32) -> f32 {
row_left(w) + ROW_WIDTH + 6.0 + 2.0
}
fn content(&self) -> f32 {
ROW * self.rows().len() as f32 + 4.0
}
/// getEntryAtPosition: the row under the pointer, inside the list.
fn hovered(&self, rows: usize, (x, y): (f32, f32), (w, h): (f32, f32)) -> Option<usize> {
@@ -212,10 +218,28 @@ impl RulesScreen {
/// The mouse wheel (AbstractSelectionList: half an entry a step).
pub(super) fn wheel(&mut self, delta: f32, h: f32) {
if !self.confirm {
let max = Self::max_scroll(self.rows().len(), h);
self.scroll = (self.scroll - delta * ROW / 2.0).clamp(0.0, max);
let content = self.content();
self.scroll
.wheel(delta, ROW / 2.0, HEADER, h - FOOTER, content);
}
}
/// A press on the scrollbar holds it (AbstractSelectionList.updateScrolling).
pub(super) fn press_scrollbar(&mut self, cursor: (f32, f32), (w, h): (f32, f32)) -> bool {
let content = self.content();
self.scroll
.press(cursor, Self::bar(w), HEADER, h - FOOTER, content)
}
/// The pointer moved while the scrollbar is held.
pub(super) fn drag(&mut self, y: f32, h: f32) {
if self.scroll.held() {
let content = self.content();
self.scroll.drag(y, HEADER, h - FOOTER, content);
}
}
/// The button came up: the scrollbar lets go.
pub(super) fn release(&mut self) {
self.scroll.release();
}
fn focused(&mut self) -> Option<(Option<&'static str>, &mut EditBox)> {
if self.search.focused {
return Some((None, &mut self.search));
@@ -229,7 +253,7 @@ impl RulesScreen {
/// number sets its rule when valid (IntegerRuleEntry's responder).
fn edited(&mut self, rule: Option<&'static str>) {
let Some(name) = rule else {
self.scroll = 0.0;
self.scroll.amount = 0.0;
return;
};
let Some(r) = gamerules::rule(name) else {
@@ -286,6 +310,11 @@ impl RulesScreen {
if on(cx, cy, 150.0, 20.0) {
return self.close();
}
// A press on the scrollbar holds it and clicks nothing else.
if self.press_scrollbar(cursor, size) {
self.unfocus();
return None;
}
// A click moves the focus to the widget under it.
let (sx, sy) = search_at(w);
if on(sx, sy, SEARCH_WIDTH, 15.0) {
@@ -360,7 +389,8 @@ impl RulesScreen {
return;
}
let rows = self.rows();
self.scroll = self.scroll.clamp(0.0, Self::max_scroll(rows.len(), h));
let content = ROW * rows.len() as f32 + 4.0;
self.scroll.clamp(HEADER, h - FOOTER, content);
// RuleList: the in-world list background, its entries clipped to it,
// then the separators and scrollbar.
ui::list_background(batch, atlas, HEADER, h - FOOTER, true);
@@ -421,16 +451,14 @@ impl RulesScreen {
}
batch.clip_since(first, 0.0, HEADER, w, h - FOOTER);
ui::separators(batch, atlas, HEADER, h - FOOTER, true);
let content = ROW * rows.len() as f32 + 4.0;
let bar_x = left + ROW_WIDTH + 6.0 + 2.0;
ui::scrollbar(
batch,
atlas,
bar_x,
Self::bar(w),
HEADER,
h - FOOTER,
content,
self.scroll.trunc(),
self.scroll.amount.trunc(),
);
// The header: the title centred over the search box.
let title = Text::translate("editGamerule.title", &[]);
@@ -536,6 +564,29 @@ mod tests {
);
}
/// AbstractScrollArea: a press on the bar holds it, a drag moves the
/// list (to the ends past them), a release lets go.
#[test]
fn the_scroll_bar_can_be_held_dragged_and_let_go() {
let mut s = RulesScreen::new(&GameRules::default());
let (w, h) = (427.0, 240.0);
let (top, bottom, content) = (HEADER, h - FOOTER, s.content());
assert!(
content > bottom - top,
"the rules overflow a 240-high screen"
);
let bar = RulesScreen::bar(w);
assert!(!s.press_scrollbar((bar - 4.0, top + 5.0), (w, h)));
assert!(s.press_scrollbar((bar + 3.0, top + 5.0), (w, h)));
s.drag(top + 40.0, h);
assert!(s.scroll.amount > 0.0);
s.drag(bottom + 10.0, h);
assert_eq!(s.scroll.amount, content - (bottom - top));
s.release();
s.drag(top, h);
assert_eq!(s.scroll.amount, content - (bottom - top));
}
#[test]
fn edits_change_rules_and_bad_numbers_hold_done() {
let mut s = RulesScreen::new(&GameRules::default());
+54 -3
View File
@@ -143,7 +143,7 @@ pub(super) struct Serving {
flags: Arc<Flags>,
tasks: Receiver<Task>,
/// The window's profile.
owner: u128,
pub(super) owner: u128,
/// Open to LAN or closed from inside a player's command, while the hub
/// is out of its place: applied after the tick.
pending: Option<Publish>,
@@ -357,6 +357,16 @@ impl Game<'_> {
});
let _ = ready.send(Ok((pipe, self.level.name.clone())));
self.settle_spawn()?;
if let (Some(script), Some(output)) = (
std::env::var_os("HORIZON_COMMAND_SCRIPT"),
std::env::var_os("HORIZON_COMMAND_OUTPUT"),
) {
// The script owns the clock: connection setup and terrain loading
// cannot add wall-clock-dependent world ticks to oracle output.
let result = self.run_command_harness(script.as_ref(), output.as_ref());
let stopped = self.stop_integrated();
return result.and(stopped);
}
let mut next = Instant::now();
while !flags.stop.load(Ordering::Relaxed) {
self.run_tasks();
@@ -698,6 +708,48 @@ fn serve(
tasks: Receiver<Task>,
ready: &Sender<Ready>,
) -> Result<()> {
let mut server = server_game(res, pack, options, settings)?;
server.run_integrated(launch, flags, tasks, ready)
}
/// Component oracles supply their own synthetic levels and entity phases.
/// They still execute on a server Game, never the client's world.
pub(super) enum ComponentHarness {
Dispenser(String),
Sculk(String),
}
impl Game<'_> {
pub(super) fn run_component_harness(&self, fixture: ComponentHarness) -> Result<()> {
let (res, pack, settings) = (self.res.clone(), self.pack.clone(), self.settings.clone());
let mut options = self.options.clone();
options.execution_role = ExecutionRole::IntegratedServer;
options.dedicated = Some(Vec::new());
options.server_thread = false;
let result = std::thread::Builder::new()
.name("Server thread".into())
.spawn(move || {
let run = || -> Result<()> {
let mut server = server_game(&res, pack, options, settings)?;
match fixture {
ComponentHarness::Dispenser(spec) => server.dispense_fixture(&spec),
ComponentHarness::Sculk(spec) => server.sculk_fixture(&spec),
}
};
run().map_err(|e| e.to_string())
})?
.join()
.map_err(|_| "the component harness server panicked")?;
result.map_err(Into::into)
}
}
fn server_game(
res: &Arc<Resources>,
pack: PackResources,
options: Options,
settings: Settings,
) -> Result<Game<'_>> {
// It draws nothing: only the font, which books and chat measure with.
let atlas = HudAtlas::fonts(&options.resources)?;
let gui = UiResources {
@@ -708,8 +760,7 @@ fn serve(
}),
};
let audio = Audio::silent(&options.resources);
let mut server = Game::new(res, pack, gui, options, settings, audio, None)?;
server.run_integrated(launch, flags, tasks, ready)
Game::new(res, pack, gui, options, settings, audio, None)
}
#[cfg(test)]
+29 -3
View File
@@ -162,6 +162,13 @@ fn mob_meta(
meta.push((3, serializer::BOOLEAN, Value::Bool(true)));
}
}
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the off
// hand 2 (a skeleton draws its bow, a witch raises her potion).
let using = i8::from(m.extra.using_item > 0) | i8::from(m.extra.using_off_hand) << 1;
if using != 0 {
meta.push((8, serializer::BYTE, Value::Byte(using)));
}
defaults.push((8, serializer::BYTE, Value::Byte(0)));
// LivingEntity.DATA_HEALTH_ID: defined as 1, then set to the max health.
let health = m.health.max(0.0);
if health != 1.0 {
@@ -293,6 +300,21 @@ fn mob_meta(
meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
}
}
// Pillager.IS_CHARGING_CROSSBOW: the charge pose and the held
// item's loading animation.
"minecraft:pillager" => {
if e.flag {
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
}
defaults.push((17, serializer::BOOLEAN, Value::Bool(false)));
}
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
"minecraft:evoker" | "minecraft:illusioner" => {
if e.variant2 != 0 {
meta.push((17, serializer::BYTE, Value::Byte(e.variant2 as i8)));
}
defaults.push((17, serializer::BYTE, Value::Byte(0)));
}
// Enderman.DATA_CARRY_STATE.
"minecraft:enderman" => {
if let Some(state) = e.carried {
@@ -983,6 +1005,7 @@ impl Game<'_> {
self.save_guest(&host, &guest);
host.models.remove(&guest.conn);
host.play.remove(&guest.conn);
self.guest_combat.remove(&guest.conn);
if self.options.dedicated.is_some() && guest.placed {
super::dedicated::log(
"INFO",
@@ -1113,9 +1136,9 @@ impl Game<'_> {
for e in events {
if let horizon_world::level::LevelEvent::LevelEvent { id, pos, data } = e {
// The acting guest does not predict the egg's teleport
// particles, nor bone meal's growth (BoneMealItem.useOn's
// levelEvent names no player).
let except = if matches!(*id, 2015 | 1505) {
// particles, bone meal's growth, or anvil result sounds
// (these levelEvent calls name no excluded player).
let except = if matches!(*id, 2015 | 1505 | 1029 | 1030) {
None
} else {
self.lan_acting
@@ -1154,6 +1177,9 @@ impl Game<'_> {
for (id, event, at) in std::mem::take(&mut self.lan_entity_events) {
host.hub.entity_event(id, event, at);
}
for (kind, pos, data) in std::mem::take(&mut self.lan_global_events) {
host.hub.global_level_event(kind, pos, data);
}
self.lan_broadcast_effects(host);
if host.hub.guests.is_empty() {
host.mob_state.clear();
+150 -53
View File
@@ -38,6 +38,8 @@ pub(super) struct GuestPlay {
use_delay: u32,
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
pub(super) shield_cooldown: u32,
/// The guest's `Player.getCooldowns()` (`Game::cooldowns` for its turn).
pub(super) cooldowns: horizon_client::cooldowns::Cooldowns,
attack_ticks: u32,
/// The main hand's item at the guest's last tick (`Game::attack_item`).
attack_item: Option<std::sync::Arc<str>>,
@@ -84,6 +86,7 @@ pub(super) struct GuestPlay {
equipped: Option<Vec<Option<ItemStack>>>,
/// The guest's cast fishing hook (`Player.fishing`).
pub(super) hook: Option<super::fishing::Hook>,
sculk: super::sculk::PlayerEvents,
}
/// A guest's command waiting for the hub (`LanHost::commands`).
@@ -125,6 +128,8 @@ pub(super) struct GuestSwap {
using: Option<(usize, u32)>,
use_delay: u32,
pub(super) shield_cooldown: u32,
/// The guest's item cooldowns (`Game::cooldowns` for its turn).
cooldowns: horizon_client::cooldowns::Cooldowns,
attack_ticks: u32,
attack_item: Option<std::sync::Arc<str>>,
swing: horizon_client::first_person::SwingState,
@@ -144,6 +149,8 @@ pub(super) struct GuestSwap {
adv_loaded: bool,
last_inventory: u64,
death_cause: Option<String>,
/// The guest's own damage record, in place while they act.
combat: super::combat::CombatTracker,
/// The guest whose turn this one nests in, if any.
acting: (Option<u32>, Option<String>, Option<u128>),
/// The packets queued for that guest.
@@ -250,6 +257,7 @@ impl Game<'_> {
if fresh {
// A new body (joined, respawned, changed level): nothing on it yet.
play.equipped = None;
play.sculk = Default::default();
}
let g = &mut host.hub.guests[i];
// The guest's body.
@@ -257,6 +265,15 @@ impl Game<'_> {
host.play.insert(conn, play);
return None;
};
self.sculk.swap_player(&mut play.sculk);
// The guest's own CombatTracker: damage to them is not the host's.
// A new body starts with no record of the last one.
let guest_combat = if fresh {
Default::default()
} else {
self.guest_combat.remove(&conn).unwrap_or_default()
};
let host_combat = std::mem::replace(&mut self.combat, guest_combat);
self.potions.swap_player(&mut g.effects, &mut play.potions);
motion.position = Vec3::new(g.position[0], g.position[1], g.position[2]);
motion.ground.on_ground = g.on_ground;
@@ -265,6 +282,8 @@ impl Game<'_> {
motion.sprinting = g.sprinting;
motion.may_fly = g.creative() || g.game_mode == SPECTATOR;
motion.flying = g.flying;
// FireworkRocketItem.use boosts only a gliding player.
motion.fall_flying = g.fall_flying;
motion.invulnerable = motion.may_fly;
let _ = motion.set_health(g.health, false);
motion.health.food.food = g.food;
@@ -316,6 +335,7 @@ impl Game<'_> {
let using = std::mem::replace(&mut self.using, play.using.take());
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
let cooldowns = std::mem::replace(&mut self.cooldowns, std::mem::take(&mut play.cooldowns));
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
let swing = std::mem::replace(&mut self.swing, play.swing);
@@ -400,6 +420,7 @@ impl Game<'_> {
using,
use_delay,
shield_cooldown,
cooldowns,
attack_ticks,
attack_item,
swing,
@@ -421,6 +442,7 @@ impl Game<'_> {
swings,
projectiles,
modifiers,
combat: host_combat,
})
}
@@ -456,6 +478,7 @@ impl Game<'_> {
using,
use_delay,
shield_cooldown,
cooldowns,
attack_ticks,
attack_item,
swing,
@@ -472,12 +495,17 @@ impl Game<'_> {
adv_loaded,
last_inventory,
death_cause,
combat,
acting,
packets,
swings,
projectiles,
modifiers,
} = swap;
self.sculk.swap_player(&mut play.sculk);
// The guest's damage record back into their slot, the host's in place.
let guest_combat = std::mem::replace(&mut self.combat, combat);
self.guest_combat.insert(conn, guest_combat);
play.modifiers = std::mem::replace(&mut self.applied_modifiers, modifiers);
// What the guest shot is theirs (Projectile.setOwner).
for p in self.creatures.projectiles.iter_mut().skip(projectiles) {
@@ -491,6 +519,16 @@ impl Game<'_> {
for packet in std::mem::replace(&mut self.guest_packets, packets) {
host.hub.send_to(conn, &packet);
}
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration,
}),
);
}
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
// An ender chest the guest opened: the menu shows their inventory
@@ -520,6 +558,7 @@ impl Game<'_> {
play.using = std::mem::replace(&mut self.using, using);
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
play.cooldowns = std::mem::replace(&mut self.cooldowns, cooldowns);
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
play.swing = std::mem::replace(&mut self.swing, swing);
@@ -1261,31 +1300,30 @@ impl Game<'_> {
host: &LanHost,
stack: &Option<horizon_protocol::item::Stack>,
) -> Option<ItemStack> {
use horizon_protocol::item::{Component, component};
let s = stack.as_ref()?;
let name = host
.hub
.item_name(s.item)
.unwrap_or_else(|| "minecraft:air".into());
let mut out = ItemStack::new(&name, s.count.max(1) as u32);
out.damage = s.damage().max(0) as u32;
if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) {
for (id, level) in list {
if let Some(e) = host.hub.enchantment_name(*id) {
out.enchant(&e, *level as u32);
}
}
}
if let Some(Component::Potion {
potion: Some(id), ..
}) = s.component(component::POTION_CONTENTS)
&& let Some(potion) = host.hub.registry_name("minecraft:potion", *id)
{
out = out.with_potion(potion);
}
let mut out = host.hub.stack_from_network(s);
out.count = out.count.max(1);
Some(out)
}
/// `LivingEntity.tickDeath`: 20 ticks after dying the player is removed,
/// and `Player.remove`'s `inventoryMenu.removed` drops what the cursor
/// held (`dropOrPlaceInInventory` for a removed player). Respawning
/// sooner removes it too.
fn guest_tick_death(&mut self, host: &mut LanHost, gi: usize) {
let g = &mut host.hub.guests[gi];
g.death_time += 1;
if g.death_time >= 20 {
self.guest_drop_carried(host, gi);
}
}
fn guest_drop_carried(&mut self, host: &mut LanHost, gi: usize) {
if let Some(c) = host.hub.guests[gi].carried.take() {
self.drop_guest_items(host, gi, vec![c]);
}
}
/// `AbstractContainerMenu.removed`: what a closing player held on the
/// cursor goes back into their inventory (`placeItemBackInInventory`,
/// dropped only if it doesn't fit), and their client's cursor empties
@@ -1625,6 +1663,8 @@ impl Game<'_> {
if !host.hub.guests[i].dead {
return;
}
// PlayerList.respawn removes the dead player (Player.remove).
self.guest_drop_carried(host, i);
// PlayerList.respawn: a server's player comes back in its respawn
// point's level: the Overworld, where the world spawn and beds are,
// or another one's anchor or forced point, which its block resolves
@@ -1665,6 +1705,7 @@ impl Game<'_> {
}
let g = &mut host.hub.guests[i];
g.dead = false;
g.death_time = 0;
g.health = 20.0;
g.food = 20;
g.saturation = 5.0;
@@ -1701,6 +1742,11 @@ impl Game<'_> {
border: &self.border,
};
host.hub.respawn(i, spawn, &ctx);
// ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's
// respawned player only watches.
if self.level.hardcore {
host.hub.set_game_mode(conn, SPECTATOR);
}
if let Some(config) = elsewhere {
self.respawn_trip(conn, config);
}
@@ -1748,13 +1794,28 @@ impl Game<'_> {
continue;
};
self.guest_sleep_tick(host, gi);
if host.hub.guests[gi].dead || self.on_server_trip(conn) {
if host.hub.guests[gi].dead {
self.guest_tick_death(host, gi);
continue;
}
if self.on_server_trip(conn) {
continue;
}
let play = host.play.entry(conn).or_default();
// Player.tick's ItemCooldowns.tick, once a tick for each player
// (the shield an axe disabled).
// (the shield an axe disabled, a thrown pearl).
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
// the guest (a duration of 0 removes it).
for group in play.cooldowns.tick() {
host.hub.send_to(
conn,
&C::Cooldown(play::Cooldown {
group: group.to_string(),
duration: 0,
}),
);
}
let digging = play.digging;
let using = play.using.is_some();
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
@@ -1780,14 +1841,13 @@ impl Game<'_> {
g.use_delay -= 1;
}
});
// ServerPlayerGameMode.handleBlockBreakAction: a creative
// player's START breaks the block once (destroyAndAck) and
// leaves nothing being destroyed; its client sends no STOP.
// Kept, the dig broke whatever was put there next, every
// destroy delay, for as long as the player broke nothing else.
// ServerPlayerGameMode.handleBlockBreakAction: creative and
// instant survival STARTs finish without a STOP from the client.
// tick_mining clears mining on completion; forget the START too,
// so a flower or crop planted here later is not broken again.
if digging.is_some()
&& host.hub.guests[gi].creative()
&& let Some(play) = host.play.get_mut(&conn)
&& (host.hub.guests[gi].creative() || play.mining.is_none())
{
play.digging = None;
}
@@ -1846,31 +1906,34 @@ impl Game<'_> {
let drops = (g.game_mode != SPECTATOR)
.then(|| [at[0], at[1] + g.eye_height() - 0.3, at[2]]);
let cause = host.play.get_mut(&conn).and_then(|p| p.death_cause.take());
let message = match cause {
// ServerPlayer.die: the death message, to everyone unless
// the player's team hides it.
Some(key) if self.ui.rules.bool("show_death_messages") => {
let text = horizon_client::text::Text::translate(
&key,
&[self.player_text(&name, uuid)],
);
let message = horizon_client::lan::data::component_nbt(&text.component());
let team = self.score.board.players_team(&name);
if horizon_client::scoreboard::own_death_message_shown(team) {
host.hub.system_message(message.clone());
if self.options.dedicated.is_some() {
super::dedicated::log(
"INFO",
&format!("System chat: {}", text.plain()),
);
} else if self.player.is_some() {
self.system_message(text);
}
// ServerPlayer.die: with showDeathMessages, the message goes to
// the dying player's death screen and to everyone the team lets
// see it; without it, the death screen gets an empty one.
let message = if self.ui.rules.bool("show_death_messages") {
let me = self.player_text(&name, uuid);
let text = match cause {
Some(key) => horizon_client::text::Text::translate(&key, &[me]),
None if at[1] < f64::from(horizon_client::chunk::MIN_Y - 64) => {
horizon_client::text::Text::translate("death.attack.outOfWorld", &[me])
}
None => self.guest_death_message(conn, me),
};
let message = horizon_client::lan::data::component_nbt(&text.component());
let team = self.score.board.players_team(&name);
if horizon_client::scoreboard::own_death_message_shown(team) {
host.hub.system_message(message.clone());
if self.options.dedicated.is_some() {
super::dedicated::log(
"INFO",
&format!("System chat: {}", text.plain()),
);
} else if self.player.is_some() {
self.system_message(text);
}
message
}
Some(_) => literal(""),
None => literal(&format!("{name} died")),
message
} else {
literal("")
};
host.hub.send_to(
conn,
@@ -1886,6 +1949,21 @@ impl Game<'_> {
}
}
/// `ServerPlayer.die`'s message from a guest's own `CombatTracker`, which
/// sits in `guest_combat` between turns.
fn guest_death_message(
&mut self,
conn: u32,
me: horizon_client::text::Text,
) -> horizon_client::text::Text {
let mut tracker = self.guest_combat.remove(&conn).unwrap_or_default();
std::mem::swap(&mut self.combat, &mut tracker);
let text = self.combat_death_message_for(me);
std::mem::swap(&mut self.combat, &mut tracker);
self.guest_combat.insert(conn, tracker);
text
}
/// `Player.tick`'s sleep counter, and `LivingEntity.tick`'s wake-up of a
/// sleeper who died or whose bed is gone.
fn guest_sleep_tick(&mut self, host: &mut LanHost, gi: usize) {
@@ -1996,6 +2074,7 @@ impl Game<'_> {
let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health;
let freeze_immune = game.wears_freeze_immune();
let Some(player) = game.player.as_mut() else {
return (Vec::new(), None);
};
@@ -2059,11 +2138,24 @@ impl Game<'_> {
// Entity.applyEffectsFromBlocks along those moves: magma, cactus,
// lit campfires and grown sweet berry bushes hurt (#1305).
w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start);
let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall);
let mut events = std::mem::take(&mut w.player.events);
// LayeredCauldronBlock.handleEntityOnFireInside along those moves.
for event in &events {
if let MotionEvent::CauldronExtinguish { pos } = event {
game.cauldron_extinguish(*pos);
}
}
// WitherRoseBlock.entityInside along those moves.
for event in &events {
if matches!(event, MotionEvent::InsideWitherRose) {
game.wither_rose_contact();
}
}
// ServerGamePacketListenerImpl.handleMovePlayer:
// Player.checkMovementStatistics for each move.
for d in travelled {
@@ -2087,14 +2179,19 @@ impl Game<'_> {
resources: game.motion,
}
.server_travel();
// Landing damage from this travel reaches the tracker too.
events.append(&mut player.events);
// A hurt since the last tick marked the velocity (Entity.markHurt):
// ServerEntity.sendChanges sends it as it is after this travel.
let marked = std::mem::take(&mut player.health.sync_velocity);
(events, marked.then_some(player.velocity))
let velocity = marked.then_some(player.velocity);
game.record_combat(&events);
(events, velocity)
});
let Some((events, marked)) = events else {
return;
};
self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events {
match event {
MotionEvent::HurtSound(sound) => self.player_hurt_sound(sound, at),
@@ -225,6 +225,7 @@ impl Game<'_> {
Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()),
_ => return false,
};
let furnace = matches!(kind, Kind::Furnace(_));
// CrafterBlockEntity.containerData: the disabled slots, then triggered.
let crafter_data = match self.world.block_entities.get(&pos) {
Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)),
@@ -284,6 +285,12 @@ impl Game<'_> {
}
_ => {}
}
// FurnaceResultSlot.checkTakeAchievements: the guest took from the output.
let count = |s: Option<&ItemStack>| s.map_or(0, |s| s.count);
if furnace && count(menu.slot(2)) < count(items[2].as_ref()) {
let at = host.hub.guests[gi].position;
self.award_furnace_recipes(pos, at);
}
host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu));
host.hub.inventory_clicked(conn, p, &self.world, &changed);
true
+10 -2
View File
@@ -404,11 +404,19 @@ impl Game<'_> {
Value::Item(hub.stack(&Some(r.item.clone()))),
));
}
let boosted = match r.guest {
Some(conn) => hub
.guests
.iter()
.find(|g| g.conn == conn)
.map(|g| g.entity_id),
None => host_entity,
};
if r.attached
&& let Some(host) = host_entity
&& let Some(player) = boosted
{
e.meta
.push((9, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(host + 1)));
.push((9, serializer::OPTIONAL_UNSIGNED_INT, Value::Id(player + 1)));
}
if r.angled {
e.meta.push((10, serializer::BOOLEAN, Value::Bool(true)));
@@ -171,6 +171,19 @@ impl Game<'_> {
})
.collect()
}
/// The same guests' feet and whether they stand on the ground, for the
/// blocks that also ask that (`BigDripleafBlock.canEntityTilt`).
pub(super) fn lan_guest_feet(&self) -> Vec<([f64; 3], bool)> {
let Some(host) = self.lan.as_ref() else {
return Vec::new();
};
host.hub
.guests
.iter()
.filter(|g| host.hub.here(g) && g.loaded && !g.dead && !g.spectator())
.map(|g| (g.position, g.on_ground))
.collect()
}
/// The guests a projectile can hit, under their entity ids.
pub(super) fn lan_projectile_targets(&self) -> Vec<(Who, Aabb)> {
@@ -161,12 +161,12 @@ impl Game<'_> {
+ (self.particles.random().next_float() - self.particles.random().next_float())
* 0.2)
* 0.7;
self.audio.play(
"minecraft:entity.generic.explode",
Some(p.center),
4.0,
pitch,
);
// The packet's explosionSound: a wind charge's burst, a bed's
// or anchor's blast, a modded sound.
let sound = self
.remote_sound_name(&p.sound)
.unwrap_or_else(|| "minecraft:entity.generic.explode".to_owned());
self.audio.play(&sound, Some(p.center), 4.0, pitch);
}
if let Some(options) = self.received_particle(&p.particle, p.center) {
self.particles.add(&options, p.center, [1.0, 0.0, 0.0]);
+25 -1
View File
@@ -388,7 +388,10 @@ impl Restrictions {
1 => Some("chat_restriction.chat_disabled_by_options"),
_ => None,
};
let (chat, commands) = (chat_visibility == 0, chat_visibility < 2);
let abilities = horizon_client::chat::ChatAbilities::new(
horizon_client::chat::ChatVisibility::from_option(chat_visibility),
);
let (chat, commands) = (abilities.send_messages, abilities.send_commands);
// The body's widgets: text blocks (lines, top) and the action's top.
let mut blocks = Vec::new();
let mut action = None;
@@ -802,6 +805,27 @@ impl Game<'_> {
}
}
/// The pointer moved while a list's scrollbar is held: the game rules'
/// list follows it (AbstractSelectionList.mouseDragged).
pub(super) fn world_options_drag(&mut self) {
let h = self.gui_size().1;
if let Some(o) = self.world_options.as_mut()
&& o.view == View::GameRules
&& let Some(rules) = o.rules.as_mut()
{
rules.drag(self.cursor.1, h);
}
}
/// The button came up: a held scrollbar lets go (onRelease).
pub(super) fn world_options_release(&mut self) {
if let Some(o) = self.world_options.as_mut()
&& let Some(rules) = o.rules.as_mut()
{
rules.release();
}
}
pub(super) fn world_options_click(&mut self) {
let Some(mut o) = self.world_options.take() else {
return;
+2
View File
@@ -79,6 +79,8 @@ impl Game<'_> {
if horizon_client::mobs::leash::remove(m).is_none() {
return;
}
// Leashable.tickLeash gates a dying entity's lead drop on entity_drops.
let drop = drop && (m.alive() || self.ui.rules.bool("entity_drops"));
let at = [m.position.x, m.position.y, m.position.z];
if sound {
self.lead_sound("break", at);
@@ -101,6 +101,39 @@ impl Game<'_> {
}
}
}
/// `ServerLevel.globalLevelEvent`: heard by every player on the server
/// (an end portal opening, the dragon's death roar): here, and sent to
/// every guest whatever their dimension.
pub(super) fn global_level_event(&mut self, id: i32, pos: [i32; 3], data: i32) {
self.global_level_event_sound(id, pos);
if self.audio.capture.is_some() {
self.lan_global_events.push((id, pos, data));
}
}
/// `LevelEventHandler.globalLevelEvent`: the sound two blocks from the
/// camera towards the event, so it is heard from anywhere.
pub(super) fn global_level_event_sound(&mut self, id: i32, pos: [i32; 3]) {
let (sound, volume) = match id {
1023 => ("minecraft:entity.wither.spawn", 1.0),
1028 => ("minecraft:entity.ender_dragon.death", 5.0),
1038 => ("minecraft:block.end_portal.spawn", 1.0),
_ => return,
};
let at = self.eye_position().map(|eye| {
let d = [
f64::from(pos[0]) + 0.5 - eye[0],
f64::from(pos[1]) + 0.5 - eye[1],
f64::from(pos[2]) + 0.5 - eye[2],
];
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
if length < 1.0e-4 {
return eye;
}
[0, 1, 2].map(|k| eye[k] + d[k] / length * 2.0)
});
// Each guest plays it from the global packet.
self.audio.play_unshared(sound, at, volume, 1.0);
}
/// Queue and play level event `id` at `pos` (`Level.levelEvent`).
pub(super) fn level_event_at(&mut self, id: i32, pos: [i32; 3], data: i32) {
self.level_events.push(LevelEvent::LevelEvent {
+25 -6
View File
@@ -21,7 +21,7 @@ use super::{
use horizon_client::{
Result, block_entity_anim::BlockEntityAnims, random_tick_sections::RandomTickSections,
save::SaveDir, streaming::Streaming, tick_chunk_membership::TickChunkMembership,
ticket_levels::ChunkTickets, world::World,
ticket_levels::ChunkTickets, vanillagen::VanillaTerrain, world::World,
};
use horizon_world::level::{LevelEvent, Ticks};
use std::{
@@ -39,6 +39,7 @@ const IDLE_TICKS: u32 = 300;
pub(super) struct Parked {
world: World,
streaming: Streaming,
locator: Option<Arc<VanillaTerrain>>,
save: Arc<SaveDir>,
block_ticks: Ticks,
tick_chunks: TickChunkMembership,
@@ -109,13 +110,21 @@ pub(super) struct Levels {
impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> {
let (streaming, save) =
self.make_streaming(&self.world_root.clone(), dim, self.level.seed)?;
let (streaming, save, locator) = super::world_loading::make_streaming(
&self.res,
&self.pack,
&self.options,
&self.settings,
&self.world_root,
dim,
self.level.seed,
)?;
let mut world = World::new(self.res.facts().air, self.level.seed);
world.fast_lava = dim == Dim::Nether;
Ok(Parked {
world,
streaming,
locator,
save,
block_ticks: Ticks::new(self.level.seed as i32),
tick_chunks: Default::default(),
@@ -163,6 +172,9 @@ impl Game<'_> {
use std::mem::swap;
swap(&mut self.world, &mut p.world);
swap(&mut self.streaming, &mut p.streaming);
let mut locator = self.end.locator();
swap(&mut locator, &mut p.locator);
self.end.set_locator(locator);
swap(&mut self.save, &mut p.save);
swap(&mut self.block_ticks, &mut p.block_ticks);
swap(&mut self.tick_chunks, &mut p.tick_chunks);
@@ -365,7 +377,12 @@ impl Game<'_> {
}
*next += self.clock.tick_duration();
if *next > now {
std::thread::sleep(*next - now);
// A `/pregen` task keeps the workers fed until the next tick.
self.pump_pregen(*next);
let now = Instant::now();
if *next > now {
std::thread::sleep(*next - now);
}
} else if now - *next > Duration::from_secs(2) {
*next = now;
}
@@ -373,7 +390,7 @@ impl Game<'_> {
/// The levels this server tick runs, in `MinecraftServer.levels` order
/// (the Overworld, the Nether, the End): every level with a player in
/// it, or the Overworld while nobody is online.
/// it or a `/pregen` task, or the Overworld while nobody is online.
pub(super) fn levels_to_tick(&self) -> Vec<Dim> {
let guests = self
.lan
@@ -381,7 +398,9 @@ impl Game<'_> {
.map_or(&[][..], |h| h.hub.guests.as_slice());
let mut dims: Vec<Dim> = [Dim::Overworld, Dim::Nether, Dim::End]
.into_iter()
.filter(|d| guests.iter().any(|g| g.dimension == d.id()))
.filter(|d| {
guests.iter().any(|g| g.dimension == d.id()) || self.pregen_level() == Some(*d)
})
.collect();
if dims.is_empty() {
dims.push(Dim::Overworld);
+6 -3
View File
@@ -218,7 +218,7 @@ impl Game<'_> {
oy: f32,
draws: &[ScreenDraw],
background: bool,
) -> Option<Vec<(String, u32)>> {
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let atlas = &self.gui.atlas;
let mut tooltip = None;
let mut sheet: Option<String> = None;
@@ -261,7 +261,10 @@ impl Game<'_> {
..
} => self.draw_banner_result(batch, ox + *x0 as f32, oy + *y0 as f32, base, layers),
ScreenDraw::Tooltip { key } => {
tooltip = Some(vec![(self.translate(key, key), u32::MAX)]);
tooltip = Some(vec![(
horizon_client::text::Text::literal(self.translate(key, key)),
u32::MAX,
)]);
}
ScreenDraw::SpriteOf { id } => sheet = Some(id.clone()),
ScreenDraw::Fill {
@@ -314,7 +317,7 @@ impl Game<'_> {
ox: f32,
oy: f32,
local: (f32, f32),
) -> Option<Vec<(String, u32)>> {
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let s = self.station.as_ref()?;
let l = &s.loom;
let dye = s.inputs[1]
+33 -20
View File
@@ -889,13 +889,31 @@ impl Game<'_> {
let key_is_cart = self
.container
.is_some_and(|k| k.1 == super::minecarts::CART_KEY_Y);
let (texture, height, title) = match screen {
Screen::Hopper if key_is_cart => {
("gui/container/hopper", 133.0, "Minecart with Hopper")
}
Screen::Hopper => ("gui/container/hopper", 133.0, "Item Hopper"),
Screen::Dispenser => ("gui/container/dispenser", 166.0, "Dispenser"),
Screen::Dropper => ("gui/container/dispenser", 166.0, "Dropper"),
let (texture, height, key, fallback) = match screen {
Screen::Hopper if key_is_cart => (
"gui/container/hopper",
133.0,
"entity.minecraft.hopper_minecart",
"Minecart with Hopper",
),
Screen::Hopper => (
"gui/container/hopper",
133.0,
"container.hopper",
"Item Hopper",
),
Screen::Dispenser => (
"gui/container/dispenser",
166.0,
"container.dispenser",
"Dispenser",
),
Screen::Dropper => (
"gui/container/dispenser",
166.0,
"container.dropper",
"Dropper",
),
};
if let Some(mut r) = atlas.sprites.get(texture).copied() {
let dv = (r.v1 - r.v0) / r.h as f32;
@@ -905,23 +923,18 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self
.remote_menu_title()
.unwrap_or_else(|| self.container_title(title.to_owned()));
let title = &self.remote_menu_title().unwrap_or_else(|| {
horizon_client::text::Text::literal(self.container_title(self.translate(key, fallback)))
.resolve_legacy()
});
let title_x = if screen == Screen::Hopper {
8.0
} else {
(176.0 - horizon_client::hud::HudBatch::text_width(atlas, title)) / 2.0
(176.0 - atlas.font.width_text(title)) / 2.0
};
batch.text(atlas, title, ox + title_x, oy + 6.0, grey, false);
batch.text(
atlas,
"Inventory",
ox + 8.0,
oy + height - 94.0,
grey,
false,
);
batch.text_styled(atlas, title, ox + title_x, oy + 6.0, grey, false);
let inventory = self.translate("container.inventory", "Inventory");
batch.text(atlas, &inventory, ox + 8.0, oy + height - 94.0, grey, false);
true
}
}
@@ -256,7 +256,8 @@ impl Game<'_> {
grey,
false,
);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
let inventory = self.translate("container.inventory", "Inventory");
batch.text(atlas, &inventory, ox + 8.0, oy + 72.0, grey, false);
self.paint_screen(batch, ox, oy, rest, true);
}
/// `gui.togglable_slot` over an empty, enabled grid slot.
@@ -1463,6 +1463,7 @@ impl Game<'_> {
lid: &lid,
sign: &|_| None,
banner: &|_| Vec::new(),
skull: &|_| None,
glyph: &|c| self.gui.atlas.glyph_cell(c),
};
self.res
+2 -2
View File
@@ -259,7 +259,7 @@ impl Game<'_> {
// ItemInHandLayer submits with OverlayTexture.NO_OVERLAY: no hurt tint.
for (item, off_hand) in [(&mob.extra.main_hand, false), (&mob.extra.off_hand, true)] {
let Some(item) = item else { continue };
let left = off_hand != mob.extra.main_hand_left;
let left = off_hand != mob.main_arm_left();
let Some(t) =
render::held_item_transform(mob, alpha as f32, camera, self.res.mob_data(), left)
else {
@@ -305,7 +305,7 @@ impl Game<'_> {
.player_model
.as_ref()
.is_some_and(|p| std::ptr::eq(p, mob));
owner.main_arm_left = mob.extra.main_hand_left;
owner.main_arm_left = mob.main_arm_left();
if off_hand == mob.extra.using_off_hand && mob.extra.using_item > 0 {
owner.using_this_item = true;
owner.use_duration = 72_000;
@@ -0,0 +1,92 @@
//! Capability `input` (docs/mods.md): the use button on items a mod claims,
//! and the mod's own keys. With no mod claiming items or keys, each hook
//! here returns after one check.
use super::Game;
use winit::{event::MouseButton, keyboard::KeyCode};
#[cfg(feature = "mods")]
use {super::Screen, horizon_mods::HeldItem};
/// A claimed item's use while the button is down.
#[cfg(feature = "mods")]
pub(super) struct ModUse {
item: HeldItem,
/// `Game::ticks` when it started.
since: u64,
}
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn mod_use(&mut self, _button: MouseButton, _pressed: bool) -> bool {
false
}
pub(super) fn mod_key(&mut self, _key: KeyCode, _pressed: bool, _repeat: bool) {}
}
#[cfg(feature = "mods")]
impl Game<'_> {
/// The main hand's stack as `input` shows it; none when it is empty.
pub(super) fn mod_held(&self) -> Option<HeldItem> {
let stack = self.inventory.get(self.selected)?.as_ref()?;
Some(HeldItem {
id: stack.item.to_string(),
count: stack.count,
slot: self.selected as u32,
})
}
/// The use button while playing: true when a mod claimed the held item,
/// so the game does nothing else with it (no placing, eating, swing).
pub(super) fn mod_use(&mut self, button: MouseButton, pressed: bool) -> bool {
if button != MouseButton::Right || !self.mods.mods.claims_any() {
return false;
}
if !pressed {
return self.stop_mod_use();
}
let Some(item) = self.mod_held().filter(|h| self.mods.mods.claims(&h.id)) else {
return false;
};
self.mods.mods.use_start(&item);
self.mods.using = Some(ModUse {
item,
since: self.ticks,
});
true
}
/// Ends a claimed use: the button came up, the player switched slots,
/// or a screen opened. False when none was going.
pub(super) fn stop_mod_use(&mut self) -> bool {
let Some(u) = self.mods.using.take() else {
return false;
};
let ticks = self.ticks.saturating_sub(u.since).min(u64::from(u32::MAX)) as u32;
self.mods.mods.use_stop(&u.item, ticks);
true
}
/// Once a tick: a claimed use stops when its item leaves the hand or a
/// screen opens, as vanilla's `releaseUsingItem`.
pub(super) fn tick_mod_use(&mut self) {
let Some(u) = &self.mods.using else {
return;
};
let still = self
.mod_held()
.is_some_and(|h| h.id == u.item.id && h.slot == u.item.slot);
if !still || self.screen != Screen::Playing {
self.stop_mod_use();
}
}
/// A key went down or up: a mod's registered key while playing (no
/// screen) is its `key-down` / `key-up`. Vanilla's mapping on the same
/// key still runs.
pub(super) fn mod_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) {
if repeat || !self.mods.mods.has_keys() {
return;
}
if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
return;
}
if let Some(name) = horizon_client::keybinds::key_name(key) {
self.mods.mods.key(name, pressed);
}
}
}
@@ -0,0 +1,184 @@
//! Capability `render` (docs/mods.md): the shapes mods keep on the HUD,
//! drawn by the game's own HUD renderer, and their camera shakes. Mods
//! never supply shader code. With no mod drawing, each hook here returns
//! after one check.
use super::Game;
use horizon_client::hud::HudBatch;
#[cfg(feature = "mods")]
use {
horizon_client::{hud::rgba, items::ItemStack, text::Text},
horizon_mods::Shape,
std::time::Instant,
};
/// The camera's jolts from `render.shake`, while any is fading.
#[cfg(feature = "mods")]
#[derive(Default)]
pub(super) struct Shake {
jolts: Vec<Jolt>,
}
#[cfg(feature = "mods")]
struct Jolt {
start: Instant,
strength: f32,
seconds: f32,
}
/// The HUD batch's colour (ABGR) from a mod's 0xAARRGGBB.
#[cfg(feature = "mods")]
fn argb(color: u32) -> u32 {
let [a, r, g, b] = color.to_be_bytes();
rgba(r, g, b, a)
}
/// The view's turn at full strength, in degrees: yaw, then pitch.
#[cfg(feature = "mods")]
const SHAKE_DEGREES: (f32, f32) = (3.0, 2.0);
#[cfg(feature = "mods")]
impl Shake {
pub(super) fn add(&mut self, strength: f32, seconds: f32) {
self.jolts.push(Jolt {
start: Instant::now(),
strength,
seconds,
});
}
/// How far the view turns now (yaw, pitch degrees), `scale` being the
/// player's Distortion Effects; fades jolts out and forgets ended ones.
fn offset(&mut self, now: Instant, scale: f32) -> (f32, f32) {
self.jolts
.retain(|j| now.duration_since(j.start).as_secs_f32() < j.seconds);
let mut strength = 0.0;
for j in &self.jolts {
let left = 1.0 - now.duration_since(j.start).as_secs_f32() / j.seconds;
strength += j.strength * left * left;
}
let strength = strength.min(1.0) * scale.clamp(0.0, 1.0);
if strength <= 0.0 {
return (0.0, 0.0);
}
// Smooth noise: sines at unrelated rates, so it never repeats visibly.
let t = self
.jolts
.first()
.map_or(0.0, |j| now.duration_since(j.start).as_secs_f32());
let wave = |a: f32, b: f32, c: f32| {
((t * a).sin() * 0.5 + (t * b).sin() * 0.3 + (t * c).sin() * 0.2).clamp(-1.0, 1.0)
};
(
strength * SHAKE_DEGREES.0 * wave(23.0, 37.3, 51.7),
strength * SHAKE_DEGREES.1 * wave(29.1, 43.9, 61.3),
)
}
}
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn draw_mod_shapes(&self, _batch: &mut HudBatch) {}
pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) {
(yaw, pitch)
}
}
#[cfg(feature = "mods")]
impl Game<'_> {
/// The running mods' HUD shapes, in order, over the HUD.
pub(super) fn draw_mod_shapes(&self, batch: &mut HudBatch) {
for shape in self.mods.mods.hud_shapes() {
self.draw_shapes(batch, std::slice::from_ref(shape), (0.0, 0.0));
}
}
/// Shapes with their GUI coordinates moved by `(ox, oy)`.
pub(super) fn draw_shapes(&self, batch: &mut HudBatch, shapes: &[Shape], (ox, oy): (f32, f32)) {
let atlas = &self.gui.atlas;
for shape in shapes {
match shape {
Shape::Fill(f) => {
let r = f.rect;
batch.fill(atlas, ox + r.x, oy + r.y, r.w, r.h, argb(f.color));
}
Shape::Quad(q) => {
let (a, b, c, d) = q.corners;
let corners = [a, b, c, d].map(|p| [ox + p.x, oy + p.y]);
batch.fill_quad(atlas, corners, argb(q.color));
}
Shape::Sprite(s) => {
let r = s.rect;
let name = s.sprite.strip_prefix("minecraft:").unwrap_or(&s.sprite);
let name = format!("gui/sprites/{name}");
batch.sprite_scaled(atlas, &name, ox + r.x, oy + r.y, r.w, r.h, argb(s.color));
}
Shape::Item(i) => {
if self.res.items().get(&i.item).is_none() {
continue;
}
let start = batch.vertices.len();
let stack = ItemStack::new(i.item.as_str(), 1);
let (x, y) = (ox + i.at.x, oy + i.at.y);
self.draw_item_model(batch, &stack, x, y);
batch.scale_since(start, x, y, i.scale, i.scale);
}
Shape::Text(t) => {
let text = Text::literal(t.text.clone());
let centre = if t.centered {
(HudBatch::text_width(atlas, &t.text) / 2.0).floor()
} else {
0.0
};
let x = ox + t.at.x - centre;
batch.text_styled(
atlas,
&text,
x,
oy + t.at.y,
argb(t.color | 0xFF00_0000),
t.shadow,
);
}
}
}
}
/// The view's yaw and pitch after the mods' camera shakes; unchanged
/// while none is fading.
pub(super) fn shaken_view(&mut self, yaw: f32, pitch: f32) -> (f32, f32) {
if self.mods.shake.jolts.is_empty() {
return (yaw, pitch);
}
let scale = self.settings.file.double("screenEffectScale") as f32;
let (dy, dp) = self.mods.shake.offset(Instant::now(), scale);
(yaw + dy, (pitch + dp).clamp(-90.0, 90.0))
}
}
#[cfg(all(test, feature = "mods"))]
mod tests {
use super::*;
use std::time::Duration;
#[test]
fn a_jolt_fades_out_and_distortion_scales_it() {
let mut shake = Shake::default();
shake.add(1.0, 2.0);
let start = shake.jolts[0].start;
let at = |s: f32| start + Duration::from_secs_f32(s);
let size = |(y, p): (f32, f32)| y.abs() + p.abs();
// Off with Distortion Effects at 0, inside the limits otherwise.
assert_eq!(shake.offset(at(0.3), 0.0), (0.0, 0.0));
let (y, p) = shake.offset(at(0.3), 1.0);
assert!(y.abs() <= SHAKE_DEGREES.0 && p.abs() <= SHAKE_DEGREES.1);
// Fading: the largest turn over a window shrinks.
let mut peak = |from: f32| {
(0..50)
.map(|i| size(shake.offset(at(from + i as f32 * 0.002), 1.0)))
.fold(0.0, f32::max)
};
let early = peak(0.1);
let late = peak(1.6);
assert!(late < early, "{late} !< {early}");
// Gone once it ends.
assert_eq!(shake.offset(at(2.1), 1.0), (0.0, 0.0));
assert!(shake.jolts.is_empty());
}
}
+513 -10
View File
@@ -20,17 +20,27 @@ use {
horizon_client::{
extras::Corner,
extras_hud,
items::ItemStack,
keybinds,
mod_list::Installed,
options_ui::Page,
text::{self, Text},
ui,
},
horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status},
horizon_mods::{Clock, Mods, Output, Player, Snapshot, Status, UiScreen, UiWidget},
std::time::Instant,
};
#[derive(Default)]
pub(super) struct ModsState {
#[cfg(feature = "mods")]
mods: Mods,
pub(super) mods: Mods,
/// Capability `input`: a claimed item's use while the button is down.
#[cfg(feature = "mods")]
pub(super) using: Option<super::mod_input::ModUse>,
/// Capability `render`'s camera shakes.
#[cfg(feature = "mods")]
pub(super) shake: super::mod_render::Shake,
/// `--dev-mod PATH`: always on, reloaded when rebuilt.
pub(super) dev: Vec<PathBuf>,
/// When dev mods were last checked for a rebuild.
@@ -39,6 +49,55 @@ pub(super) struct ModsState {
/// The chat's command tree while a running mod owns commands.
#[cfg(feature = "mods")]
tree: Option<Dispatcher>,
/// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse.
#[cfg(feature = "mods")]
commands: Vec<String>,
/// The server's command tree with the running mods' commands added.
#[cfg(feature = "mods")]
remote_tree: Option<Dispatcher>,
/// A `ui` mod's screen or settings page while it is up.
#[cfg(feature = "mods")]
screen: Option<ModScreen>,
/// The HUD font's advances for `render.text-width`, made once.
#[cfg(feature = "mods")]
font_widths: std::sync::Arc<[f32]>,
}
/// The mappings `input.mapping` answers for, with the default key their
/// binding is translated to (none: a mouse button, attack or use).
#[cfg(feature = "mods")]
const MAPPINGS: [(&str, Option<winit::keyboard::KeyCode>); 9] = {
use winit::keyboard::KeyCode as K;
[
("key.forward", Some(K::KeyW)),
("key.left", Some(K::KeyA)),
("key.back", Some(K::KeyS)),
("key.right", Some(K::KeyD)),
("key.jump", Some(K::Space)),
("key.sneak", Some(K::ShiftLeft)),
("key.sprint", Some(K::ControlLeft)),
("key.attack", None),
("key.use", None),
]
};
/// Characters `render.text-width` knows exactly: U+0000 to U+024F.
#[cfg(feature = "mods")]
const FONT_CHARS: u32 = 0x250;
/// A `ui` mod's own screen, or its settings page from Options > Mods: the
/// widgets the mod pushed, laid out and drawn with the menus' own widgets.
#[cfg(feature = "mods")]
struct ModScreen {
/// The running mod's index in `mods.mods.entries()`.
owner: usize,
/// Opened from Options > Mods: Done and Esc return there.
settings: bool,
/// What the mod's screen replaced (Playing, Chat, ...), to restore.
under: Screen,
/// One scroll per `list` widget, in widget order.
scrolls: Vec<ui::Scroll>,
}
impl ModsState {
/// The chat's command tree: vanilla's, plus the running mods' commands.
@@ -49,6 +108,14 @@ impl ModsState {
}
vanilla::game_dispatcher()
}
/// The server's tree plus the mods' commands, when a mod owns any.
pub(super) fn remote_dispatcher(&self) -> Option<&Dispatcher> {
#[cfg(feature = "mods")]
if let Some(tree) = &self.remote_tree {
return Some(tree);
}
None
}
/// Whether a mod runs: the chat keeps its lines for them.
pub(super) fn running(&self) -> bool {
#[cfg(feature = "mods")]
@@ -57,10 +124,10 @@ impl ModsState {
}
false
}
/// Whether a mod draws a HUD panel.
/// Whether a mod draws a HUD panel or a corner panel.
pub(super) fn has_panels(&self) -> bool {
#[cfg(feature = "mods")]
if self.mods.panels().next().is_some() {
if self.mods.panels().next().is_some() || self.mods.corner_panels().next().is_some() {
return true;
}
false
@@ -158,6 +225,7 @@ impl Game<'_> {
);
}
}
pub(super) fn merge_remote_tree(&mut self) {}
pub(super) fn sync_mods(&mut self) {}
pub(super) fn tick_mods(&mut self) {}
pub(super) fn mods_frame(&mut self, _elapsed: Duration) {}
@@ -166,6 +234,11 @@ impl Game<'_> {
}
pub(super) fn mods_chat(&mut self, _line: &str) {}
pub(super) fn draw_mod_panels(&self, _batch: &mut HudBatch, _corners: &mut Corners) {}
pub(super) fn open_mod_screen(&mut self, _owner: usize, _settings: bool) {}
pub(super) fn close_mod_screen(&mut self, _tell: bool) {}
pub(super) fn draw_mod_screen(&mut self, _batch: &mut HudBatch) {}
pub(super) fn mod_screen_click(&mut self) {}
pub(super) fn mod_screen_scroll(&mut self, _delta: f32) {}
}
#[cfg(feature = "mods")]
@@ -187,6 +260,8 @@ impl Game<'_> {
let on = |id: &str| enabled.contains(id) || dev_ids.iter().any(|d| d == id);
let mods = Mods::load(&paths, on, vanilla_command);
self.mods.mods = mods;
// Entries were replaced wholesale: a screen's owner index is stale.
self.mods.screen = None;
self.list_mods();
self.sync_mod_commands();
self.show_mod_output();
@@ -212,6 +287,7 @@ impl Game<'_> {
description: String::new(),
problem,
dev: false,
has_settings: false,
};
};
// What it may do first: the row cuts long descriptions.
@@ -227,6 +303,7 @@ impl Game<'_> {
description: format!("{may} {}", m.description).trim().to_owned(),
problem,
dev: dev.contains(&e.path),
has_settings: e.has_ui_settings(),
}
})
.collect();
@@ -238,7 +315,20 @@ impl Game<'_> {
.peek()
.is_some()
.then(|| vanilla::game_dispatcher().with_mod_commands(names));
self.merge_remote_tree();
}
/// The server's command tree with the mods' commands, for the chat.
pub(super) fn merge_remote_tree(&mut self) {
let names: Vec<String> = self.mods.mods.commands().map(str::to_owned).collect();
self.mods.remote_tree = self
.remote
.as_ref()
.and_then(|r| r.commands.as_ref())
.filter(|_| !names.is_empty())
.map(|t| t.with_mod_commands(names.iter().map(String::as_str)));
}
/// After the options changed: restart the mods if the list of the ones
/// turned on did.
pub(super) fn sync_mods(&mut self) {
@@ -263,8 +353,8 @@ impl Game<'_> {
self.start_mods();
}
}
/// What mods read this tick.
fn mod_snapshot(&self) -> Snapshot {
/// What mods read this tick (or frame, for mods with a `frame` hook).
fn mod_snapshot(&mut self) -> Snapshot {
let player = self.player.as_ref().map(|p| Player {
x: p.position.x,
y: p.position.y,
@@ -279,13 +369,48 @@ impl Game<'_> {
game_time: self.world.game_time.max(0) as u64,
day_time: self.world.day_time.max(0) as u64,
});
Snapshot { player, clock }
let (cps, mouse) = self.mouse_reading();
// The movement and click mappings, as the keystroke overlay reads them:
// keys by the default key their binding is translated to.
let mappings = MAPPINGS
.iter()
.map(|&(name, key)| {
let label = keybinds::display_name(self.settings.keys.get(name)).plain();
let down = match key {
Some(k) => self.keys.contains(&k),
None => mouse[usize::from(name == "key.use")],
};
(name, label, down)
})
.collect();
if self.mods.font_widths.is_empty() {
let atlas = &self.gui.atlas;
self.mods.font_widths = (0..FONT_CHARS)
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
.collect();
}
Snapshot {
player,
clock,
gui_size: self.gui_size(),
held: self.mod_held(),
frame: self.frame_reading(),
mappings,
cps,
font_widths: self.mods.font_widths.clone(),
}
}
/// A game tick.
pub(super) fn tick_mods(&mut self) {
// Here, at the player's level: shown inside a console call (a control
// socket command set the hook off), they would run as the console.
for line in std::mem::take(&mut self.mods.commands) {
self.run_command(&line);
}
if !self.mods.mods.is_running() {
return;
}
self.tick_mod_use();
let snapshot = self.mod_snapshot();
self.mods.mods.set_snapshot(snapshot);
self.mods.mods.tick(self.ticks);
@@ -309,6 +434,10 @@ impl Game<'_> {
if !self.mods.mods.is_running() {
return;
}
if self.mods.mods.wants_frames() {
let snapshot = self.mod_snapshot();
self.mods.mods.set_snapshot(snapshot);
}
self.mods.mods.frame(elapsed.as_secs_f32());
self.show_mod_output();
}
@@ -342,17 +471,58 @@ impl Game<'_> {
}
Output::Feedback { text, error: false } => Text::literal(text),
Output::Feedback { text, error: true } => Text::literal(text).with_color(text::RED),
// Vanilla's commands only: a mod running a mod command could loop.
Output::Command { line } => {
let name = line.split(' ').next().unwrap_or_default();
if !vanilla_command(name) {
// Dropped.
} else if self.remote.is_some() {
// The server checks the player's permissions.
self.send_chat(&format!("/{line}"));
} else {
self.mods.commands.push(line);
}
continue;
}
Output::Stopped { name, reason } => {
// Its screen goes with it: the entry's run is gone, so
// `mod_ui_view` finds no widgets and the screen closes.
self.list_mods();
self.sync_mod_commands();
Text::literal(format!("Mod {name} stopped: {reason}")).with_color(text::RED)
}
Output::OpenScreen { owner } => {
self.open_mod_screen(owner, false);
continue;
}
Output::Shake { strength, seconds } => {
self.mods.shake.add(strength, seconds);
continue;
}
Output::CloseScreen { owner } => {
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
self.close_mod_screen(false);
}
continue;
}
};
// Not through system_message: a mod must not hear its own lines.
// Written by this client, so the Chat option doesn't hide it.
let focused = self.screen == Screen::Chat;
self.ui
.chat
.add(&self.gui.atlas, line, None, self.ticks, focused);
self.ui.chat.add(
&self.gui.atlas,
line,
None,
horizon_client::chat::ChatSource::Client,
self.ticks,
focused,
);
}
// A mod may set or clear its settings page in any call, not only
// while loading: its row's Settings button follows.
let rows = self.settings.mods.installed.iter_mut();
for (row, e) in rows.zip(self.mods.mods.entries()) {
row.has_settings = e.has_ui_settings();
}
}
/// The mods' HUD panels, stacked with the extras in their corners.
@@ -375,5 +545,338 @@ impl Game<'_> {
.collect();
extras_hud::draw_lines(batch, &self.gui.atlas, corners, corner, &lines);
}
// Capability `render`'s corner panels, placed the same way.
for panel in self.mods.mods.corner_panels() {
let corner = match panel.corner {
horizon_mods::RenderCorner::TopLeft => Corner::TopLeft,
horizon_mods::RenderCorner::TopRight => Corner::TopRight,
horizon_mods::RenderCorner::BottomLeft => Corner::BottomLeft,
horizon_mods::RenderCorner::BottomRight => Corner::BottomRight,
};
if self.debug && corner == Corner::TopLeft {
continue;
}
let at = corners.place(corner, panel.width, panel.height);
self.draw_shapes(batch, &panel.shapes, at);
}
}
/// A `ui` screen's title and widgets as the mod last pushed them; None
/// when the surface is gone (the mod stopped or closed it). Borrows
/// `mods` only, so `self.mods.screen` may stay borrowed for the scrolls.
fn mod_ui_view<'a>(mods: &'a Mods, ms: &ModScreen) -> Option<(&'a str, &'a [UiWidget])> {
if ms.settings {
let widgets = mods.settings_widgets(ms.owner);
if widgets.is_empty() {
return None;
}
let name = mods
.entries()
.get(ms.owner)
.and_then(|e| e.manifest.as_ref())
.map_or("Mod", |m| m.name.as_str());
Some((name, widgets))
} else {
let s: &UiScreen = mods.screen(ms.owner)?;
Some((s.title.as_str(), s.widgets.as_slice()))
}
}
/// The layout the mod screen's widgets get at `h`: (widget, top,
/// height), the column being `COLUMN` wide down the middle.
fn mod_ui_layout(h: f32, widgets: &[UiWidget]) -> Vec<(f32, f32)> {
let mut out = Vec::with_capacity(widgets.len());
let mut y = MOD_UI_TOP;
for w in widgets {
let wh = match w {
UiWidget::Text(_) => 12.0,
UiWidget::Item(_) | UiWidget::Button(_) => 20.0,
UiWidget::List(l) => (l.rows.len().min(6) as f32 * 12.0) + 8.0,
};
// Nothing may cover Done; a crowded mod loses what won't fit.
if y + wh > h - 34.0 {
break;
}
out.push((y, wh));
y += wh + 6.0;
}
out
}
/// A mod pushes its screen (`ui.open-screen`), or Options > Mods opens
/// its settings page (`settings`, the mod's `installed` index).
pub(super) fn open_mod_screen(&mut self, owner: usize, settings: bool) {
if self.title.is_some() {
return;
}
if settings {
self.mods.mods.ui_settings_opened(owner);
if self.mods.mods.settings_widgets(owner).is_empty() {
self.show_mod_output();
return;
}
}
self.mods.screen = Some(ModScreen {
owner,
settings,
under: self.screen,
scrolls: Vec::new(),
});
self.screen = Screen::Mod;
if self.player.is_some() {
self.capture(false);
}
self.show_mod_output();
}
/// Leaves the mod screen: back to Options for a settings page, to what
/// it covered for a mod's own. `tell` is Esc/Done, heard as `closed`.
pub(super) fn close_mod_screen(&mut self, tell: bool) {
let Some(ms) = self.mods.screen.take() else {
return;
};
if ms.settings {
self.open_options_at(self.options_from_title, Page::Mods);
} else {
self.screen = ms.under;
if self.screen == Screen::Playing && self.player.is_some() {
self.capture(true);
}
}
if tell {
self.mods.mods.ui_closed(ms.owner);
self.show_mod_output();
}
}
/// The mod's screen or settings page: its title over widgets stacked
/// down the middle, a Done button, Esc to leave (vanilla's menus).
pub(super) fn draw_mod_screen(&mut self, batch: &mut HudBatch) {
let Some(ms) = self.mods.screen.as_mut() else {
// The screen was dropped while it was up: back to the world,
// mouse held again like any return to Playing.
self.screen = Screen::Playing;
if self.player.is_some() {
self.capture(true);
}
return;
};
let Some((title, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
// The mod's surface is gone (it stopped or cleared it): leave
// the screen like Done did, without `closed` — the mod ended it.
self.close_mod_screen(false);
return;
};
// Item icons draw in a second pass: `draw_item` needs `&mut self`,
// so `atlas` may not stay borrowed across it.
let mut items: Vec<(String, f32, f32)> = Vec::new();
let atlas = &self.gui.atlas;
let in_world = self.player.is_some();
ui::menu_background(batch, atlas, 0.0, 0.0, batch.width, batch.height, in_world);
ui::centered_text(
batch,
atlas,
&Text::literal(title),
0.0,
15.0,
batch.width,
u32::MAX,
);
let cx = (batch.width / 2.0).floor();
let x = cx - MOD_UI_COLUMN / 2.0;
let layout = Self::mod_ui_layout(batch.height, widgets);
let mut list_i = 0usize;
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
match w {
UiWidget::Button(b) => {
let hover = ui::hovered(self.cursor, x, wy, MOD_UI_COLUMN, 20.0);
let label = Text::literal(b.label.clone());
ui::button(
batch,
atlas,
x,
wy,
MOD_UI_COLUMN,
20.0,
&label,
true,
hover,
);
}
UiWidget::Text(t) => {
let color = if t.color == 0 {
u32::MAX
} else {
t.color | 0xFF00_0000
};
ui::centered_text(
batch,
atlas,
&Text::literal(t.text.clone()),
x,
wy + 1.0,
MOD_UI_COLUMN,
color,
);
}
UiWidget::Item(i) => {
if self.res.items().get(&i.item).is_some() {
items.push((i.item.clone(), x + 2.0, wy + 2.0));
} else {
batch.text(atlas, "?", x + 6.0, wy + 6.0, u32::MAX, true);
}
let name = if i.name.is_empty() {
i.item.rsplit(':').next().unwrap_or(&i.item).to_string()
} else {
i.name.clone()
};
batch.text_styled(
atlas,
&Text::literal(name),
x + 22.0,
wy + 6.0,
u32::MAX,
true,
);
}
UiWidget::List(l) => {
ms.scrolls.resize_with(list_i + 1, ui::Scroll::default);
let scroll = ms.scrolls[list_i];
list_i += 1;
let rows_top = wy + 4.0;
let rows_bottom = wy + wh - 4.0;
batch.fill(atlas, x, wy, MOD_UI_COLUMN, wh, 0x8000_0000);
for (b, yy) in [(x, wy), (x, wy + wh - 1.0)] {
batch.fill(atlas, b, yy, MOD_UI_COLUMN, 1.0, 0xFF50_5050);
}
for (xx, yy) in [(x, wy), (x + MOD_UI_COLUMN - 1.0, wy)] {
batch.fill(atlas, xx, yy, 1.0, wh, 0xFF50_5050);
}
let content = l.rows.len() as f32 * 12.0;
let first = (scroll.amount / 12.0) as usize;
let last = (first + ((rows_bottom - rows_top) / 12.0).ceil() as usize + 1)
.min(l.rows.len());
for (vi, ri) in (first..last).enumerate() {
let ry = rows_top + vi as f32 * 12.0 - (scroll.amount % 12.0);
if ui::hovered(self.cursor, x, ry, MOD_UI_COLUMN - 6.0, 12.0) {
batch.fill(atlas, x + 1.0, ry, MOD_UI_COLUMN - 8.0, 12.0, 0x20FF_FFFF);
}
if l.selected == Some(ri as u32) {
batch.fill(atlas, x + 1.0, ry, 3.0, 12.0, 0xFFFF_FFFF);
}
batch.text_styled(
atlas,
&Text::literal(l.rows[ri].clone()),
x + 6.0,
ry + 2.0,
u32::MAX,
true,
);
}
ui::scrollbar(
batch,
atlas,
x + MOD_UI_COLUMN - 5.0,
rows_top,
rows_bottom,
content,
scroll.amount,
);
}
}
}
let hover = ui::hovered(self.cursor, cx - 100.0, batch.height - 27.0, 200.0, 20.0);
ui::button(
batch,
atlas,
cx - 100.0,
batch.height - 27.0,
200.0,
20.0,
&Text::literal("Done"),
true,
hover,
);
for (id, ix, iy) in items {
let stack = ItemStack::new(id.as_str(), 1);
self.draw_item(batch, &stack, ix, iy);
}
}
/// A click on the mod screen: Done leaves it, a `list` row is the mod's
/// `ui-events::select`.
pub(super) fn mod_screen_click(&mut self) {
let (w, h) = self.gui_size();
let cursor = self.cursor;
if ui::hovered(cursor, (w / 2.0).floor() - 100.0, h - 27.0, 200.0, 20.0) {
self.audio.play_button_click();
self.close_mod_screen(true);
return;
}
let Some(ms) = self.mods.screen.as_ref() else {
return;
};
let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
return;
};
let owner = ms.owner;
let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0;
let layout = Self::mod_ui_layout(h, widgets);
let mut list_i = 0usize;
// The `ui_select` call needs `&mut`: find the pick first.
let mut hit = None;
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
// A button is `select(id, 0)`.
if let UiWidget::Button(b) = w
&& ui::hovered(cursor, x, wy, MOD_UI_COLUMN, 20.0)
{
self.audio.play_button_click();
let owner = self.mods.screen.as_ref().map_or(0, |ms| ms.owner);
self.mods.mods.ui_select(owner, b.id, 0);
self.show_mod_output();
return;
}
let UiWidget::List(l) = w else { continue };
let scroll = ms.scrolls.get(list_i).copied().unwrap_or_default();
list_i += 1;
let row = ((cursor.1 - (wy + 4.0) + scroll.amount) / 12.0) as i64;
if ui::hovered(cursor, x + 1.0, wy + 1.0, MOD_UI_COLUMN - 7.0, wh - 2.0)
&& row >= 0
&& (row as usize) < l.rows.len()
{
hit = Some((l.id, row as u32));
break;
}
}
if let Some((id, row)) = hit {
self.audio.play_button_click();
self.mods.mods.ui_select(owner, id, row);
self.show_mod_output();
}
}
/// The wheel over a `list` scrolls it.
pub(super) fn mod_screen_scroll(&mut self, delta: f32) {
let (w, h) = self.gui_size();
let cursor = self.cursor;
let Some(ms) = self.mods.screen.as_mut() else {
return;
};
let Some((_, widgets)) = Self::mod_ui_view(&self.mods.mods, ms) else {
return;
};
let x = (w / 2.0).floor() - MOD_UI_COLUMN / 2.0;
let layout = Self::mod_ui_layout(h, widgets);
let mut list_i = 0usize;
for (w, &(wy, wh)) in widgets.iter().zip(&layout) {
let UiWidget::List(l) = w else { continue };
let over = ui::hovered(cursor, x, wy, MOD_UI_COLUMN, wh);
ms.scrolls.resize_with(list_i + 1, ui::Scroll::default);
if over {
let content = l.rows.len() as f32 * 12.0;
ms.scrolls[list_i].wheel(delta, 12.0, wy + 4.0, wy + wh - 4.0, content);
return;
}
list_i += 1;
}
}
}
#[cfg(feature = "mods")]
const MOD_UI_TOP: f32 = 40.0;
#[cfg(feature = "mods")]
const MOD_UI_COLUMN: f32 = 200.0;
+2 -1
View File
@@ -470,7 +470,8 @@ impl Game<'_> {
None => String::new(),
};
batch.text(atlas, &title, ox + 8.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
let inventory = self.translate("container.inventory", "Inventory");
batch.text(atlas, &inventory, ox + 8.0, oy + 72.0, grey, false);
if let Some(m) = self.mobs.iter().find(|m| m.id == open.mob) {
self.draw_mob_preview(
batch,
+48 -4
View File
@@ -151,10 +151,13 @@ impl Game<'_> {
.clone()
.unwrap_or_else(|| Text::literal(&name))
};
// StringDecomposer.iterateFormatted: `§` codes a server leaves
// inside the team prefix or the name itself apply at draw time.
let shown = match team {
Some(t) => t.formatted_name(member),
None => member,
};
}
.resolve_legacy();
let mut lines = Vec::new();
// EntityRenderer.extractNameTags: the score shows within the
// below-name distance (10), under the name.
@@ -162,7 +165,7 @@ impl Game<'_> {
if distance_sqr < 10.0 * 10.0
&& let Some(score) = holder.and_then(|h| self.below_name_text(&h))
{
lines.push((score, 0.0));
lines.push((score.resolve_legacy(), 0.0));
lift = f64::from(9.0f32 * 1.15 * 0.025);
}
lines.push((shown, lift));
@@ -213,14 +216,15 @@ impl Game<'_> {
let shown = match team {
Some(t) => t.formatted_name(name.clone()),
None => name.clone(),
};
}
.resolve_legacy();
let mut lines = Vec::new();
let mut lift = 0.0;
let holder = self.persist.uuids.get(&a.id).map(|u| uuid_text(*u));
if distance_sqr < 10.0 * 10.0
&& let Some(score) = holder.and_then(|h| self.below_name_text(&h))
{
lines.push((score, 0.0));
lines.push((score.resolve_legacy(), 0.0));
lift = f64::from(9.0f32 * 1.15 * 0.025);
}
lines.push((shown, lift));
@@ -236,6 +240,42 @@ impl Game<'_> {
discrete: false,
});
}
// ItemFrameRenderer.shouldShowName/getNameTag: only the targeted
// frame's custom-named item, with the HUD visible (also glow frames).
if !self.ui.hide_gui
&& let Some((i, distance)) = self.frame_hit()
&& self.before_block(distance)
&& self.mob_hit().is_none_or(|(_, d)| d > distance)
&& let Some(name) = self.item_frames[i]
.item
.as_ref()
.and_then(|item| item.custom_name())
{
let frame = &self.item_frames[i];
let (lo, hi) = frame.bounds();
let center = glam::DVec3::from_array(std::array::from_fn(|a| (lo[a] + hi[a]) / 2.0));
if center.distance_squared(camera) < 64.0 * 64.0 {
// NAME_TAG is at the entity height (0.5), then the name
// submitter lifts it 0.5. ItemFrameRenderer offsets rendering
// 0.3 toward its facing and -0.25 vertically.
let step = frame.step();
tags.push(NameTag {
at: center
+ glam::DVec3::new(
f64::from(step[0] as f32 * 0.3),
0.75,
f64::from(step[2] as f32 * 0.3),
),
lines: vec![(Text::literal(name).resolve_legacy(), 0.0)],
light: self.world.light(
center.x.floor() as i32,
center.y.floor() as i32,
center.z.floor() as i32,
),
discrete: false,
});
}
}
tags
}
/// `SubmitNodeCollection.submitNameTag`: a discrete name is drawn once,
@@ -253,12 +293,16 @@ impl Game<'_> {
const FADED: u32 = 0x7F;
for tag in self.name_tags(camera, alpha) {
let o = tag.at - camera;
// `gbuffers_entities` draws name tag text (2.3); a sneaking player's faded tag, on its
// background, blends.
if tag.discrete {
self.mark_translucent_entity(out.len(), "minecraft:name_tag");
self.name_tag_quads(o, &tag.lines, FADED, true, 0, vertex_light(tag.light), out);
continue;
}
// LightCoordsUtil.lightCoordsWithEmission(lightCoords, 2).
let lit = (tag.light >> 4).max(2) << 4 | (tag.light & 15).max(2);
self.mark_entity(out.len(), "minecraft:name_tag");
self.name_tag_quads(o, &tag.lines, 0xFF, false, 0, vertex_light(lit), out);
// RenderPipelines.TEXT_SEE_THROUGH: no depth test, no lightmap.
self.name_tag_quads(o, &tag.lines, FADED, true, 2, 0, see_through);
@@ -237,6 +237,7 @@ impl Game<'_> {
let _ = std::fs::create_dir_all(&dir);
super::packs::open_folder(&dir);
}
Event::ModSettings(i) => self.open_mod_screen(i, true),
Event::Credits => self.open_win_screen(false, super::win::Finish::Options),
}
}
@@ -246,6 +247,7 @@ impl Game<'_> {
pub(super) fn load_language(&mut self, code: &str) {
let root = self.options.resources.clone();
lang::set(lang::Language::load(&[&root], code));
self.refresh_remote_language();
self.ui.chat.rescale(&self.gui.atlas);
}
/// Settings that Horizon applies beyond render distance, volume and GUI scale.
+7
View File
@@ -142,6 +142,8 @@ impl Game<'_> {
}
let server = &self.server_packs.active;
let root = startup_root(&vanilla, &self.settings.resource_packs, server)?;
let root =
super::mods::content_root(&root, &self.settings.mods.enabled, &self.options.dev_mods);
self.reload_resources(&root)
}
fn reload_resources(&mut self, root: &Path) -> horizon_client::Result<()> {
@@ -192,6 +194,10 @@ impl Game<'_> {
let context = pack.context.clone();
self.pack = pack;
self.gui = gui;
// The atlas's sprites moved: the particle engine re-reads every rect
// and the packs' sprite sets, or every particle draws a stale region.
self.particles
.reload(root, &self.gui.atlas.sprites, &self.gui.atlas.translucent);
horizon_client::ui_theme::reset_atlas();
// Villager hats come from the pack's texture metadata (shared data, swapped in place).
*self
@@ -203,6 +209,7 @@ impl Game<'_> {
horizon_client::mobs::villager_hats::VillagerHats::load(root);
horizon_client::ui::load_metadata(root);
lang::set(lang::Language::load(&[&root.to_path_buf()], &lang::code()));
self.refresh_remote_language();
self.audio.reload(root);
self.clear_lod();
self.streaming.reload_resources(&mut self.world, context);
+4 -2
View File
@@ -921,8 +921,10 @@ impl Game<'_> {
} else if self.book.is_some() {
self.book_input(key, text);
} else if self.screen == Screen::Creative && self.creative_screen.tab().search {
if key != Some(KeyCode::Enter) {
self.creative_search_edit(text, backspace);
if backspace {
self.creative_search_backspace(false);
} else if key != Some(KeyCode::Enter) {
self.creative_search_edit(text);
}
} else if self.recipe_search_focused() {
if key != Some(KeyCode::Enter) {
+10 -2
View File
@@ -147,8 +147,16 @@ impl Game<'_> {
}
}
Species::Strider if !baby => self.spawn_strider_jockey(id, at),
// ZombieHorse.finalizeSpawn: a zombie with an iron spear.
Species::ZombieHorse if natural => {
// ZombieHorse.finalizeSpawn: a zombie with an iron spear. The rider
// comes from EntityType.create, which makes no zombie in peaceful
// (canSpawn), so a peaceful zombie horse spawns without one.
Species::ZombieHorse
if natural
&& (self.ui.difficulty != 0
|| horizon_client::mobs::spawn_rules::allowed_in_peaceful(
Species::Zombie,
)) =>
{
if let Some(zombie) = self.spawn_mob("minecraft:zombie", at, false) {
if let Some(z) = self.mobs.iter_mut().find(|m| m.id == zombie) {
z.extra.main_hand = Some("minecraft:iron_spear".into());
@@ -412,7 +412,8 @@ impl Game<'_> {
}
/// Whether the player's own model shows in the world view.
fn player_model_shown(&self) -> bool {
!self.camera_type.first_person()
// A shader pack's shadow pass draws the player in first person too (shadowPlayer).
(!self.camera_type.first_person() || self.pack_shadow_casters.1)
&& self.sleeping.is_none()
&& !self.spectator()
&& self.potions.effects.get("minecraft:invisibility").is_none()
+1 -1
View File
@@ -755,7 +755,7 @@ impl Game<'_> {
image_width,
&self.potions.effects.list,
self.clock.rate(),
&|key| self.pack.names.get(key).map(str::to_owned),
&|key| self.pack.names.display_get(key),
&|text| self.gui.atlas.font.width(text).ceil() as i32,
);
if let Some(lines) = inventory_effects::paint(
+17 -6
View File
@@ -502,7 +502,7 @@ impl Game<'_> {
horizon_client::item_tooltip::lines(
stack,
self.res.items().get(&stack.item),
&|k| self.pack.names.get(k).map(str::to_owned),
&|k| self.pack.names.display_get(k),
)
})
{
@@ -1163,8 +1163,12 @@ impl Game<'_> {
}
/// Paints recipe book calls; returns the first tooltip set (vanilla keeps
/// the first one a frame asks for).
fn paint_book(&mut self, batch: &mut HudBatch, calls: &[Drawn]) -> Option<Vec<(String, u32)>> {
let mut tooltip: Option<Vec<(String, u32)>> = None;
fn paint_book(
&mut self,
batch: &mut HudBatch,
calls: &[Drawn],
) -> Option<Vec<(horizon_client::text::Text, u32)>> {
let mut tooltip: Option<Vec<(horizon_client::text::Text, u32)>> = None;
for d in calls {
let start = batch.vertices.len();
let atlas = &self.gui.atlas;
@@ -1259,7 +1263,14 @@ impl Game<'_> {
tooltip = Some(
lines
.iter()
.map(|l| (l.iter().map(|r| r.text.as_str()).collect(), u32::MAX))
.map(|l| {
(
horizon_client::text::Text::literal(
l.iter().map(|r| r.text.as_str()).collect::<String>(),
),
u32::MAX,
)
})
.collect(),
);
}
@@ -1269,10 +1280,10 @@ impl Game<'_> {
let mut lines = self.stack_tooltip(stack);
if *more {
lines.push((
self.translate(
horizon_client::text::Text::literal(self.translate(
"gui.recipebook.moreRecipes",
"Right Click for More",
),
)),
u32::MAX,
));
}
+283 -308
View File
@@ -58,6 +58,12 @@ fn remote_text(tag: &Tag) -> horizon_client::text::Text {
comp_text(&tag_to_json(tag))
}
/// `ClientboundOpenScreenPacket.title` as a container screen draws it: the
/// component's styles, and the `§` codes a literal holds (`StringDecomposer`).
fn menu_title(tag: &Tag) -> horizon_client::text::Text {
remote_text(tag).resolve_legacy()
}
/// A section's sky and block light layers from the wire.
type LightLayers = (Option<Vec<u8>>, Option<Vec<u8>>);
@@ -123,6 +129,9 @@ pub(super) struct Remote {
loaded_sent: bool,
/// The view distance last sent in ClientInformation.
sent_view: i8,
/// The Chat option's visibility last sent in ClientInformation
/// (`Options.broadcastOptions` sends it again when it changes).
sent_chat_visibility: i32,
/// BlockStatePredictionHandler: blocks changed ahead of the server (a predicted break),
/// with the sequence of the last action that changed them and the state the server
/// last said they have. Until the server acknowledges that sequence its block updates
@@ -130,8 +139,8 @@ pub(super) struct Remote {
predictions: HashMap<[i32; 3], (i32, i32)>,
/// Open container: (window id, menu name).
pub(super) menu: Option<(i32, String)>,
/// The open menu's title as the server named it.
pub(super) menu_title: Option<String>,
/// The open menu's title as the server named it, with its styles.
pub(super) menu_title: Option<horizon_client::text::Text>,
state_id: i32,
use_target: Option<[i32; 3]>,
entities: HashMap<i32, Tracked>,
@@ -223,30 +232,6 @@ fn face_direction(face: [i32; 3]) -> u8 {
}
}
/// A `minecraft:profile` component as the item data JSON the model reads.
fn profile_tag(p: &horizon_protocol::item::Profile) -> Tag {
let properties = p
.properties
.iter()
.map(|(name, value, signature)| {
let mut entries: Vec<(&'static str, Tag)> = vec![
("name", Tag::String(name.as_str().into())),
("value", Tag::String(value.as_str().into())),
];
if let Some(signature) = signature {
entries.push(("signature", Tag::String(signature.as_str().into())));
}
Tag::compound(entries)
})
.collect::<Vec<_>>();
let mut entries: Vec<(&'static str, Tag)> = Vec::new();
if let Some(name) = &p.name {
entries.push(("name", Tag::String(name.as_str().into())));
}
entries.push(("properties", Tag::List(properties)));
Tag::compound(entries)
}
/// A protocol number format as the scoreboard's.
fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFormat {
use horizon_client::scoreboard::{NumberFormat, tag_to_json};
@@ -258,6 +243,22 @@ fn number_format(f: &play::NumberFormat) -> horizon_client::scoreboard::NumberFo
}
impl Game<'_> {
/// A `Holder<SoundEvent>` off the wire: an inline event's location, or
/// the name of a registered one.
pub(super) fn remote_sound_name(
&self,
sound: &(i32, Option<(String, Option<f32>)>),
) -> Option<String> {
match &sound.1 {
Some((location, _)) => Some(location.clone()),
None => self.remote.as_ref().and_then(|r| {
r.builtin
.get("minecraft:sound_event")?
.name(sound.0)
.map(str::to_owned)
}),
}
}
/// Leave the title for a server (ConnectScreen): an empty world fed by the connection.
pub(super) fn connect_server(&mut self, address: &str, name: &str) -> Result<()> {
self.connect_server_with_cookies(address, name, None)
@@ -430,6 +431,7 @@ impl Game<'_> {
abilities: None,
loaded_sent: false,
sent_view: view,
sent_chat_visibility: self.settings.chat_visibility as i32,
predictions: HashMap::new(),
menu: None,
menu_title: None,
@@ -497,6 +499,7 @@ impl Game<'_> {
r.session.disconnect();
}
self.server_packs_disconnect();
self.close_dialogs();
// Single player's server thread saves the world before the title shows.
let single_player = match self.integrated.take() {
Some(server) => {
@@ -610,198 +613,51 @@ impl Game<'_> {
.and_then(|i| i.id(name))
.unwrap_or(0)
}
/// A stack from the server, decoded as the saved and command item NBT
/// are, so tooltips and models see every field.
pub(super) fn to_stack(&self, s: &Option<Stack>) -> Option<ItemStack> {
let s = s.as_ref()?;
let mut out = ItemStack {
item: self.item_name(s.item),
count: s.count.max(0) as u32,
damage: 0,
extra: None,
};
// A vanilla `components` compound, then the same decoder the saved
// and command item NBT use, so tooltips and models see every field.
let components = self.protocol_components(s);
let (damage, data) = horizon_client::item_data::decode_components(components.as_ref());
out.damage = damage;
if let Some(data) = data {
*out.data_mut() = *data;
}
out.tidy();
Some(out)
}
/// The item's patched components as vanilla's `components` compound.
fn protocol_components(&self, s: &Stack) -> Option<Tag> {
use horizon_protocol::item::{Component, component};
let r = self.remote.as_ref()?;
let name = |id: i32| r.builtin.get("minecraft:data_component_type")?.name(id);
let mut entries: Vec<(&str, Tag)> = Vec::new();
for (kind, c) in &s.added {
let Some(key) = name(*kind) else {
continue;
};
let value = match c {
// Read past, not decoded: the item keeps its prototype's value.
Component::Raw(_) => continue,
// Trim materials and patterns are synced registries, as enchantments are.
Component::Trim { material, pattern } => {
let (Some(material), Some(pattern)) = (
r.registries.name("minecraft:trim_material", *material),
r.registries.name("minecraft:trim_pattern", *pattern),
) else {
continue;
};
Tag::compound([
("material", Tag::String(material.into())),
("pattern", Tag::String(pattern.into())),
])
}
Component::Int(v) if *kind == component::RARITY => {
let rarity = ["common", "uncommon", "rare", "epic"];
Tag::String(rarity.get(*v as usize).copied().unwrap_or("common").into())
}
Component::Int(v) => Tag::Int(*v),
Component::Unit => Tag::Compound(Default::default()),
Component::Bool(v) => Tag::Byte(i8::from(*v)),
Component::Text(t) | Component::Nbt(t) => t.clone(),
Component::Ident(v) => Tag::String(v.as_str().into()),
Component::Lore(lines) => Tag::List(lines.clone()),
Component::WritableBook(pages) => Tag::compound([(
"pages",
Tag::List(
pages
.iter()
.map(|p| Tag::String(p.as_str().into()))
.collect(),
),
)]),
Component::WrittenBook(b) => Tag::compound([
("title", Tag::String(b.title.as_str().into())),
("author", Tag::String(b.author.as_str().into())),
("generation", Tag::Int(b.generation)),
("pages", Tag::List(b.pages.clone())),
("resolved", Tag::Byte(i8::from(b.resolved))),
]),
Component::Enchantments(list) => {
// Enchantments are a synced (data-driven) registry: the
// ids index the server's RegistryData, not the builtin
// report, so a datapack enchantment names correctly.
let levels = list.iter().filter_map(|(id, level)| {
let name = r.registries.name("minecraft:enchantment", *id)?;
Some((name, Tag::Int(*level)))
});
Tag::compound(levels)
}
Component::AttackRange(v) => Tag::compound([
("min_reach", Tag::Float(v[0].to_bits())),
("max_reach", Tag::Float(v[1].to_bits())),
("min_attack_momentum", Tag::Float(v[2].to_bits())),
("max_attack_momentum", Tag::Float(v[3].to_bits())),
("hitbox_margin", Tag::Float(v[4].to_bits())),
("mob_factor", Tag::Float(v[5].to_bits())),
]),
Component::Profile(p) => profile_tag(p),
// PotionContents' NBT: the potion by name and the custom colour.
Component::Potion { potion, color, .. } => {
let potion = potion.and_then(|id| r.builtin.get("minecraft:potion")?.name(id));
Tag::compound(
potion
.map(|name| ("potion", Tag::String(name.into())))
.into_iter()
.chain(color.map(|c| ("custom_color", Tag::Int(c)))),
)
}
// ItemStackTemplate.CODEC: id, count and components.
Component::Stacks(stacks) => Tag::List(
stacks
.iter()
.map(|t| {
let mut entries = vec![
("id", Tag::String(self.item_name(t.item).as_ref().into())),
("count", Tag::Int(t.count)),
];
if let Some(c) = self.protocol_components(t) {
entries.push(("components", c));
}
Tag::compound(entries)
})
.collect(),
),
Component::CustomModelData {
floats,
flags,
strings,
colors,
} => Tag::compound([
(
"floats",
Tag::List(floats.iter().map(|f| Tag::Float(f.to_bits())).collect()),
),
(
"flags",
Tag::List(flags.iter().map(|b| Tag::Byte(i8::from(*b))).collect()),
),
(
"strings",
Tag::List(
strings
.iter()
.map(|s| Tag::String(s.as_str().into()))
.collect(),
),
),
(
"colors",
Tag::List(colors.iter().map(|c| Tag::Int(*c)).collect()),
),
]),
Component::TooltipDisplay { hide, hidden } => {
let hidden = hidden
.iter()
.filter_map(|id| Some(Tag::String(name(*id)?.into())));
Tag::compound([
("hide_tooltip", Tag::Byte(i8::from(*hide))),
("hidden_components", Tag::List(hidden.collect())),
])
}
};
entries.push((key, value));
}
Some(Tag::compound(entries))
Some(horizon_client::item_sync::from_network(
s.as_ref()?,
&r.builtin,
&r.registries,
))
}
/// A stack to the server (`SetCreativeModeSlot`): the same component
/// patch a Horizon server sends its clients, with the registries' ids, so
/// the server's echo doesn't hand back a bare item.
fn to_network(&self, s: &Option<ItemStack>) -> Option<Stack> {
let s = s.as_ref()?;
let mut stack = Stack::new(self.item_id(&s.item), s.count as i32);
// A creative pick keeps its potion (PotionContents by its builtin id).
if let Some(id) = s.potion().and_then(|p| {
let potions = self.remote.as_ref()?.builtin.get("minecraft:potion")?;
potions.id(&horizon_world::datafix::dynamic::namespaced(p))
}) {
stack.added.push((
horizon_protocol::item::component::POTION_CONTENTS,
horizon_protocol::item::Component::Potion {
potion: Some(id),
color: None,
rest: Vec::new(),
},
));
}
if s.damage > 0 {
stack.added.push((
horizon_protocol::item::component::DAMAGE,
horizon_protocol::item::Component::Int(s.damage as i32),
));
}
Some(stack)
let r = self.remote.as_ref()?;
horizon_client::lan::guest::stack_to_network(
|name| self.item_id(name),
// Built-in first, as a hub's `SyncData::id` does: potions are one.
|registry, name| {
r.builtin
.get(registry)
.and_then(|ids| ids.id(name))
.or_else(|| r.registries.id(registry, name))
},
s,
)
}
/// A line in the connection's chat, with its styles, click and hover
/// events (ChatComponent.addMessage).
pub(super) fn chat_line(&mut self, content: horizon_client::text::Text) {
/// events (ChatComponent.addMessage). The lines the Chat option hides
/// are dropped there (its `visibleMessageFilter`).
pub(super) fn chat_line(
&mut self,
content: horizon_client::text::Text,
source: horizon_client::chat::ChatSource,
) {
if !self.ui.chat.shows(source) {
return;
}
let text = content.plain();
log::info!("[chat] {text}");
self.ui.chat.add(
&self.gui.atlas,
content,
None,
source,
self.ticks,
self.screen == Screen::Chat,
);
@@ -864,6 +720,23 @@ impl Game<'_> {
pub(super) fn remote_backlog(&self) -> usize {
self.remote.as_ref().map_or(0, |r| r.backlog.len())
}
/// A headless command oracle has a real connection but no movement tick.
/// Acknowledge loaded terrain without predicting or sending movement.
pub(super) fn poll_stationary_client(&mut self) -> Result<()> {
self.poll_remote()?;
let loaded = self.player.as_ref().is_some_and(|p| {
self.streaming.is_lit(
(p.position.x.floor() as i32) >> 4,
(p.position.z.floor() as i32) >> 4,
)
});
if loaded && self.remote.as_ref().is_some_and(|r| !r.loaded_sent) {
self.send(S::PlayerLoaded(Empty));
self.remote.as_mut().unwrap().loaded_sent = true;
}
Ok(())
}
/// Process what the network thread received (once per frame, like the
/// client's packet processor), in order. Chunk packets get
/// `CHUNK_PACKETS_PER_FRAME`: once a frame has spent it, the events from
@@ -900,6 +773,8 @@ impl Game<'_> {
} => {
self.set_registries(registries);
self.extras_joined();
// handleLogin: the level loading screen replaces any dialog.
self.close_dialogs();
if let Some(r) = self.remote.as_mut() {
r.joined = true;
r.profile = uuid;
@@ -928,6 +803,8 @@ impl Game<'_> {
}
Event::PackPush(p) => self.handle_pack_push(p),
Event::PackPop(id) => self.handle_pack_pop(id),
Event::ShowDialog(dialog) => self.show_dialog(&dialog),
Event::ClearDialog => self.clear_dialog(),
Event::DecodeError(e) => {
if let Some(r) = self.remote.as_mut() {
r.decode_errors += 1;
@@ -1566,13 +1443,29 @@ impl Game<'_> {
m.on_ground = on_ground;
return;
}
if let Some(p) = self.creatures.projectiles.iter_mut().find(|p| {
p.id == id as u32
&& matches!(
p.kind,
horizon_client::projectiles::ProjectileKind::LargeFireball { .. }
)
}) {
if path.is_some() {
p.position = Vec3::new(position[0], position[1], position[2]);
}
if let Some((yaw, pitch)) = rotation {
p.yaw = yaw;
p.pitch = pitch;
}
return;
}
if let Some(p) = r.pending_items.get_mut(&id) {
p.0 = position;
}
// ItemEntity and FallingBlockEntity keep Entity's NO_OP
// InterpolationHandler: moveOrInterpolateTo puts them there at
// once, and their own tick moves them on between the server's
// updates (`tick_remote_entities`).
// ItemEntity, FallingBlockEntity and PrimedTnt keep Entity's
// NO_OP InterpolationHandler: moveOrInterpolateTo puts them there
// at once, and their own tick moves them on between the server's
// updates (`tick_remote_entities`, `tick_remote_projectiles`).
let at = Vec3::new(position[0], position[1], position[2]);
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
d.position = at;
@@ -1583,6 +1476,11 @@ impl Game<'_> {
f.position = at;
return;
}
if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id as u32) {
t.position = at;
t.on_ground = on_ground;
return;
}
// AbstractInterpolationHandler.interpolateTo: without a rotation,
// the one it was heading for.
let rotation = rotation.or_else(|| r.lerps.get(&id).and_then(|l| l.rotation));
@@ -1776,9 +1674,10 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.sent_view = view;
}
self.send(S::ClientInformation(
horizon_protocol::packets::configuration::ClientInformation::new(view),
));
let mut info =
horizon_protocol::packets::configuration::ClientInformation::new(view);
info.chat_visibility = self.settings.chat_visibility as i32;
self.send(S::ClientInformation(info));
}
C::Respawn(p) => {
// A new player, without effects: the server sends them again.
@@ -1890,20 +1789,14 @@ impl Game<'_> {
// ClientLevel.levelEvent: LevelEventHandler, as this client's own
// level plays them (particles and sounds: a spawner's burst, bone
// meal, waxing, a block broken by someone else).
// ClientPacketListener.handleLevelEvent: a global one is heard
// from anywhere (ClientLevel.globalLevelEvent).
C::LevelEvent(p) if p.global => self.global_level_event_sound(p.kind, p.pos),
C::LevelEvent(p) => self.level_event_at(p.kind, p.pos, p.data),
C::LevelParticles(p) => self.remote_level_particles(&p),
C::Explode(p) => self.remote_explode(&p),
C::Sound(p) => {
let name = match &p.sound.1 {
Some((location, _)) => Some(location.clone()),
None => self.remote.as_ref().and_then(|r| {
r.builtin
.get("minecraft:sound_event")?
.name(p.sound.0)
.map(str::to_owned)
}),
};
if let Some(name) = name {
if let Some(name) = self.remote_sound_name(&p.sound) {
let at = [
f64::from(p.x) / 8.0,
f64::from(p.y) / 8.0,
@@ -2084,25 +1977,16 @@ impl Game<'_> {
}
}
}
// LivingEntity.onSyncedDataUpdated(DATA_LIVING_ENTITY_FLAGS):
// another player starts using the item in a hand (eating, a
// bow drawn, a shield up), or stops.
let other = self
.remote
.as_ref()
.is_some_and(|r| r.level_players.contains_key(&p.id) && r.entity_id != p.id);
if other && let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32) {
for (index, _, value) in &p.values {
if let (8, Value::Byte(flags)) = (index, value) {
m.extra.using_off_hand = flags & 2 != 0;
if flags & 1 == 0 {
m.extra.using_item = 0;
} else if m.extra.using_item == 0 {
m.extra.using_item = 1;
}
}
}
}
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: for another player
// too, remote_mob_data's apply reads index 8 above.
let mannequin = self
.mobs
.iter()
.any(|m| m.id == p.id as u32 && &*m.kind.id == "minecraft:mannequin");
let other = mannequin
|| self.remote.as_ref().is_some_and(|r| {
r.level_players.contains_key(&p.id) && r.entity_id != p.id
});
// LivingEntity.onSyncedDataUpdated(SLEEPING_POS_ID): another
// player lies down in their bed (drawn lying in it), or gets up.
if other {
@@ -2153,11 +2037,13 @@ impl Game<'_> {
}
}
// Entity.DATA_SHARED_FLAGS_ID's crouching bit: another
// player's crouch (their model and Entity.isDiscrete's name tag).
if self
.remote
.as_ref()
.is_some_and(|r| r.level_players.contains_key(&p.id))
// player's or a mannequin's crouch (their model and
// Entity.isDiscrete's name tag).
if (mannequin
|| self
.remote
.as_ref()
.is_some_and(|r| r.level_players.contains_key(&p.id)))
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
{
for (index, _, value) in &p.values {
@@ -2352,12 +2238,10 @@ impl Game<'_> {
}
}
C::PlayerCombatKill(p) => {
let lang = self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default();
let message = plain(&p.message, &lang);
// The component resolves in the client's current language, as
// the chat line does, not in the language the session joined
// with (`Remote.lang` is the vanilla server-language table).
let message = remote_text(&p.message).plain();
let me = self.remote.as_ref().is_some_and(|r| r.entity_id == p.id);
if let Some(r) = self.remote.as_mut() {
r.death_message = Some(message);
@@ -2560,6 +2444,17 @@ impl Game<'_> {
if let Some(r) = self.remote.as_mut() {
r.commands = Some(tree);
}
self.merge_remote_tree();
}
C::Cooldown(p) => {
// ClientPacketListener.handleItemCooldown: the server starts
// (or confirms) a group's cooldown; 0 ends it.
let group: Arc<str> = Arc::from(p.group.as_str());
if p.duration == 0 {
self.cooldowns.remove(&group);
} else {
self.cooldowns.add(group, p.duration);
}
}
C::SystemChat(p) => {
// The component as sent, translated in the client's own
@@ -2568,7 +2463,7 @@ impl Game<'_> {
if p.overlay {
self.titles.set_overlay(text, false);
} else {
self.chat_line(text);
self.chat_line(text, horizon_client::chat::ChatSource::Server);
}
}
C::PlayerChat(p) => {
@@ -2578,12 +2473,12 @@ impl Game<'_> {
.as_ref()
.map_or_else(|| serde_json::Value::from(p.content.as_str()), tag_to_json);
let line = self.format_chat(&p.chat_type, content);
self.chat_line(line);
self.chat_line(line, horizon_client::chat::ChatSource::Player);
}
C::DisguisedChat(p) => {
let content = horizon_client::scoreboard::tag_to_json(&p.message);
let line = self.format_chat(&p.chat_type, content);
self.chat_line(line);
self.chat_line(line, horizon_client::chat::ChatSource::Player);
}
C::PlayerInfoUpdate(p) => {
if let Some(r) = self.remote.as_mut() {
@@ -2798,6 +2693,9 @@ impl Game<'_> {
C::SetTitleText(p) => self.titles.set_title(remote_text(&p.text)),
C::SetSubtitleText(p) => self.titles.set_subtitle(remote_text(&p.text)),
C::SetTitlesAnimation(p) => self.titles.set_times(p.fade_in, p.stay, p.fade_out),
// ClientCommonPacketListenerImpl.handleShowDialog / handleClearDialog.
C::ShowDialog(p) => self.show_play_dialog(&p.dialog),
C::ClearDialog(_) => self.clear_dialog(),
C::ClearTitles(p) => {
self.titles.clear();
if p.value {
@@ -2975,6 +2873,53 @@ impl Game<'_> {
{
mob.skin = Some(skin);
}
// ClientMannequin.updateSkin (PlayerSkinRenderCache.lookup): a
// mannequin's DATA_PROFILE `textures` property resolves like a
// player's, never required to be signed.
let mannequins: Vec<(u32, horizon_client::skins::Textures)> = self
.mobs
.iter()
.filter(|m| &*m.kind.id == "minecraft:mannequin" && m.profile.is_some())
.map(|m| {
let t = m
.profile
.as_ref()
.and_then(|p| p.properties.iter().find(|p| p.name == "textures"));
let textures = t.map_or_else(Default::default, |t| {
let signature = if t.signature.is_some() {
horizon_client::skins::Signature::Signed
} else {
horizon_client::skins::Signature::Unsigned
};
horizon_client::skins::unpack(
&t.value,
signature,
&horizon_client::skins::TEXTURE_URIS,
)
});
(m.id, textures)
})
.collect();
let mut resolved: Vec<(u32, Option<String>)> = Vec::new();
for (id, textures) in mannequins {
let skin = {
let mut downloads = self.skin_downloads.borrow_mut();
horizon_client::skins::lookup(&textures, false, |kind, url| {
downloads.state(kind, url)
})
};
resolved.push((id, skin));
}
for (id, skin) in resolved {
let skin = skin.filter(|s| !s.starts_with("skins/") || self.show_skin(s));
if let Some(mob) = self
.mobs
.iter_mut()
.find(|m| m.id == id && &*m.kind.id == "minecraft:mannequin")
{
mob.skin = skin;
}
}
}
/// Puts a downloaded skin in an atlas skin slot: a free one, else the
/// least recently shown.
@@ -3096,14 +3041,23 @@ impl Game<'_> {
});
}
/// `Entity.lerpMotion` (and `recreateFromPacket`'s motion) for the
/// entities whose own tick moves them on a client: dropped items and
/// falling blocks.
/// entities whose own tick moves them on a client: dropped items, falling
/// blocks and primed TNT.
fn remote_motion(&mut self, id: i32, velocity: [f64; 3]) {
let v = Vec3::new(velocity[0], velocity[1], velocity[2]);
if let Some(d) = self.dropped.iter_mut().find(|d| d.id == id as u32) {
d.velocity = v;
} else if let Some(f) = self.falling.iter_mut().find(|f| f.id == id as u32) {
f.velocity = v;
} else if let Some(t) = self.tnts.iter_mut().find(|t| t.id == id as u32) {
t.velocity = v;
} else if let Some(p) = self
.creatures
.projectiles
.iter_mut()
.find(|p| p.id == id as u32)
{
p.velocity = v;
} else if let Some(p) = self
.remote
.as_mut()
@@ -3216,16 +3170,19 @@ impl Game<'_> {
fn tick_remote_level(&mut self) -> Result<()> {
self.ticks += 1;
self.track_experience_display();
// Options.broadcastOptions: a changed render distance is sent again.
// Options.broadcastOptions: a changed render distance or Chat option
// is sent again.
let view = client_view_distance(self.settings.render_distance);
let visibility = self.settings.chat_visibility as i32;
if let Some(r) = self.remote.as_mut()
&& r.joined
&& r.sent_view != view
&& (r.sent_view != view || r.sent_chat_visibility != visibility)
{
r.sent_view = view;
self.send(S::ClientInformation(
horizon_protocol::packets::configuration::ClientInformation::new(view),
));
r.sent_chat_visibility = visibility;
let mut info = horizon_protocol::packets::configuration::ClientInformation::new(view);
info.chat_visibility = visibility;
self.send(S::ClientInformation(info));
}
// Minecraft.tick: TickRateManager.tick; ClientLevel.tickTime advances
// the time only while the level runs normally.
@@ -3254,6 +3211,7 @@ impl Game<'_> {
self.tick_block_entity_anims();
self.tick_hand();
self.tick_particles();
self.tick_client_ambient();
self.tick_client_effects();
// Player.tick's sleep counter (the darkening and the wake-up fade).
self.sleep_timer = super::tick_sleep_timer(self.sleep_timer, self.sleeping.is_some());
@@ -3587,25 +3545,32 @@ impl Game<'_> {
m.head_yaw += wrap_degrees(*yaw - m.head_yaw) / *steps as f32;
*steps -= 1;
}
// LivingEntity.updatingUsingItem for another player: the ticks the
// item has been used before this one.
if player && m.extra.using_item > 0 {
let item = if m.extra.using_off_hand {
m.extra.off_hand.clone()
} else {
m.extra.main_hand.clone()
};
if let Some(item) = item {
let eye = if m.extra.crouching { 1.27 } else { 1.62 };
let at = [m.position.x, m.position.y, m.position.z];
using.push((
item,
m.extra.using_item as u32 - 1,
at,
eye,
m.head_pitch,
m.yaw,
));
// Chicken.aiStep: the wings follow the server's on-ground flag.
if m.species() == horizon_client::mobs::Species::Chicken {
horizon_client::mobs::farm::chicken_flap(m);
}
// LivingEntity.updatingUsingItem: the ticks the item has been
// used before this one. Another player's use particles; a mob's
// drawn bow only needs the count (its pull follows it).
if m.extra.using_item > 0 {
if player {
let item = if m.extra.using_off_hand {
m.extra.off_hand.clone()
} else {
m.extra.main_hand.clone()
};
if let Some(item) = item {
let eye = if m.extra.crouching { 1.27 } else { 1.62 };
let at = [m.position.x, m.position.y, m.position.z];
using.push((
item,
m.extra.using_item as u32 - 1,
at,
eye,
m.head_pitch,
m.yaw,
));
}
}
m.extra.using_item += 1;
}
@@ -4303,8 +4268,12 @@ impl Game<'_> {
let Some(info) = self.res.items().get(&held.item).cloned() else {
return false;
};
// MultiPlayerGameMode.useItem runs the use here too: food starts
// being eaten (Consumable.startConsuming), a book and quill opens.
// MultiPlayerGameMode.useItem runs the use here too (inside
// startPrediction): the `use_cooldown` component starts its entry, and
// the server's ClientboundCooldownPacket confirms it.
self.apply_use_cooldown(&held);
// Food starts being eaten (Consumable.startConsuming), a book and
// quill opens.
self.with_hand(hand, |g| g.start_eating(&info));
if self.with_hand(hand, |g| g.remote_use_book(&held)) {
return true;
@@ -4643,10 +4612,12 @@ impl Game<'_> {
_ => Ok(false),
}
}
/// ClientPacketListener.sendChat / sendCommand (unsigned).
/// ClientPacketListener.sendChat / sendCommand (unsigned). The Chat
/// option's Hidden and System levels keep chat out and Hidden keeps the
/// commands out (ChatAbilities).
pub(super) fn send_chat(&mut self, message: &str) {
let message = message.trim();
if message.is_empty() {
if message.is_empty() || !self.chat_abilities().allows(message) {
return;
}
if let Some(command) = message.strip_prefix('/') {
@@ -4961,14 +4932,7 @@ impl Game<'_> {
return;
}
if let Some(kind) = Self::remote_station_kind(&menu) {
let title = plain(
&p.title,
&self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default(),
);
let title = menu_title(&p.title);
let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]);
self.remote_open_station(p.container, menu, kind, title, pos);
return;
@@ -5002,6 +4966,7 @@ impl Game<'_> {
cooking_timer: 0,
cooking_total: 0,
speed: 1.0,
recipes_used: std::collections::HashMap::new(),
}))
}
// HopperMenu, and DispenserMenu (MenuType.GENERIC_3x3: dispensers
@@ -5026,20 +4991,16 @@ impl Game<'_> {
self.send(S::ContainerClose(play::ContainerClose {
container: p.container,
}));
self.chat_line(horizon_client::text::Text::literal(format!(
"(Horizon cannot show {menu} screens yet)"
)));
self.chat_line(
horizon_client::text::Text::literal(format!(
"(Horizon cannot show {menu} screens yet)"
)),
horizon_client::chat::ChatSource::Client,
);
return;
}
};
let title = plain(
&p.title,
&self
.remote
.as_ref()
.map(|r| r.lang.clone())
.unwrap_or_default(),
);
let title = menu_title(&p.title);
if let Some(r) = self.remote.as_mut() {
r.menu = Some((p.container, menu.clone()));
r.menu_title = Some(title);
@@ -5083,11 +5044,20 @@ impl Game<'_> {
Some(self.remote.as_ref()?.menu.as_ref()?.1.as_str())
}
/// The title the server gave the menu it opened.
pub(super) fn remote_menu_title(&self) -> Option<String> {
pub(super) fn remote_menu_title(&self) -> Option<horizon_client::text::Text> {
self.remote.as_ref()?.menu_title.clone()
}
/// A language change reaches the server-sent components too: their titles
/// are resolved when the packet arrives, with the session's language.
pub(super) fn refresh_remote_language(&mut self) {
if let Some(lang) = horizon_client::lang::current()
&& let Some(r) = self.remote.as_mut()
{
r.lang = Arc::new(lang.map().clone());
}
}
/// A server's chest-like menu (`MenuType.GENERIC_9xN`): its rows and title.
pub(super) fn remote_chest_menu(&self) -> Option<(usize, String)> {
pub(super) fn remote_chest_menu(&self) -> Option<(usize, horizon_client::text::Text)> {
let r = self.remote.as_ref()?;
let rows = r
.menu
@@ -5096,7 +5066,12 @@ impl Game<'_> {
.strip_prefix("minecraft:generic_9x")?
.parse()
.ok()?;
Some((rows, r.menu_title.clone().unwrap_or_default()))
Some((
rows,
r.menu_title
.clone()
.unwrap_or_else(horizon_client::text::Text::empty),
))
}
/// ServerboundPlayerCommandPacket STOP_SLEEPING.
pub(super) fn remote_stop_sleeping(&mut self) {
@@ -20,6 +20,17 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
// client, which draws the flames. A client doesn't count the
// fire down: the flag goes off when the server's fire is out.
(0, Value::Byte(flags)) => m.fire_ticks = i32::from(flags & 1),
// LivingEntity.DATA_LIVING_ENTITY_FLAGS: using an item 1, in the
// off hand 2. The flag starts and stops the use; the client ticks
// the count itself (a bow's pull follows it).
(8, Value::Byte(flags)) => {
m.extra.using_off_hand = flags & 2 != 0;
if flags & 1 == 0 {
m.extra.using_item = 0;
} else if m.extra.using_item == 0 {
m.extra.using_item = 1;
}
}
// LivingEntity.DATA_HEALTH_ID: the boss bars and the death
// animation follow it.
(9, Value::Float(health)) => m.health = *health,
@@ -53,10 +64,22 @@ fn apply(m: &mut Mob, values: &[(u8, i32, Value)], builtin: &Builtin) {
(Species::Slime | Species::MagmaCube, 18, Value::Int(size)) => {
m.extra.size = (*size).clamp(1, 127);
}
// Pillager.IS_CHARGING_CROSSBOW: the charge pose (Raider's
// IS_CELEBRATING takes 16).
(Species::Pillager, 17, Value::Bool(charging)) => m.extra.flag = *charging,
// SpellcasterIllager.DATA_SPELL_CASTING_ID: the casting pose.
(Species::Evoker | Species::Illusioner, 17, Value::Byte(spell)) => {
m.extra.variant2 = (*spell).max(0) as u8;
}
// Villager.DATA_VILLAGER_DATA and ZombieVillager's (after
// Zombie's three): what VillagerProfessionLayer draws.
(Species::Villager, 19, Value::Ids(data))
| (Species::ZombieVillager, 20, Value::Ids(data)) => villager_data(m, data, builtin),
// Mannequin.DATA_PROFILE (after Avatar's two): whose skin it
// wears; update_remote_skins resolves it like a tab player's.
(Species::Mannequin, 17, Value::Profile(profile)) => {
m.profile = Some(profile.clone());
}
_ => {}
}
}
@@ -239,4 +262,60 @@ mod tests {
);
assert_eq!(name(&z), ("desert", "farmer", 3));
}
#[test]
fn the_mob_flags_drive_the_aggressive_poses() {
let Some(mut m) = mob("minecraft:skeleton") else {
return;
};
apply(&mut m, &[(15, s::BYTE, Value::Byte(2 | 4))]);
assert!(m.ai.aggressive && m.extra.left_handed && !m.no_ai);
apply(&mut m, &[(15, s::BYTE, Value::Byte(0))]);
assert!(!m.ai.aggressive && !m.extra.left_handed);
}
#[test]
fn the_living_flags_start_and_stop_a_mob_using_an_item() {
let Some(mut m) = mob("minecraft:skeleton") else {
return;
};
apply(&mut m, &[(8, s::BYTE, Value::Byte(1))]);
assert_eq!(m.extra.using_item, 1);
assert!(!m.extra.using_off_hand);
// Using in the off hand.
apply(&mut m, &[(8, s::BYTE, Value::Byte(3))]);
assert!(m.extra.using_off_hand);
apply(&mut m, &[(8, s::BYTE, Value::Byte(0))]);
assert_eq!(m.extra.using_item, 0);
}
#[test]
fn a_pillager_charges_and_a_spellcaster_casts() {
let Some(mut p) = mob("minecraft:pillager") else {
return;
};
apply(&mut p, &[(17, s::BOOLEAN, Value::Bool(true))]);
assert!(p.extra.flag);
let mut e = mob("minecraft:evoker").unwrap();
apply(&mut e, &[(17, s::BYTE, Value::Byte(2))]);
assert_eq!(e.extra.variant2, 2);
}
#[test]
fn a_mannequin_exists_and_takes_its_profile() {
let Some(mut m) = mob("minecraft:mannequin") else {
return;
};
assert_eq!(&*m.kind.id, "minecraft:mannequin");
let profile = horizon_protocol::entity_data::Profile {
name: Some("Gommunity".into()),
uuid: Some(1),
..Default::default()
};
apply(
&mut m,
&[(17, s::RESOLVABLE_PROFILE, Value::Profile(profile.clone()))],
);
assert_eq!(m.profile, Some(profile));
}
}
@@ -2,7 +2,7 @@
//! end crystals on a server's client (`ClientPacketListener.handleAddEntity`
//! and `handleSetEntityData`): the server simulates them, the client draws
//! them where it says and interpolates their moves.
use super::{FallStep, FallingBlock, Game};
use super::{FallStep, FallingBlock, Game, fireworks::fireworks_of, view_vector};
use horizon_client::projectiles::{Projectile, ProjectileKind};
use horizon_core::{geometry::Vec3, position::BlockPos};
use horizon_protocol::entity_data::Value;
@@ -125,6 +125,37 @@ impl Game<'_> {
pub(super) fn remote_projectile_data(&mut self, id: i32, values: &[(u8, i32, Value)]) {
let id = id as u32;
self.remote_hook_data(id, values);
if self.rockets.iter().any(|r| r.id == id) {
for (index, _, value) in values {
match (index, value) {
// FireworkRocketEntity.DATA_ID_FIREWORKS_ITEM: its
// explosions for `createFireworks`.
(8, Value::Item(stack)) => {
if let Some(stack) = self.to_stack(stack)
&& let Some(r) = self.rockets.iter_mut().find(|r| r.id == id)
{
let (_, explosions) = fireworks_of(&stack);
r.explosions = explosions;
r.item = stack;
}
}
// DATA_ATTACHED_TO_TARGET (OptionalInt: the id plus 1).
(9, Value::Id(v)) => {
let v = (*v > 0).then(|| (*v - 1) as u32);
if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id) {
r.attached_to = v;
}
}
// DATA_SHOT_AT_ANGLE.
(10, Value::Bool(a)) => {
if let Some(r) = self.rockets.iter_mut().find(|r| r.id == id) {
r.angled = *a;
}
}
_ => {}
}
}
}
if self.potions.has_thrown(id) {
// ThrowableItemProjectile.DATA_ITEM_STACK: the potion it is.
for (index, _, value) in values {
@@ -189,10 +220,21 @@ impl Game<'_> {
/// One tick of interpolation, as `tick_remote_objects`.
pub(super) fn tick_remote_projectiles(&mut self, mut step: impl FnMut(u32, Vec3) -> Vec3) {
for t in &mut self.tnts {
t.previous = t.position;
t.position = step(t.id, t.position);
}
// PrimedTnt.tick runs on a client too: it falls, bounces and burns its
// fuse down (the swell and flash follow it) between the server's
// updates (every 10 ticks), and a client discards it when the fuse
// runs out; only the server explodes it.
let (world, collision, assets, facts) = (
&self.world,
self.collision,
&self.pack.assets,
self.res.facts(),
);
self.tnts.retain_mut(|t| {
// A fluid lookup that fails leaves it where its move put it.
let _ = t.tick(world, collision, assets, facts);
t.fuse > 0
});
// FallingBlockEntity.tick runs on a client too: the block falls by
// itself between the server's updates (every 20 ticks), then waits
// where it lands for the server to place it and remove it.
@@ -207,15 +249,54 @@ impl Game<'_> {
for p in &mut self.creatures.projectiles {
p.previous = p.position;
p.age += 1;
p.position = step(p.id, p.position);
if matches!(p.kind, ProjectileKind::LargeFireball { .. }) {
// AbstractHurtingProjectile.tick advances on the client between
// the tracker updates (ten ticks apart for a ghast's fireball).
let at = p.position;
let water = self
.res
.facts()
.get(self.world.block(
at.x.floor() as i32,
at.y.floor() as i32,
at.z.floor() as i32,
))
.fluid
== horizon_client::blocks::Fluid::Water;
p.apply_hurting_inertia(water);
p.position = p.position.add_vector(p.velocity);
} else {
p.position = step(p.id, p.position);
}
}
for t in &mut self.tridents {
let id = t.id;
t.remote_step(|at| step(id, at));
}
// FireworkRocketEntity.tick: a rocket attached to the gliding local
// player boosts it client-side too (attachedToEntity.isFallFlying).
let me = self
.remote
.as_ref()
.and_then(|r| u32::try_from(r.entity_id).ok());
for r in &mut self.rockets {
let id = r.id;
r.remote_step(|at| step(id, at));
if me.is_some()
&& r.attached_to == me
&& let Some(p) = self.player.as_mut()
&& p.fall_flying
{
let look = view_vector(self.yaw, self.pitch);
let m = p.velocity;
p.velocity = Vec3::new(
m.x + look[0] * 0.1 + (look[0] * 1.5 - m.x) * 0.5,
m.y + look[1] * 0.1 + (look[1] * 1.5 - m.y) * 0.5,
m.z + look[2] * 0.1 + (look[2] * 1.5 - m.z) * 0.5,
);
r.position = p.position;
r.velocity = p.velocity;
}
}
for c in &mut self.crystals {
c.time += 1;
@@ -18,7 +18,7 @@ impl Game<'_> {
container: i32,
menu: String,
kind: Kind,
title: String,
title: horizon_client::text::Text,
pos: [i32; 3],
) {
if let Some(r) = self.remote.as_mut() {
@@ -332,6 +332,7 @@ impl Game<'_> {
return;
}
self.load_scoreboard();
host.hub.teams.clone_from(&self.score.board.teams);
let view = horizon_client::lan::scoreboard::View::of(&self.score.board);
for g in host.hub.guests.iter_mut().filter(|g| g.placed) {
if g.scoreboard != view {
+24 -6
View File
@@ -2,6 +2,7 @@
use super::{Game, Screen};
use horizon_client::{
Result,
command::args::GameMode,
hud::{HudBatch, rgba},
text::{self, Text},
ui,
@@ -17,7 +18,8 @@ impl Screen {
| Self::Stats
| Self::Advancements
| Self::WorldOptions
| Self::Friends => true,
| Self::Friends
| Self::Mod => true,
Self::Playing
| Self::GameModeSwitcher
| Self::Chat
@@ -81,9 +83,15 @@ fn pause_icons(w: f32, h: f32) -> [(f32, f32, &'static str); 4] {
(x0 + 72.0, y, "gui/sprites/pause_menu/player_reporting"),
]
}
fn death_buttons(w: f32, h: f32) -> [(f32, f32, &'static str, u8); 2] {
/// DeathScreen.init: a hardcore player can only spectate.
fn death_buttons(w: f32, h: f32, hardcore: bool) -> [(f32, f32, &'static str, u8); 2] {
let respawn = if hardcore {
"deathScreen.spectate"
} else {
"deathScreen.respawn"
};
[
(w / 2.0 - 100.0, h / 4.0 + 72.0, "deathScreen.respawn", 0),
(w / 2.0 - 100.0, h / 4.0 + 72.0, respawn, 0),
(
w / 2.0 - 100.0,
h / 4.0 + 96.0,
@@ -223,7 +231,12 @@ impl Game<'_> {
),
);
}
let title = Text::translate("deathScreen.title", &[]);
let title = if self.level.hardcore {
"deathScreen.title.hardcore"
} else {
"deathScreen.title"
};
let title = Text::translate(title, &[]);
let tw = atlas.font.width_text(&title);
ui::text_scaled(
batch,
@@ -258,7 +271,7 @@ impl Game<'_> {
.ui
.died_at
.is_none_or(|t| t.elapsed().as_millis() >= 1000);
for (x, y, key, _) in death_buttons(w, h) {
for (x, y, key, _) in death_buttons(w, h, self.level.hardcore) {
let hover = active && ui::hovered(self.cursor, x, y, 200.0, 20.0);
ui::button(
batch,
@@ -286,7 +299,7 @@ impl Game<'_> {
.as_ref()
.map_or([1, 1], |r| [r.config.width, r.config.height]);
let b = HudBatch::new(size);
let hit = death_buttons(b.width, b.height)
let hit = death_buttons(b.width, b.height, self.level.hardcore)
.into_iter()
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
.map(|d| d.3);
@@ -330,6 +343,11 @@ impl Game<'_> {
Some(1) => self.close_world()?,
_ => {}
}
// ServerGamePacketListenerImpl.handleClientCommand: a hardcore world's
// respawned player only watches.
if hit == Some(0) && self.remote.is_none() && self.level.hardcore {
self.set_mode(GameMode::Spectator);
}
if hit.is_some() {
self.audio.play_button_click();
}
+36 -6
View File
@@ -63,6 +63,12 @@ struct Steps {
on_ground: bool,
in_water: bool,
}
#[derive(Default)]
pub(super) struct PlayerEvents {
steps: Option<Steps>,
last_health: Option<f32>,
}
#[derive(Default)]
pub(super) struct SculkState {
/// The player's warning level toward a warden.
@@ -86,6 +92,15 @@ pub(super) struct SculkState {
}
impl SculkState {
pub(super) fn swap_player(&mut self, other: &mut PlayerEvents) {
let steps = self.steps.remove(&Who::Player);
if let Some(guest) = other.steps.take() {
self.steps.insert(Who::Player, guest);
}
other.steps = steps;
std::mem::swap(&mut self.last_health, &mut other.last_health);
}
/// Exchange the level-held parts (its sculk block entities and the
/// chunks scanned for them) with another level's (game/levels.rs).
pub(super) fn swap_level(&mut self, other: &mut Self) {
@@ -718,17 +733,24 @@ impl Game<'_> {
})
};
// The ticking ones in the index's order, with whether the chunks
// around them tick too.
// around them tick too. Most sensors and catalysts wait for a
// vibration or a death: their tick would change nothing, so they
// are passed over here (a vibration scheduled during these ticks is
// chosen on the next tick at the earliest, as in vanilla).
let entities = &self.world.block_entities;
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)
})
if !ticks(cx, cz)
|| matches!(entities.get(&key), Some(BlockEntity::Sculk(e)) if e.idle())
{
return None;
}
let adjacent = (-1..=1).all(|dx| (-1..=1).all(|dz| ticks(cx + dx, cz + dz)));
Some((key, adjacent))
})
.collect();
for (key, adjacent) in due {
@@ -1491,6 +1513,12 @@ impl Game<'_> {
/// Events from entities moving, getting hurt and dying, derived from what
/// changed this tick.
fn tick_entity_events(&mut self) {
self.tick_player_sculk_events();
self.tick_mob_sculk_events();
}
/// Entity.move emits on the authoritative server too, for each ServerPlayer.
pub(super) fn tick_player_sculk_events(&mut self) {
// The player.
let player = self.player.as_ref().map(|p| {
(
@@ -1518,7 +1546,9 @@ impl Game<'_> {
}
self.sculk.last_health = Some(health);
}
// Mobs.
}
fn tick_mob_sculk_events(&mut self) {
let snapshot: Vec<(u32, [f64; 3], bool, bool, Species, Option<i64>)> = self
.mobs
.iter()

Some files were not shown because too many files have changed in this diff Show More