Merge main and retain both HUD regression tests

This commit is contained in:
rdbtCVS
2026-10-14 23:33:46 +01:00
259 changed files with 21806 additions and 3486 deletions
+3
View File
@@ -0,0 +1,3 @@
self-hosted-runner:
# The Mac mini's runner (ludovics-mac-mini), which holds the maintainer's own Minecraft files.
labels: [horizon-game, ludovics-mac-mini]
+48
View File
@@ -1,14 +1,25 @@
name: checks
# verify: every pull request and every push to main, on GitHub's runners (the repository is public).
# parity: the vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the
# maintainer's own Minecraft files (Horizon never downloads the game). A fork's pull request runs it only when
# a maintainer adds the run-parity label, once per label. See docs/release-flow.md.
on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, labeled]
workflow_dispatch:
permissions:
contents: read
concurrency:
# A new push to a pull request replaces its running checks; main's runs all finish (releases follow them).
group: checks-${{ github.event.pull_request.number || github.sha }}-${{ github.event.action == 'labeled' && 'label' || 'run' }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
verify:
if: github.event.action != 'labeled'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
with:
@@ -26,12 +37,49 @@ jobs:
run: |
sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
rustup toolchain install stable --profile minimal --component rustfmt --component clippy
# Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache).
- uses: Swatinem/rust-cache@v2
with:
shared-key: verify
save-if: ${{ github.ref == 'refs/heads/main' }}
- name: Check formatting and lint
run: |
cargo +stable fmt --all -- --check
cargo +stable clippy --workspace --all-targets -- -D warnings
- name: Test Rust core and voxel kernel correctness
run: cargo +stable test --workspace
parity:
if: >-
github.event_name == 'pull_request' && (
(github.event.pull_request.head.repo.full_name == github.repository && github.event.action != 'labeled') ||
(github.event.action == 'labeled' && github.event.label.name == 'run-parity'))
runs-on: [self-hosted, horizon-game]
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
with:
# The commit the event names: a fork's later pushes need another run-parity label.
ref: ${{ github.event.pull_request.head.sha }}
fetch-depth: 0
persist-credentials: false
# Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
clean: false
- uses: dtolnay/rust-toolchain@stable
- name: Tools from the runner
run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer
run: bash tools/ci/vanilla-data.sh
- name: The harnesses this change can affect
env:
PARITY_HOSTS: ''
run: python3 tools/parity.py --changed ${{ github.event.pull_request.base.sha }} --timeout 1500
- name: Logs of the failed harnesses
if: failure()
uses: actions/upload-artifact@v4
with:
name: parity-logs
path: .local/parity-runner/logs/
if-no-files-found: ignore
# Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
+160 -37
View File
@@ -1,61 +1,156 @@
name: launcher
# Builds the launcher on Linux, macOS and Windows. A pushed `launcher-vX.Y.Z` tag also puts the
# three archives on a draft GitHub release of that tag, to publish by hand. Horizon's own
# releases are tagged `vYYYY.MM.DD`; the launcher reads only `launcher-v*` releases for itself.
# Builds the launcher on Linux, macOS and Windows, and releases it by itself (docs/release-flow.md): after a
# push to main that changes the launcher or what it builds in (crates/horizon-prepare, crates/horizon-theme),
# every hour (a release the cooldown held goes out) and by hand, tools/release_train.py decides as for the game.
# A release is launcher-vX.Y.Z: the patch after the last launcher tag, or the next minor when a merged pull
# request is labelled feature. The version is given to the build (HORIZON_LAUNCHER_VERSION): no bump commits.
# Never marked latest. Pushes to launcher branches only build. RELEASES_PAUSED=1 stops releases.
# gh workflow run launcher --ref <branch> # dry run: builds everything, publishes nothing
# gh workflow run launcher --ref main -f dry_run=false -f force=true
on:
workflow_dispatch:
push:
branches: [launcher, 'launcher-*']
tags: ['launcher-v*']
branches: [main, launcher, 'launcher-*']
paths:
- 'launcher/**'
- 'crates/horizon-prepare/**'
- 'crates/horizon-theme/**'
- '.github/workflows/launcher.yml'
schedule:
- cron: '47 * * * *'
workflow_dispatch:
inputs:
dry_run:
description: Build everything and write the notes, but publish nothing
type: boolean
default: true
force:
description: Release even without launcher changes, within the cooldown or while paused
type: boolean
default: false
permissions:
contents: read
concurrency:
group: launcher-${{ github.ref == 'refs/heads/main' && 'release' || github.ref }}
cancel-in-progress: false
jobs:
decide:
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
release: ${{ steps.decide.outputs.release }}
tag: ${{ steps.decide.outputs.tag }}
head: ${{ steps.decide.outputs.head }}
version: ${{ steps.decide.outputs.version }}
dry_run: ${{ steps.mode.outputs.dry_run }}
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- id: mode
# Off main every run is a dry run (a launcher branch's push only builds).
run: echo "dry_run=${{ github.ref != 'refs/heads/main' || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }}" >> "$GITHUB_OUTPUT"
- id: decide
env:
GH_TOKEN: ${{ github.token }}
RELEASES_PAUSED: ${{ vars.RELEASES_PAUSED }}
# A push or a run off main builds its own commit; otherwise main's newest commit with green checks.
HEAD_SHA: ${{ (github.event_name == 'push' || steps.mode.outputs.dry_run == 'true') && github.sha || '' }}
FORCE: ${{ inputs.force && 'yes' || '' }}
run: |
python3 tools/release_train.py decide --kind launcher ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json
echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY"
tag=$(jq -r '.tag' decision.json)
echo "version=${tag#launcher-v}" >> "$GITHUB_OUTPUT"
# A dry run (and a launcher branch's push) builds whatever the decision.
if [[ "${{ steps.mode.outputs.dry_run }}" == true ]]; then
echo "release=true" >> "$GITHUB_OUTPUT"
echo "head=$GITHUB_SHA" >> "$GITHUB_OUTPUT"
fi
build:
needs: decide
if: needs.decide.outputs.release == 'true'
name: build ${{ matrix.name }}
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
- name: linux
os: ubuntu-22.04
asset: horizon-launcher-linux-x86_64.tar.gz
binary: horizon-launcher
- os: macos-latest
- name: macos
mac: true
asset: horizon-launcher-macos-arm64.zip
binary: horizon-launcher
- os: windows-latest
- name: windows
os: windows-latest
asset: horizon-launcher-windows-x64.zip
binary: horizon-launcher.exe
# The C runtime linked in: without it the launcher asks for VCRUNTIME140.dll,
# which only the Visual C++ redistributable installs.
rustflags: -C target-feature=+crt-static
runs-on: ${{ matrix.os }}
runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }}
timeout-minutes: 40
env:
RUSTFLAGS: ${{ matrix.rustflags }}
# Horizon's Azure app for Microsoft sign-in (docs/microsoft-account.md): a repository
# variable, not a secret. Unset, the launcher says sign-in is not configured.
HORIZON_MSA_CLIENT_ID: ${{ vars.HORIZON_MSA_CLIENT_ID }}
# The release's version, built in (launcher/src/backend.rs VERSION); a launcher branch's build keeps
# Cargo.toml's.
HORIZON_LAUNCHER_VERSION: ${{ (github.event_name != 'push' || github.ref == 'refs/heads/main') && needs.decide.outputs.version || '' }}
defaults:
run:
working-directory: launcher
shell: bash
steps:
- uses: actions/checkout@v4
with:
ref: ${{ needs.decide.outputs.head }}
persist-credentials: false
# The Mac mini's runner keeps its target/ between runs.
clean: ${{ runner.environment == 'github-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
if: runner.environment == 'github-hosted'
with:
workspaces: launcher
shared-key: launcher-${{ matrix.name }}
- name: Linux libraries GPUI links to
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y libxkbcommon-x11-dev libwayland-dev libx11-xcb-dev libfontconfig-dev libvulkan-dev libasound2-dev
- name: The tag matches Cargo.toml
if: startsWith(github.ref, 'refs/tags/launcher-v')
run: grep -qx "version = \"${GITHUB_REF_NAME#launcher-v}\"" Cargo.toml
- run: cargo test --release --locked --lib
- run: cargo build --release --locked
- name: Metal shaders compiled now, or at run time without the Metal toolchain
# GPUI compiles its Metal shaders when it builds; the Mac mini has Xcode without the Metal toolchain
# (xcodebuild -downloadComponent MetalToolchain), so there they are compiled when the launcher starts.
if: runner.os == 'macOS'
run: |
if ! xcrun metal --version > /dev/null 2>&1; then
echo "::notice::No Metal toolchain on this runner: GPUI compiles its shaders at run time"
echo "LAUNCHER_FEATURES=gpui/runtime_shaders" >> "$GITHUB_ENV"
fi
- run: cargo test --release --locked --lib ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"}
- run: cargo build --release --locked ${LAUNCHER_FEATURES:+--features "$LAUNCHER_FEATURES"}
- name: The version is the release's
run: |
out=$(target/release/${{ matrix.binary }} --version)
echo "$out"
expected="${HORIZON_LAUNCHER_VERSION:-$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)}"
[[ "$out" == "horizon-launcher $expected" ]] || { echo "::error::expected horizon-launcher $expected"; exit 1; }
- name: Only system libraries
if: runner.os == 'Windows'
run: python ../tools/check_imports.py target/release/${{ matrix.binary }}
run: |
file=target/release/${{ matrix.binary }}
case "$RUNNER_OS" in
Windows) python ../tools/check_imports.py "$file" ;;
macOS) others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true)
[[ -z "$others" ]] || { echo "::error::links $others"; exit 1; } ;;
esac
- name: Smoke test
env:
HORIZON_LAUNCHER_NO_SELF_UPDATE: '1'
@@ -64,10 +159,10 @@ jobs:
set -euo pipefail
export HORIZON_LAUNCHER_HOME="${RUNNER_TEMP//\\//}/horizon-launcher-smoke"
export HORIZON_HOME="$HORIZON_LAUNCHER_HOME/game"
rm -rf "$HORIZON_LAUNCHER_HOME"
launcher="$PWD/target/release/${{ matrix.binary }}"
# GitHub's API rate-limits shared runner addresses now and then: try a few times.
retry() { for i in 1 2 3 4; do "$@" && return 0; sleep $((i * 15)); done; return 1; }
"$launcher" --version
retry "$launcher" versions
retry "$launcher" install latest
"$launcher" versions --installed
@@ -83,46 +178,74 @@ jobs:
soft() { if [[ "$RUNNER_OS" == "Linux" ]]; then "$@" || echo "::warning::$* failed"; else "$@"; fi; }
if [[ "$RUNNER_OS" == "Windows" ]]; then
python ../tools/check_imports.py "$client"
python ../tools/check_imports.py "$launcher"
elif [[ "$RUNNER_OS" == "Linux" ]]; then
soft python3 ../tools/check_imports.py "$client"
fi
# The client starts: --help prints before any window or GPU is needed.
help() { "$client" --help > "$RUNNER_TEMP/help.txt" 2>&1 && head -3 "$RUNNER_TEMP/help.txt" && grep -q -- '--resources' "$RUNNER_TEMP/help.txt"; }
soft help
rm -rf "$HORIZON_LAUNCHER_HOME"
- name: Package
run: |
mkdir -p dist
cp target/release/${{ matrix.binary }} dist/
cd dist
if [[ "${{ matrix.asset }}" == *.tar.gz ]]; then
tar czf ../${{ matrix.asset }} ${{ matrix.binary }}
elif [[ "$RUNNER_OS" == "Windows" ]]; then
7z a ../${{ matrix.asset }} ${{ matrix.binary }}
rm -rf dist out && mkdir -p out
if [[ "$RUNNER_OS" == "macOS" ]]; then
# Horizon.app, zipped (self-update) and in a .dmg (installer): packaging/macos.
python3 -m venv "$RUNNER_TEMP/dmg" && "$RUNNER_TEMP/dmg/bin/pip" install --quiet dmgbuild==1.6.5
version=${HORIZON_LAUNCHER_VERSION:-$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)}
DMGBUILD="$RUNNER_TEMP/dmg/bin/dmgbuild" ../packaging/macos/package.sh target/release/${{ matrix.binary }} "$version" out
rm -rf out/Horizon.app
else
zip ../${{ matrix.asset }} ${{ matrix.binary }}
mkdir -p dist
cp target/release/${{ matrix.binary }} dist/
if [[ "${{ matrix.asset }}" == *.tar.gz ]]; then
(cd dist && tar czf ../out/${{ matrix.asset }} ${{ matrix.binary }})
else
(cd dist && 7z a ../out/${{ matrix.asset }} ${{ matrix.binary }})
fi
fi
ls -l out
- uses: actions/upload-artifact@v4
with:
name: ${{ matrix.asset }}
path: launcher/${{ matrix.asset }}
path: launcher/out/*
retention-days: 7
release:
if: startsWith(github.ref, 'refs/tags/launcher-v')
needs: build
needs: [decide, build]
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Notes
env:
GH_TOKEN: ${{ github.token }}
run: |
python3 tools/release_train.py notes --kind launcher --tag "${{ needs.decide.outputs.tag }}" \
--head "${{ needs.decide.outputs.head }}" --out notes > /dev/null
{ echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY"
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
# A draft, and never marked latest: Horizon's own releases stay the repository's latest.
- uses: softprops/action-gh-release@v2
# Never marked latest: Horizon's own releases stay the repository's latest.
- name: Publish ${{ needs.decide.outputs.tag }}
if: needs.decide.outputs.dry_run != 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.decide.outputs.tag }}
run: |
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
--notes-file notes/body.md --latest=false dist/horizon-launcher-*
- name: Dry run, the release that would be published
if: needs.decide.outputs.dry_run == 'true'
run: |
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)"
ls -l dist
- uses: actions/upload-artifact@v4
with:
tag_name: ${{ github.ref_name }}
name: Horizon launcher ${{ github.ref_name }}
draft: true
make_latest: false
files: dist/*
name: launcher-release-notes
path: notes/
+79
View File
@@ -0,0 +1,79 @@
name: nightly audit
# Every vanilla harness, from scratch, on main, at 03:00 Paris time on the Mac mini's runner (it holds the
# maintainer's own Minecraft files). The resources are prepared again first when the preparer or its exporters
# changed (tools/ci/vanilla-data.sh). A harness that passed in the previous audit and fails now gets an issue
# labelled parity-regression (one per harness); its issue closes when it passes again
# (tools/ci/parity_issues.py). The bugs session picks those up. See docs/release-flow.md.
# gh workflow run "nightly audit" # now
# gh workflow run "nightly audit" -f dry_run=true # the audit, without touching issues
on:
schedule:
# GitHub's schedules are in UTC: both, and the first step keeps the one that is 03:00 in Paris.
- cron: '7 1 * * *'
- cron: '7 2 * * *'
workflow_dispatch:
inputs:
dry_run:
description: Run the audit, but only print what it would do with issues
type: boolean
default: false
permissions:
contents: read
issues: write
concurrency:
group: nightly-audit
cancel-in-progress: false
jobs:
audit:
runs-on: [self-hosted, horizon-game]
timeout-minutes: 150
steps:
- name: 03:00 in Paris
id: when
run: |
hour=$(TZ=Europe/Paris date +%H)
if [[ "${{ github.event_name }}" == schedule && "$hour" != 03 ]]; then
echo "It is ${hour}:00 in Paris: the other schedule runs the audit."
echo "run=false" >> "$GITHUB_OUTPUT"
else
echo "run=true" >> "$GITHUB_OUTPUT"
fi
- uses: actions/checkout@v4
if: steps.when.outputs.run == 'true'
with:
fetch-depth: 0
persist-credentials: false
# Keeps .local/ (parity state, probe builds, the previous audit) and target/.
clean: false
- uses: dtolnay/rust-toolchain@stable
if: steps.when.outputs.run == 'true'
- name: Tools from the runner
if: steps.when.outputs.run == 'true'
run: bash tools/ci/runner-env.sh
- name: Vanilla data, prepared again if the preparer changed
if: steps.when.outputs.run == 'true'
run: bash tools/ci/vanilla-data.sh
- name: Every harness
id: audit
if: steps.when.outputs.run == 'true'
env:
PARITY_HOSTS: ''
run: |
echo "since=$(date +%Y-%m-%dT%H:%M:%S)" >> "$GITHUB_OUTPUT"
set +e
python3 tools/parity.py --all --timeout 1800 2>&1 | tee "$RUNNER_TEMP/audit.log"
echo "exit=${PIPESTATUS[0]}" >> "$GITHUB_OUTPUT"
{ echo '```'; tail -40 "$RUNNER_TEMP/audit.log"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
- name: Issues for the harnesses that regressed
if: steps.when.outputs.run == 'true' && always() && steps.audit.outputs.since
env:
GH_TOKEN: ${{ github.token }}
run: python3 tools/ci/parity_issues.py --since "${{ steps.audit.outputs.since }}" ${{ inputs.dry_run && '--dry-run' || '' }} | tee -a "$GITHUB_STEP_SUMMARY"
- name: Logs of the failed harnesses
if: steps.when.outputs.run == 'true' && steps.audit.outputs.exit != '0'
uses: actions/upload-artifact@v4
with:
name: nightly-parity-logs
path: .local/parity-runner/logs/
if-no-files-found: ignore
retention-days: 14
+206 -40
View File
@@ -1,57 +1,223 @@
name: release builds
# Started by hand: gh workflow run release.yml --ref <branch>
# Builds the Windows x64 and Linux x86_64 clients (with horizon-ctl and horizon-prepare) and uploads the playable folders
# as artifacts.
# macOS builds are made on the development machines. Linux is built here, on an older Ubuntu,
# so the binary uses the standard loader and runs on any recent distribution (and on NixOS
# through nix-ld): a build made on NixOS asks for a /nix/store loader no other system has.
name: release
# Automatic game releases (docs/release-flow.md). After every green `checks` run on main, every hour (a release
# held by the cooldown goes out without another merge) and by hand, tools/release_train.py decides: a release
# when a pull request merged since the last one changed what players run and that release is 3 hours old, or at
# once for a pull request labelled release-now. RELEASES_PAUSED=1 (repository variable) stops them.
# Builds Linux (an older Ubuntu, so the binary runs on any recent distribution and on NixOS through nix-ld) and
# Windows on GitHub, macOS on the Mac mini's runner (MAC_RUNNER=macos-latest sends it to GitHub), then
# publishes vYYYY.MM.DD[.N] with notes from the merged pull requests.
# gh workflow run release --ref <branch> # dry run: builds and notes, publishes nothing
# gh workflow run release -f dry_run=false -f force=true # on main: release now, whatever the rules say
on:
workflow_run:
workflows: [checks]
types: [completed]
branches: [main]
schedule:
- cron: '17 * * * *'
workflow_dispatch:
inputs:
dry_run:
description: Build everything and write the notes, but publish nothing
type: boolean
default: true
force:
description: Release even without player-facing changes, within the cooldown or while paused
type: boolean
default: false
permissions:
contents: read
concurrency:
group: game-release
cancel-in-progress: false
jobs:
windows:
runs-on: windows-latest
decide:
if: >-
github.event_name != 'workflow_run' ||
(github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
runs-on: ubuntu-latest
timeout-minutes: 10
outputs:
release: ${{ steps.decide.outputs.release }}
tag: ${{ steps.decide.outputs.tag }}
head: ${{ steps.decide.outputs.head }}
dry_run: ${{ steps.mode.outputs.dry_run }}
steps:
- uses: actions/checkout@v4
- name: Install Rust toolchain
run: rustup toolchain install stable --profile minimal
- name: Build the client
# The C runtime linked in, so the game runs without the Visual C++ redistributable.
with:
fetch-depth: 0
- id: mode
# A dry run never publishes; a hand-started run off main is always one.
run: echo "dry_run=${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run || github.ref != 'refs/heads/main') }}" >> "$GITHUB_OUTPUT"
- id: decide
env:
RUSTFLAGS: -C target-feature=+crt-static
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
- name: Only system DLLs
# Vulkan and the rest are loaded at run time; a linked non-system DLL is a
# "DLL not found" dialog on some players' machines.
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.
HEAD_SHA: ${{ github.event.workflow_run.head_sha || (steps.mode.outputs.dry_run == 'true' && github.sha) || '' }}
FORCE: ${{ inputs.force && 'yes' || '' }}
run: |
python tools/check_imports.py target/release/horizon-client.exe
python tools/check_imports.py target/release/horizon-ctl.exe
python tools/check_imports.py target/release/horizon-prepare.exe
- name: Package
run: cargo +stable run --locked -p xtask -- package target/release/horizon-client.exe dist/horizon-windows-x64
- uses: actions/upload-artifact@v4
with:
name: horizon-windows-x64
path: dist/horizon-windows-x64
linux:
runs-on: ubuntu-22.04
python3 tools/release_train.py decide --kind game ${HEAD_SHA:+--head "$HEAD_SHA"} ${FORCE:+--force} | tee decision.json
echo "### $(jq -r '.reason' decision.json)" >> "$GITHUB_STEP_SUMMARY"
# 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:
needs: decide
if: needs.decide.outputs.release == 'true'
name: build ${{ matrix.name }}
strategy:
fail-fast: false
matrix:
include:
- name: linux
os: ubuntu-22.04
dir: horizon-linux-x86_64
asset: horizon-linux-x86_64.tar.gz
- name: windows
os: windows-latest
dir: horizon-windows-x64
asset: horizon-windows-x64.zip
exe: .exe
# The C runtime linked in, so the game runs without the Visual C++ redistributable.
rustflags: -C target-feature=+crt-static
- name: macos
mac: true
dir: horizon-macos-arm64
asset: horizon-macos-arm64.zip
runs-on: ${{ matrix.mac && (vars.MAC_RUNNER || 'ludovics-mac-mini') || matrix.os }}
timeout-minutes: 40
env:
RUSTFLAGS: ${{ matrix.rustflags }}
defaults:
run:
shell: bash
steps:
- uses: actions/checkout@v4
- name: Install Rust toolchain
run: rustup toolchain install stable --profile minimal
with:
ref: ${{ needs.decide.outputs.head }}
persist-credentials: false
# On the Mac mini's runner, keep target/ (incremental) and .local/ (the prepared resources).
clean: ${{ runner.environment == 'github-hosted' }}
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
if: runner.environment == 'github-hosted'
with:
shared-key: release-${{ matrix.name }}
- name: ALSA and udev headers
if: runner.os == 'Linux'
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends libasound2-dev libudev-dev
- name: Build the client
run: cargo +stable build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
- name: Standard loader and libraries only
- name: Build the client, horizon-ctl and horizon-prepare
run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare
- name: Every program the release folder takes was built
run: |
python3 tools/check_imports.py target/release/horizon-client
python3 tools/check_imports.py target/release/horizon-ctl
python3 tools/check_imports.py target/release/horizon-prepare
for binary in horizon-client horizon-ctl horizon-prepare; do
test -f "target/release/$binary${{ matrix.exe }}" || { echo "::error::target/release/$binary${{ matrix.exe }} is missing"; exit 1; }
done
- name: Only system libraries
# Windows: no non-system DLL (a "DLL not found" dialog on some players' machines). Linux: the standard
# loader and libraries every desktop distribution has. macOS: only the system's own libraries.
run: |
for binary in horizon-client horizon-ctl horizon-prepare; do
file="target/release/$binary${{ matrix.exe }}"
if [[ "$RUNNER_OS" == macOS ]]; then
others=$(otool -L "$file" | tail -n +2 | awk '{print $1}' | grep -v -E '^(/usr/lib/|/System/Library/)' || true)
[[ -z "$others" ]] || { echo "::error::$binary links $others"; exit 1; }
else
${{ runner.os == 'Windows' && 'python' || 'python3' }} tools/check_imports.py "$file"
fi
done
- name: Every program starts
run: |
set -euo pipefail
bin=target/release
"$bin/horizon-client${{ matrix.exe }}" --help | grep -q -- '--resources'
"$bin/horizon-ctl${{ matrix.exe }}" --help > /dev/null
"$bin/horizon-prepare${{ matrix.exe }}" --version
"$bin/horizon-prepare${{ matrix.exe }}" --help | grep -q -- '--minecraft-dir'
- name: Tools from the runner
if: runner.environment == 'self-hosted'
run: bash tools/ci/runner-env.sh
- name: Resources prepared from the runner's own Minecraft
if: runner.environment == 'self-hosted'
run: bash tools/ci/vanilla-data.sh
- name: The game runs (offscreen, a new world, 1500 frames)
if: runner.environment == 'self-hosted'
run: |
set -euo pipefail
# From a scratch folder: the game keeps its saves and options in the folder it starts in.
home="$RUNNER_TEMP/horizon-smoke"
rm -rf "$home" && mkdir -p "$home"
version=$(sed -n 's/.*"version": *"\([^"]*\)".*/\1/p' research-lock.json | head -1)
client="$PWD/target/release/horizon-client"
resources="$PWD/.local/horizon-client/$version"
(cd "$home" && HORIZON_HOME="$home" HORIZON_NO_AUDIO=1 "$client" --resources "$resources" --offscreen \
--world smoke --seed 1 --render-distance 4 --frames 1500 --timeout-seconds 180 \
--smoke-report "$home/smoke.json" > "$home/client.log" 2>&1) || { tail -40 "$home/client.log"; exit 1; }
python3 - "$home/smoke.json" <<'EOF'
import json, sys
report = json.load(open(sys.argv[1]))
print(json.dumps(report))
if report.get("error") is not None or report.get("frames", 0) < 1500 or not report.get("chunks") \
or not report.get("meshed_sections") or not report.get("player"):
sys.exit("the smoke run did not draw a world")
EOF
- name: Package
run: cargo +stable run --locked -p xtask -- package target/release/horizon-client dist/horizon-linux-x86_64
run: |
set -euo pipefail
cargo run --locked -p xtask -- package "target/release/horizon-client${{ matrix.exe }}" "dist/${{ matrix.dir }}"
cd dist
rm -f "${{ matrix.asset }}"
case "${{ matrix.asset }}" in
*.tar.gz) tar czf "${{ matrix.asset }}" "${{ matrix.dir }}" ;;
*) if [[ "$RUNNER_OS" == Windows ]]; then 7z a -tzip "${{ matrix.asset }}" "${{ matrix.dir }}" > /dev/null
else ditto -c -k --keepParent "${{ matrix.dir }}" "${{ matrix.asset }}"; fi ;;
esac
ls -l "${{ matrix.asset }}"
- uses: actions/upload-artifact@v4
with:
name: horizon-linux-x86_64
path: dist/horizon-linux-x86_64
name: ${{ matrix.asset }}
path: dist/${{ matrix.asset }}
if-no-files-found: error
retention-days: 7
publish:
needs: [decide, build]
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Notes
env:
GH_TOKEN: ${{ github.token }}
run: |
python3 tools/release_train.py notes --kind game --tag "${{ needs.decide.outputs.tag }}" \
--head "${{ needs.decide.outputs.head }}" --out notes > /dev/null
{ echo "## $(cat notes/title.txt)"; echo; cat notes/body.md; } >> "$GITHUB_STEP_SUMMARY"
- uses: actions/download-artifact@v4
with:
path: dist
merge-multiple: true
- name: Publish ${{ needs.decide.outputs.tag }}
if: needs.decide.outputs.dry_run != 'true'
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ needs.decide.outputs.tag }}
run: |
gh release create "$TAG" --target "${{ needs.decide.outputs.head }}" --title "$(cat notes/title.txt)" \
--notes-file notes/body.md --latest dist/horizon-linux-x86_64.tar.gz dist/horizon-windows-x64.zip \
dist/horizon-macos-arm64.zip
- name: Dry run, the release that would be published
if: needs.decide.outputs.dry_run == 'true'
run: |
echo "Would publish ${{ needs.decide.outputs.tag }} at ${{ needs.decide.outputs.head }}: $(cat notes/title.txt)"
ls -l dist
- uses: actions/upload-artifact@v4
with:
name: release-notes
path: notes/
+1
View File
@@ -16,6 +16,7 @@
/dist/
/mods/horizon/build/
/saves/
/backups/
/tools/logs/
.DS_Store
# What the client writes to its working directory when run from the repo root.
Generated
+427
View File
@@ -174,6 +174,12 @@ version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "bit-set"
version = "0.10.0"
@@ -693,6 +699,15 @@ version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
[[package]]
name = "form_urlencoded"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
dependencies = [
"percent-encoding",
]
[[package]]
name = "futures-core"
version = "0.3.34"
@@ -737,6 +752,17 @@ dependencies = [
"windows-link",
]
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -894,8 +920,11 @@ dependencies = [
"pollster",
"serde_json",
"symphonia",
"ureq",
"wgpu",
"winit",
"winresource",
"zip",
]
[[package]]
@@ -920,8 +949,10 @@ name = "horizon-protocol"
version = "0.1.0"
dependencies = [
"flate2",
"getrandom 0.3.4",
"horizon-world",
"serde_json",
"sha1",
]
[[package]]
@@ -964,6 +995,110 @@ dependencies = [
"cc",
]
[[package]]
name = "icu_collections"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
dependencies = [
"displaydoc",
"potential_utf",
"utf8_iter",
"yoke",
"zerofrom",
"zerovec",
]
[[package]]
name = "icu_locale_core"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
dependencies = [
"displaydoc",
"litemap",
"tinystr",
"writeable",
"zerovec",
]
[[package]]
name = "icu_normalizer"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
dependencies = [
"icu_collections",
"icu_normalizer_data",
"icu_properties",
"icu_provider",
"smallvec",
"zerovec",
]
[[package]]
name = "icu_normalizer_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
[[package]]
name = "icu_properties"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
dependencies = [
"displaydoc",
"icu_collections",
"icu_locale_core",
"icu_properties_data",
"icu_provider",
"zerotrie",
"zerovec",
]
[[package]]
name = "icu_properties_data"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
[[package]]
name = "icu_provider"
version = "2.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
dependencies = [
"displaydoc",
"icu_locale_core",
"writeable",
"yoke",
"zerofrom",
"zerotrie",
"zerovec",
]
[[package]]
name = "idna"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
dependencies = [
"idna_adapter",
"smallvec",
"utf8_iter",
]
[[package]]
name = "idna_adapter"
version = "1.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
dependencies = [
"icu_normalizer",
"icu_properties",
]
[[package]]
name = "indexmap"
version = "2.14.2"
@@ -1157,6 +1292,12 @@ version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "litemap"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
[[package]]
name = "litrs"
version = "1.0.0"
@@ -1880,6 +2021,15 @@ dependencies = [
"portable-atomic",
]
[[package]]
name = "potential_utf"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
dependencies = [
"zerovec",
]
[[package]]
name = "presser"
version = "0.3.1"
@@ -2020,6 +2170,20 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom 0.2.17",
"libc",
"untrusted",
"windows-sys 0.52.0",
]
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -2061,6 +2225,41 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"log",
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.15.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -2149,6 +2348,15 @@ dependencies = [
"zmij",
]
[[package]]
name = "serde_spanned"
version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
dependencies = [
"serde_core",
]
[[package]]
name = "sha1"
version = "0.10.7"
@@ -2254,6 +2462,12 @@ dependencies = [
"bitflags 2.13.2",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "static_assertions"
version = "1.1.0"
@@ -2266,6 +2480,12 @@ version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "symphonia"
version = "0.5.5"
@@ -2359,6 +2579,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -2424,6 +2655,16 @@ dependencies = [
"strict-num",
]
[[package]]
name = "tinystr"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
dependencies = [
"displaydoc",
"zerovec",
]
[[package]]
name = "tokio"
version = "1.53.2"
@@ -2433,6 +2674,21 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "toml"
version = "1.1.6+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
dependencies = [
"indexmap",
"serde_core",
"serde_spanned",
"toml_datetime",
"toml_parser",
"toml_writer",
"winnow",
]
[[package]]
name = "toml_datetime"
version = "1.1.1+spec-1.1.0"
@@ -2463,6 +2719,12 @@ dependencies = [
"winnow",
]
[[package]]
name = "toml_writer"
version = "1.1.3+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
[[package]]
name = "tracing"
version = "0.1.44"
@@ -2520,6 +2782,45 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "ureq"
version = "2.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
dependencies = [
"base64",
"log",
"once_cell",
"rustls",
"rustls-pki-types",
"url",
"webpki-roots 0.26.11",
]
[[package]]
name = "url"
version = "2.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
dependencies = [
"form_urlencoded",
"idna",
"percent-encoding",
"serde",
]
[[package]]
name = "utf8_iter"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "uuid"
version = "1.28.0"
@@ -2556,6 +2857,12 @@ dependencies = [
"winapi-util",
]
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "wasip2"
version = "1.0.4+wasi-0.2.12"
@@ -2750,6 +3057,24 @@ dependencies = [
"wasm-bindgen",
]
[[package]]
name = "webpki-roots"
version = "0.26.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
dependencies = [
"webpki-roots 1.0.9",
]
[[package]]
name = "webpki-roots"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "wgpu"
version = "30.0.1"
@@ -3265,6 +3590,16 @@ dependencies = [
"memchr",
]
[[package]]
name = "winresource"
version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2bc6d36480b829272a5bdabf08e6dca8004761c1da7e35efef800540c66221b"
dependencies = [
"toml",
"version_check",
]
[[package]]
name = "wit-bindgen"
version = "0.57.1"
@@ -3289,6 +3624,12 @@ dependencies = [
"wayland-protocols-wlr",
]
[[package]]
name = "writeable"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x11-dl"
version = "2.21.0"
@@ -3349,6 +3690,9 @@ checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
[[package]]
name = "xtask"
version = "0.1.0"
dependencies = [
"horizon-theme",
]
[[package]]
name = "xxhash-rust"
@@ -3356,6 +3700,29 @@ version = "0.8.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "550a2b930b62486a393c52d5c3b84bff264b28aa437ed64694d31e93b1757af7"
[[package]]
name = "yoke"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
dependencies = [
"stable_deref_trait",
"yoke-derive",
"zerofrom",
]
[[package]]
name = "yoke-derive"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
"synstructure",
]
[[package]]
name = "zerocopy"
version = "0.8.60"
@@ -3376,6 +3743,66 @@ dependencies = [
"syn 2.0.119",
]
[[package]]
name = "zerofrom"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
dependencies = [
"zerofrom-derive",
]
[[package]]
name = "zerofrom-derive"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
"synstructure",
]
[[package]]
name = "zeroize"
version = "1.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
[[package]]
name = "zerotrie"
version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
dependencies = [
"displaydoc",
"yoke",
"zerofrom",
]
[[package]]
name = "zerovec"
version = "0.11.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
dependencies = [
"yoke",
"zerofrom",
"zerovec-derive",
]
[[package]]
name = "zerovec-derive"
version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.6",
]
[[package]]
name = "zip"
version = "2.4.2"
+3 -3
View File
@@ -47,8 +47,8 @@ Horizon is downloaded only through **the Horizon launcher**: get it from [playho
<table>
<tr>
<td width="50%"><img src="docs/media/launcher-play.webp" alt="The launcher's Play page: v2026.10.13.1 ready to play, its summary, Client and Server, the Play button and prepared resources"></td>
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page, showing the notes of Horizon 2026.10.13.1"></td>
<td width="50%"><img src="docs/media/launcher-play.webp" alt="The launcher's Play page: v2026.10.14.1 ready to play, its summary, Client and Server, the version picker and Play, the resources and the Minecraft folder as a numbered list"></td>
<td width="50%"><img src="docs/media/launcher-patch-notes.webp" alt="The launcher's Patch notes page, showing the notes of Horizon 2026.10.14.1"></td>
</tr>
</table>
@@ -62,7 +62,7 @@ Captured in the Rust client itself, with vanilla assets and no mods or shaders.
<table>
<tr>
<td colspan="2"><img src="docs/media/menu-title.webp" alt="Horizon's title screen: a sidebar, the Horizon title, Singleplayer and Multiplayer buttons and the last world played, over a blurred frozen landscape"></td>
<td colspan="2"><img src="docs/media/menu-title.webp" alt="Horizon's title screen: the mark and the pages on the left, the Horizon title, Singleplayer and Multiplayer, and the last world played and the faint wordmark, over a veiled snowy landscape"></td>
</tr>
<tr>
<td width="50%"><img src="docs/media/menu-worlds.webp" alt="The Singleplayer page: three worlds with their dates and game modes, and Create world and Play buttons"></td>
+7
View File
@@ -28,8 +28,15 @@ chrono = { version = "0.4.42", default-features = false, features = ["clock", "s
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
horizon-theme = { path = "../horizon-theme" }
arboard = { version = "3.6.1", default-features = false, features = ["wayland-data-control"] }
zip = { version = "2", default-features = false, features = ["deflate"] }
# Controllers (evdev + libudev on Linux, IOKit on macOS, Windows.Gaming.Input).
gilrs = "0.11"
# HTTPS to the Minecraft services (online-mode session join).
ureq = { version = "2", default-features = false, features = ["tls"] }
[target.'cfg(windows)'.build-dependencies]
# The icon resource in the .exe (build.rs).
winresource = "0.1"
[features]
# Records the call sites of mob random draws (`mob_ai_probe` traces).
+15
View File
@@ -0,0 +1,15 @@
//! Embeds Horizon's icon (`packaging/icons/horizon.ico`) in the Windows executables, as icon
//! resource 1: Explorer and the task bar show it, and the window takes it as its icon.
fn main() {
let dir = std::env::var("CARGO_MANIFEST_DIR").unwrap_or_default();
let ico = format!("{dir}/../../packaging/icons/horizon.ico");
println!("cargo:rerun-if-changed={ico}");
#[cfg(windows)]
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
let mut resource = winresource::WindowsResource::new();
resource.set_icon(&ico);
if let Err(e) = resource.compile() {
panic!("embedding {ico}: {e}");
}
}
}
@@ -0,0 +1,312 @@
//! Arrows over the client's resident scene (`arrows::tick`), for
//! tools/test_arrow_parity.py: one line of state and one of events per operation.
#![forbid(unsafe_code)]
use horizon_client::{
Result,
arrows::{
self, ArrowEvent, ArrowParticle, ArrowScene, ArrowSound, BlockReaction, Pickup, Touch,
},
assets::Assets,
blocks::BlockFacts,
collisions,
items::ItemStack,
mobs::Who,
motion::{LAVA, MotionResources, WATER},
projectiles::{Projectile, ProjectileKind},
world::World,
};
use horizon_core::{
geometry::Vec3,
random::{LegacyRandom, RandomSource},
};
use serde_json::Value;
use std::{
fs,
io::{BufRead, Write},
path::PathBuf,
};
fn number(v: &Value) -> f64 {
f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}
fn vector(v: &Value) -> Vec3 {
Vec3::new(number(&v[0]), number(&v[1]), number(&v[2]))
}
fn bits(v: Vec3) -> String {
format!(
"{:016x},{:016x},{:016x}",
v.x.to_bits(),
v.y.to_bits(),
v.z.to_bits()
)
}
fn seed(v: &Value) -> i64 {
v.as_str().unwrap().parse().unwrap()
}
fn particle(k: ArrowParticle) -> &'static str {
match k {
ArrowParticle::Bubble => "bubble",
ArrowParticle::Crit => "crit",
ArrowParticle::Splash => "splash",
}
}
fn main() -> Result<()> {
let args: Vec<_> = std::env::args().skip(1).collect();
if args.len() != 3 {
return Err("usage: arrow_probe RESOURCES FIXTURE_DIRECTORY --describe|REFERENCE".into());
}
let root = PathBuf::from(&args[0]);
let dir = PathBuf::from(&args[1]);
let assets = Assets::load(&root)?;
let mut scene = World::test_scene(&assets, 1)?;
fs::write(
dir.join("scene.json"),
serde_json::to_vec(
&serde_json::json!({"radius":1,"resident_chunks":scene.chunks.len(),"model_gallery":assets.model_gallery}),
)?,
)?;
if args[2] == "--describe" {
return Ok(());
}
let binding = collisions::load(&root, assets.registry)?;
let motion = MotionResources::load(&root, &assets)?;
let facts = BlockFacts::load(&root, assets.registry)?;
let side = &args[2];
let mut out = std::io::BufWriter::new(fs::File::create(dir.join(format!("rust-{side}.txt")))?);
let mut level_random = LegacyRandom::new(0);
for line in std::io::BufReader::new(fs::File::open(dir.join("inputs.txt"))?).lines() {
let f: Value = serde_json::from_str(&line?)?;
let kind = ProjectileKind::Arrow {
base_damage: 2.0,
critical: f["crit"].as_bool().unwrap(),
effect: None,
};
let mut arrow = Projectile::new(kind, vector(&f["position"]), None)
.with_arrow_random(LegacyRandom::new(seed(&f["seed"])));
arrow.velocity = vector(&f["velocity"]);
arrow.arrow.as_mut().unwrap().no_physics = f["no_physics"].as_bool().unwrap();
// ProjectileWeaponItem.useAmmo's stack, intangible when no ammo was used.
arrow.arrow.as_mut().unwrap().set_item(&arrows::drawn_ammo(
&ItemStack::new("minecraft:arrow", 1),
f["intangible"].as_bool().unwrap(),
));
for op in f["ops"].as_array().unwrap() {
let mut events = Vec::new();
let mut touched = "-".to_string();
match op["mode"].as_str().unwrap() {
"tick" => {
if !arrow.arrow.as_ref().unwrap().removed {
let no_rain = |_| false;
let view = ArrowScene {
world: &scene,
registry: assets.registry,
facts: &facts,
collision: &binding,
fluids: &motion.fluids,
raining: &no_rain,
mob_griefing: true,
tnt_explodes: true,
};
arrows::tick(&mut arrow, &view, &[]);
}
for event in arrow.arrow.as_mut().unwrap().events.drain(..) {
match event {
ArrowEvent::Particle {
kind,
position,
velocity,
} => events.push(format!(
"particle {} {} {}",
particle(kind),
bits(position),
bits(velocity)
)),
ArrowEvent::Sound {
sound,
volume,
pitch,
} => events.push(format!(
"sound {} {:08x} {:08x}",
match sound {
ArrowSound::HitGround => "hit",
ArrowSound::Splash => "splash",
ArrowSound::Extinguish => "extinguish",
},
volume.to_bits(),
pitch.to_bits()
)),
ArrowEvent::BubbleColumnParticles { pos } => {
for _ in 0..2 {
let x = f64::from(pos.x) + level_random.next_double();
let z = f64::from(pos.z) + level_random.next_double();
let at = Vec3::new(x, f64::from(pos.y + 1), z);
events.push(format!(
"sent splash {} {} {:016x}",
bits(at),
bits(Vec3::ZERO),
1.0f64.to_bits()
));
let x = f64::from(pos.x) + level_random.next_double();
let z = f64::from(pos.z) + level_random.next_double();
let at = Vec3::new(x, f64::from(pos.y + 1), z);
events.push(format!(
"sent bubble {} {} {:016x}",
bits(at),
bits(Vec3::new(0.0, 0.01, 0.0)),
0.2f64.to_bits()
));
}
}
ArrowEvent::Block { pos, reaction } => match reaction {
BlockReaction::PrimeTnt => {
// TntBlock.prime: PrimedTnt draws its push from the
// level random, then removeBlock(pos, false).
let _ = level_random.next_double();
let at = Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y),
f64::from(pos.z) + 0.5,
);
events.push(format!("spawn tnt {} 80", bits(at)));
events.push(format!(
"sound tnt_primed {:08x} {:08x}",
1.0f32.to_bits(),
1.0f32.to_bits()
));
events.push("prime-event".into());
let air =
assets.registry.default_state("minecraft:air").unwrap();
scene.set(pos.x, pos.y, pos.z, air)?;
events.push(format!(
"write {},{},{} {} 3",
pos.x, pos.y, pos.z, air.0
));
}
BlockReaction::Light(lit) => {
scene.set(pos.x, pos.y, pos.z, lit)?;
events.push(format!(
"write {},{},{} {} 11",
pos.x, pos.y, pos.z, lit.0
));
}
},
ArrowEvent::SplashEvent => events.push("splash-event".into()),
ArrowEvent::ShootEvent => events.push("shoot-event".into()),
}
}
}
"block" => {
let p = &op["position"];
let mut state = assets
.registry
.default_state(op["name"].as_str().unwrap())
.ok_or("missing fixture block")?;
if let Some(properties) = op["properties"].as_object() {
let mut definition = assets.registry.state(state).unwrap().clone();
for (name, value) in properties {
definition
.properties
.insert(name.clone(), value.as_str().unwrap().into());
}
state = assets
.registry
.id(&definition)
.ok_or("missing fixture state")?;
}
scene.set(
p[0].as_i64().unwrap() as i32,
p[1].as_i64().unwrap() as i32,
p[2].as_i64().unwrap() as i32,
state,
)?;
}
"velocity" => arrow.velocity = vector(&op["value"]),
"ignite" => arrow
.arrow
.as_mut()
.unwrap()
.ignite_for_seconds(f32::from_bits(
u32::from_str_radix(op["value"].as_str().unwrap(), 16).unwrap(),
)),
"level_seed" => level_random.set_seed(seed(&op["value"])),
"owner" => arrow
.arrow
.as_mut()
.unwrap()
.set_owner(match op["value"].as_str() {
Some("player") => Some(Who::Player),
Some("mob") => Some(Who::Mob(1)),
_ => None,
}),
"pickup" => {
arrow.arrow.as_mut().unwrap().pickup =
Pickup::from_byte(op["value"].as_i64().unwrap())
}
// The game's touch: the inventory takes the arrow unless full,
// and a creative player takes it anyway.
"touch" => {
let creative = op["creative"].as_bool().unwrap();
let full = op["inventory"] == "full";
let a = arrow.arrow.as_mut().unwrap();
let (taken, arrows) = match a.player_touch(creative) {
Touch::Ignore => (false, 0),
Touch::Take => (true, 0),
Touch::Give(_) => (!full || creative, u32::from(!full)),
};
if taken {
a.removed = true;
}
touched = format!("{taken} {arrows}");
}
other => return Err(format!("unknown operation {other}").into()),
}
let a = arrow.arrow.as_ref().unwrap();
writeln!(
out,
"arrow {} {} {:08x} {:08x} {} {} {} {} {} {} {} {} {} {:016x} {:016x} {} {} {:016x}",
bits(arrow.position),
bits(arrow.velocity),
arrow.pitch.to_bits(),
arrow.yaw.to_bits(),
a.in_ground,
a.in_ground_time,
a.life,
a.shake,
a.last_state.map_or("none".into(), |s| s.0.to_string()),
a.fire_ticks,
a.was_touching_water,
a.was_eye_in_water,
a.first_tick,
a.fluids.fluid_height(&Tags, WATER).to_bits(),
a.fluids.fluid_height(&Tags, LAVA).to_bits(),
a.removed,
arrow.critical(),
a.fall_distance.to_bits()
)?;
writeln!(out, "events {}", events.join(" | "))?;
let a = arrow.arrow.as_ref().unwrap();
let intangible = a
.pickup_item
.data()
.and_then(|d| d.other(arrows::INTANGIBLE))
.is_some();
writeln!(out, "pickup {} {intangible} {touched}", a.pickup.byte())?;
}
writeln!(out, "end")?;
}
Ok(())
}
struct Tags;
impl horizon_world::entity_fluid::FluidMembership for Tags {
fn fluid_in_tag(
&self,
kind: horizon_world::fluid::FluidKind,
tag: horizon_world::entity_fluid::FluidTagId,
) -> bool {
use horizon_world::fluid::FluidKind;
if tag == WATER {
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
} else {
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
}
}
}
@@ -294,12 +294,26 @@ fn main() -> horizon_client::Result<()> {
let types = MobTypes::load(&root)?;
let animations = MobData::load_animations(&root);
let mut out = String::new();
let crystal = horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main");
for line in fs::read_to_string(&args[1])?.lines() {
let v: Value = serde_json::from_str(line)?;
let layer = v["layer"]
.as_str()
.unwrap_or_default()
.trim_start_matches("minecraft:");
// EndCrystalModel is not a mob's: horizon_client::end_crystal poses it.
if layer == "end_crystal#main"
&& let Some(model) = &crystal
{
let case = &v["case"];
let mut poses = horizon_client::end_crystal::poses(
model,
case["ageInTicks"].as_f64().unwrap_or(0.0) as f32,
case["showsBottom"].as_bool().unwrap_or(false),
);
out.push_str(&format!("{}\n", emit(model, &mut poses, case, layer)));
continue;
}
let baby = layer.contains("_baby#");
let adult = layer.replace("_baby#", "#");
// Variant layers (sizes, hatless villagers, climate cows...) animate
@@ -576,35 +590,38 @@ fn main() -> horizon_client::Result<()> {
}
_ => anim::setup(&mob, s, p, &animations),
}
// The harness's part-scale override, set after setupAnim as the oracle does.
if let Some(scale) = case["@partScale"].as_array() {
let pose = poses.get(scale[0].as_str().unwrap_or_default());
for i in 0..3 {
pose[6 + i] = scale[1 + i].as_f64().unwrap_or(1.0) as f32;
}
}
let mut parts = BTreeMap::new();
walk(&model, "", &poses, &mut parts);
let mut emitted = Vec::new();
render::draw(
&model,
root_transform(case),
&poses,
[0.0, 0.0, 1.0, 1.0],
0xFFFF_FFFF,
240 | 240 << 8,
0,
&mut emitted,
);
let mut vertices = BTreeMap::new();
let mut cursor = 0;
drawn(&model, "", &poses, &emitted, &mut cursor, &mut vertices);
assert_eq!(cursor, emitted.len(), "{layer}: draw's walk changed");
out.push_str(&format!(
"{}\n",
json!({"parts": parts, "vertices": vertices})
));
out.push_str(&format!("{}\n", emit(&model, &mut poses, case, layer)));
}
fs::write(&args[2], out)?;
Ok(())
}
/// Every part's pose, and the vertices drawn under the harness's root transform.
fn emit(model: &Part, poses: &mut Poses, case: &Value, layer: &str) -> Value {
// The harness's part-scale override, set after setupAnim as the oracle does.
if let Some(scale) = case["@partScale"].as_array() {
let pose = poses.get(scale[0].as_str().unwrap_or_default());
for i in 0..3 {
pose[6 + i] = scale[1 + i].as_f64().unwrap_or(1.0) as f32;
}
}
let poses = &*poses;
let mut parts = BTreeMap::new();
walk(model, "", poses, &mut parts);
let mut emitted = Vec::new();
render::draw(
model,
root_transform(case),
poses,
[0.0, 0.0, 1.0, 1.0],
0xFFFF_FFFF,
240 | 240 << 8,
0,
&mut emitted,
);
let mut vertices = BTreeMap::new();
let mut cursor = 0;
drawn(model, "", poses, &emitted, &mut cursor, &mut vertices);
assert_eq!(cursor, emitted.len(), "{layer}: draw's walk changed");
json!({"parts": parts, "vertices": vertices})
}
@@ -93,8 +93,9 @@ fn encode(draws: &[GuiDraw]) -> Vec<Value> {
h,
region,
color,
blend,
} => {
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32})
json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32, "pipeline": blend.pipeline()})
}
GuiDraw::AtlasSprite {
sprite,
@@ -190,7 +191,12 @@ fn decorations(c: &Value, atlas: &HudAtlas) -> Vec<GuiDraw> {
// Spectators only see it over a spectatable target (none here).
if c["crosshair"].as_bool().unwrap_or(false) && mode != "spectator" {
let attack = (indicator == "CROSSHAIR").then(|| float("attackScale", 1.0));
draws.extend(hud_layout::crosshair(w, h, attack, false));
// crosshairPickEntity: absent, or a living entity alive or not.
let target = c["target"].as_bool();
let full = attack.is_some_and(|a| {
hud_layout::full_attack_indicator(a, float("attackDelay", 5.0), target)
});
draws.extend(hud_layout::crosshair(w, h, attack, full));
}
if mode != "spectator" {
let pop = |v: &Value| v.as_f64().map(|p| p as f32 - partial);
@@ -0,0 +1,54 @@
//! Horizon's sprite mip levels for tools/test_mipmap_parity.py: each sprite
//! loads through `sprites::Sprites` (its .mcmeta settings and transparency)
//! and `mipmap::generate` makes its levels down to 1x1, printed as RGBA hex
//! rows like VanillaMipmapOracle.
use std::{fmt::Write as _, fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
let input = fs::read_to_string(&args[0])?;
let mut lines = input.lines();
let root = Path::new(lines.next().ok_or("no resources root")?);
let names: Vec<&str> = lines.collect();
let mut sprites = horizon_client::sprites::Sprites::default();
let layers = names
.iter()
.map(|name| sprites.insert(root, name))
.collect::<horizon_client::Result<Vec<u32>>>()?;
sprites.finish();
let size = sprites.size;
let bytes = (size * size * 4) as usize;
let mut out = String::new();
for (name, layer) in names.iter().zip(layers) {
let start = layer as usize * bytes;
let base = horizon_client::mipmap::Image {
width: size,
height: size,
pixels: sprites.pixels[start..start + bytes]
.as_chunks::<4>()
.0
.to_vec(),
};
let s = sprites.mips[layer as usize];
writeln!(out, "== {name}")?;
for mip in horizon_client::mipmap::generate(
base,
size.trailing_zeros(),
s.strategy,
s.alpha_cutoff_bias,
s.has_transparent,
s.item,
) {
write!(out, "{}x{}", mip.width, mip.height)?;
for row in mip.pixels.chunks(mip.width as usize) {
out.push(' ');
for p in row {
write!(out, "{:02x}{:02x}{:02x}{:02x}", p[0], p[1], p[2], p[3])?;
}
}
out.push('\n');
}
}
fs::write(&args[1], out)?;
Ok(())
}
@@ -684,6 +684,7 @@ fn main() -> horizon_client::Result<()> {
let assets = Assets::load(root)?;
let registry = assets.registry;
let facts = BlockFacts::load(root, registry)?;
let motion = horizon_client::motion::MotionResources::load(root, &assets)?;
let data = MobData::load(root, &facts);
let types = MobTypes::load(root)?;
let biomes = Biomes::load(root)?;
@@ -911,6 +912,7 @@ fn main() -> horizon_client::Result<()> {
world: &world,
registry,
facts: &facts,
movement: &motion.blocks,
collision: &collision,
data: &data,
player: player.clone(),
@@ -4,7 +4,7 @@ use horizon_client::{
Result,
assets::Assets,
collisions,
motion::{MotionEvent, MotionResources, MotionWorld, PlayerMotion},
motion::{LAVA, MotionEvent, MotionResources, MotionWorld, PlayerMotion, WATER},
world::World,
};
use horizon_core::geometry::Vec3;
@@ -174,6 +174,31 @@ fn snapshot(out: &mut impl Write, player: &PlayerMotion) -> Result<()> {
velocity.y.to_bits(),
velocity.z.to_bits()
)),
MotionEvent::Splash {
high_speed,
volume,
pitch,
} => Some(format!(
"sound {} entity {:08x} {:08x}",
if *high_speed { "splash-high" } else { "splash" },
volume.to_bits(),
pitch.to_bits()
)),
MotionEvent::SplashParticle {
bubble,
position,
velocity,
} => Some(format!(
"splash-particle {} {:016x},{:016x},{:016x} {:016x},{:016x},{:016x}",
if *bubble { "bubble" } else { "splash" },
position.x.to_bits(),
position.y.to_bits(),
position.z.to_bits(),
velocity.x.to_bits(),
velocity.y.to_bits(),
velocity.z.to_bits()
)),
MotionEvent::SplashEvent => Some("splash-event".into()),
// The oracle marks every getAdvancements call (ENTER_BLOCK.trigger) so.
MotionEvent::EnterBlock { .. } => Some("hurt-criterion".into()),
MotionEvent::Waypoint { receiver, enabled } => Some(format!(
@@ -415,6 +440,9 @@ fn main() -> Result<()> {
p,
)?;
}
// Entity.baseTick's fluid phase alone (wasEyeInWater,
// updateFluidInteraction, lava fall halving, firstTick).
"fluid_tick" => world.fluid_base_tick()?,
"travel" => world.travel_in_air(vector(&op["value"]))?,
"tick" => {
let v = vector(&op["value"]);
@@ -541,14 +569,20 @@ fn main() -> Result<()> {
let stuck = player.stuck_multiplier;
writeln!(
out,
"block {} frozen {} {} {} {:016x},{:016x},{:016x}",
"block {} frozen {} {} {} {:016x},{:016x},{:016x} fluid {} {} {} {} {:016x} {:016x}",
check_block.0,
player.ticks_frozen,
player.in_powder_snow,
player.was_in_powder_snow,
stuck.x.to_bits(),
stuck.y.to_bits(),
stuck.z.to_bits()
stuck.z.to_bits(),
player.fluids.was_touching_water,
player.fluids.was_eye_in_water,
player.is_eye_in_fluid(WATER),
player.fluids.first_tick,
player.fluid_height(WATER).to_bits(),
player.fluid_height(LAVA).to_bits()
)?;
writeln!(
out,
File diff suppressed because it is too large Load Diff
+3
View File
@@ -63,6 +63,8 @@ pub struct Assets {
pub animations: Vec<crate::sprites::SpriteAnimation>,
pub sprite_layers: std::collections::BTreeMap<String, u32>,
pub translucent_layers: Vec<bool>,
/// Each layer's `MipmapGenerator` settings.
pub sprite_mips: Vec<crate::mipmap::Settings>,
/// Block names in `#minecraft:blocks_fluid_flow` (fluid flow vectors).
pub blocks_fluid_flow: BTreeSet<String>,
}
@@ -246,6 +248,7 @@ impl Assets {
animations: sprites.animations,
sprite_layers: sprites.layers,
translucent_layers: sprites.translucent,
sprite_mips: sprites.mips,
blocks_fluid_flow,
})
}
+44
View File
@@ -617,6 +617,18 @@ impl Audio {
let seed = self.random.next_long();
self.play_seeded(event, at, volume, pitch, seed);
}
/// `AbstractWidget.playButtonClickSound`: an unseeded, relative UI sound.
pub fn play_button_click(&mut self) {
self.play_instance(
SoundInstance::for_ui(
"minecraft:ui.button.click",
1.0,
0.25,
SoundEngine::unseeded(),
),
false,
);
}
/// `play` with the seed a sound packet carries.
pub fn play_seeded(
&mut self,
@@ -749,6 +761,38 @@ impl Sounds for Audio {
mod tests {
use super::*;
#[test]
fn button_click_uses_vanilla_ui_parameters_without_advancing_world_random() {
let mut audio = Audio::silent(Path::new("/nonexistent/horizon-test-assets"));
audio.engine.registry.add_file(
"minecraft",
br#"{"ui.button.click":{"sounds":["gui/button"]}}"#,
&|_, _| true,
);
// Exercise the mixer without opening an output device. The missing
// sample is harmless: this test checks the source the engine creates.
audio.engine.loaded = true;
audio.backend.live = true;
let mut random = audio.random.clone();
audio.play_button_click();
let instance = audio.engine.instance(1).expect("click reached the engine");
assert_eq!(instance.identifier, "minecraft:ui.button.click");
assert_eq!(instance.source, crate::sound_engine::UI);
assert_eq!(instance.volume, 0.25);
assert_eq!(instance.pitch, 1.0);
assert_eq!(instance.attenuation, Attenuation::None);
assert_eq!(instance.position, [0.0; 3]);
assert!(instance.relative);
assert!(!instance.looping);
assert_eq!(audio.random.next_long(), random.next_long());
audio.pause();
assert_eq!(
audio.backend.mixer.lock().unwrap().channels[&1].state,
State::Initial
);
audio.stop_all();
}
fn channel(samples: Vec<f32>, linear: Option<f32>, at: [f32; 3], looping: bool) -> Channel {
Channel {
samples: Some((Arc::new(samples), 48_000)),
+343
View File
@@ -0,0 +1,343 @@
//! The Microsoft account the launcher signed in, handed over in a session
//! file (docs/microsoft-account.md), and the Minecraft services call
//! online-mode servers need: authlib's MinecraftServicesSessionService.joinServer
//! through the services discovery document. The access token stays in this
//! process's memory: it is never logged, printed or written anywhere.
use std::{
path::Path,
sync::{Arc, Mutex, OnceLock},
time::{Duration, SystemTime},
};
/// MinecraftServicesEnvironment.PROD.
pub const DEFAULT_DISCOVERY: &str = "https://discovery.minecraftservices.com/minecraft/client";
/// A session file older than this is refused: it can't be replayed later.
const MAX_SESSION_FILE_AGE: Duration = Duration::from_secs(120);
/// A signed-in account (vanilla's User with type msa).
pub struct AuthSession {
pub name: String,
pub uuid: u128,
pub xuid: Option<String>,
access_token: String,
}
impl std::fmt::Debug for AuthSession {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AuthSession")
.field("name", &self.name)
.field("uuid", &horizon_protocol::crypto::uuid_string(self.uuid))
.field("access_token", &"<hidden>")
.finish()
}
}
/// A UUID with or without dashes.
pub fn parse_uuid(text: &str) -> Option<u128> {
let hex: String = text.chars().filter(|c| *c != '-').collect();
(hex.len() == 32)
.then(|| u128::from_str_radix(&hex, 16).ok())
.flatten()
}
impl AuthSession {
/// For tests and harnesses.
pub fn new(name: &str, uuid: u128, access_token: &str) -> Self {
Self {
name: name.to_owned(),
uuid,
xuid: None,
access_token: access_token.to_owned(),
}
}
/// The session file's JSON: {"name", "uuid", "access_token", "user_type": "msa", "xuid"}.
pub fn parse(text: &str) -> Result<Self, String> {
let v: serde_json::Value =
serde_json::from_str(text).map_err(|_| "the session file is not valid JSON")?;
let field = |k: &str| v.get(k).and_then(|s| s.as_str());
let name = field("name").ok_or("the session file has no name")?;
if name.is_empty() || name.chars().count() > 16 {
return Err("the session file's name is not a valid player name".into());
}
let uuid = field("uuid")
.and_then(parse_uuid)
.ok_or("the session file has no valid uuid")?;
let access_token = field("access_token")
.filter(|t| !t.is_empty())
.ok_or("the session file has no access token")?;
if field("user_type").is_some_and(|t| t != "msa") {
return Err("the session file is not a Microsoft account session".into());
}
Ok(Self {
name: name.to_owned(),
uuid,
xuid: field("xuid").map(str::to_owned),
access_token: access_token.to_owned(),
})
}
/// Read the session file the launcher wrote and delete it at once. It
/// must be fresh and, on Unix, readable by its owner only.
pub fn load(path: &Path) -> Result<Self, String> {
let meta = std::fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?;
let refuse = |why: &str| {
let _ = std::fs::remove_file(path);
Err(format!("{}: {why}", path.display()))
};
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o077 != 0 {
return refuse("other users can read it");
}
}
let age = meta
.modified()
.ok()
.and_then(|m| SystemTime::now().duration_since(m).ok())
.unwrap_or_default();
if age > MAX_SESSION_FILE_AGE {
return refuse("it is too old (start the game from the launcher)");
}
let text = std::fs::read_to_string(path);
let _ = std::fs::remove_file(path);
Self::parse(&text.map_err(|e| format!("{}: {e}", path.display()))?)
}
}
static CURRENT: OnceLock<Arc<AuthSession>> = OnceLock::new();
/// The account this game was started with (set once at start).
pub fn set_current(session: AuthSession) {
let _ = CURRENT.set(Arc::new(session));
}
pub fn current() -> Option<Arc<AuthSession>> {
CURRENT.get().cloned()
}
/// Why joining a server through the session service failed, like the
/// AuthenticationException subclasses authlib throws.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum JoinError {
/// No answer, or a 5xx (AuthenticationUnavailableException).
Unavailable,
/// 401 or ForbiddenOperationException (InvalidCredentialsException).
InvalidSession,
/// InsufficientPrivilegesException: multiplayer is off for the account.
InsufficientPrivileges,
/// multiplayer.access.banned or FORCED_USERNAME_CHANGE.
Banned,
/// Anything else, with the service's message.
Other(String),
}
impl JoinError {
/// MinecraftClientHttpException.toAuthenticationException.
pub fn from_response(status: u16, body: &str) -> Self {
let v: serde_json::Value = serde_json::from_str(body).unwrap_or_default();
let error = v.get("error").and_then(|e| e.as_str()).unwrap_or("");
match error {
"ForbiddenOperationException" => return Self::InvalidSession,
"multiplayer.access.banned" | "FORCED_USERNAME_CHANGE" => return Self::Banned,
"InsufficientPrivilegesException" => return Self::InsufficientPrivileges,
_ => {}
}
match status {
401 => Self::InvalidSession,
500.. => Self::Unavailable,
_ => Self::Other(
v.get("errorMessage")
.and_then(|m| m.as_str())
.map_or_else(|| format!("Status: {status}"), str::to_owned),
),
}
}
/// ClientHandshakePacketListenerImpl.authenticateServer's message: the
/// key of the reason inside "disconnect.loginFailedInfo", or its text.
pub fn reason(&self) -> Result<&'static str, &str> {
match self {
Self::Unavailable => Ok("disconnect.loginFailedInfo.serversUnavailable"),
Self::InvalidSession => Ok("disconnect.loginFailedInfo.invalidSession"),
Self::InsufficientPrivileges => Ok("disconnect.loginFailedInfo.insufficientPrivileges"),
Self::Banned => Ok("disconnect.loginFailedInfo.userBanned"),
Self::Other(message) => Err(message),
}
}
}
/// The services discovery document URL: `HORIZON_API_DISCOVERY` overrides
/// it like authlib's `-Dminecraft.api.discovery.host`.
pub fn discovery_url() -> String {
std::env::var("HORIZON_API_DISCOVERY")
.ok()
.filter(|u| !u.is_empty())
.unwrap_or_else(|| DEFAULT_DISCOVERY.to_owned())
}
fn agent() -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout(Duration::from_secs(15))
.user_agent(concat!("Horizon/", env!("CARGO_PKG_VERSION")))
.build()
}
/// The discovery document, fetched once per game (a failure is retried next time).
fn discovery() -> Result<Arc<serde_json::Value>, JoinError> {
static CACHE: Mutex<Option<Arc<serde_json::Value>>> = Mutex::new(None);
if let Some(d) = CACHE.lock().unwrap().clone() {
return Ok(d);
}
let doc: serde_json::Value = agent()
.get(&discovery_url())
.call()
.ok()
.and_then(|r| r.into_string().ok())
.and_then(|t| serde_json::from_str(&t).ok())
.ok_or(JoinError::Unavailable)?;
let doc = Arc::new(doc);
*CACHE.lock().unwrap() = Some(doc.clone());
Ok(doc)
}
/// MinecraftServicesDiscoveryService.getUrl(service, endpoint).
pub fn endpoint(doc: &serde_json::Value, service: &str, name: &str) -> Option<String> {
doc.pointer(&format!("/discovery/{service}/endpoints/{name}/uri"))
.and_then(|u| u.as_str())
.map(str::to_owned)
}
/// The JoinMinecraftServerRequest body; `selectedProfile` is the undashed UUID.
pub fn join_request(session: &AuthSession, server_hash: &str) -> String {
serde_json::json!({
"accessToken": session.access_token,
"selectedProfile": format!("{:032x}", session.uuid),
"serverId": server_hash,
})
.to_string()
}
/// MinecraftServicesSessionService.joinServer: tell the session service this
/// account is joining the server whose hash is `server_hash`.
pub fn join_server(session: &AuthSession, server_hash: &str) -> Result<(), JoinError> {
let doc = discovery()?;
let url = endpoint(&doc, "session", "join").ok_or(JoinError::Unavailable)?;
match agent()
.post(&url)
.set("Content-Type", "application/json; charset=utf-8")
.send_string(&join_request(session, server_hash))
{
Ok(_) => Ok(()),
Err(ureq::Error::Status(status, response)) => Err(JoinError::from_response(
status,
&response.into_string().unwrap_or_default(),
)),
Err(ureq::Error::Transport(_)) => Err(JoinError::Unavailable),
}
}
#[cfg(test)]
mod tests {
use super::*;
const UUID: u128 = 0x069a79f444e94726a5befca90e38aaf5;
fn write(dir: &Path, text: &str, mode: u32) -> std::path::PathBuf {
let path = dir.join("session.json");
std::fs::write(&path, text).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
}
let _ = mode;
path
}
#[test]
fn session_files_are_read_once_and_must_be_private() {
let dir = std::env::temp_dir().join(format!("horizon-auth-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let text = r#"{"name":"Notch","uuid":"069a79f4-44e9-4726-a5be-fca90e38aaf5","access_token":"mock-token","user_type":"msa"}"#;
let path = write(&dir, text, 0o600);
let s = AuthSession::load(&path).unwrap();
assert_eq!((s.name.as_str(), s.uuid), ("Notch", UUID));
assert!(!path.exists(), "deleted after reading");
assert!(!format!("{s:?}").contains("mock-token"));
#[cfg(unix)]
{
let path = write(&dir, text, 0o644);
assert!(
AuthSession::load(&path)
.unwrap_err()
.contains("other users")
);
assert!(!path.exists());
}
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn session_file_fields() {
assert!(
AuthSession::parse(r#"{"name":"Notch","uuid":"069a79f444e94726a5befca90e38aaf5"}"#)
.is_err()
);
assert!(
AuthSession::parse(
r#"{"name":"","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t"}"#
)
.is_err()
);
assert!(AuthSession::parse(r#"{"name":"A","uuid":"nope","access_token":"t"}"#).is_err());
assert!(AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","user_type":"legacy"}"#).is_err());
let s = AuthSession::parse(r#"{"name":"A","uuid":"069a79f444e94726a5befca90e38aaf5","access_token":"t","xuid":"25"}"#).unwrap();
assert_eq!(s.xuid.as_deref(), Some("25"));
}
#[test]
fn join_request_like_authlib() {
let s = AuthSession::new("Notch", UUID, "tok");
let v: serde_json::Value = serde_json::from_str(&join_request(&s, "-7c9d")).unwrap();
assert_eq!(
v,
serde_json::json!({"accessToken": "tok", "selectedProfile": "069a79f444e94726a5befca90e38aaf5", "serverId": "-7c9d"})
);
}
#[test]
fn errors_map_like_authlib() {
let e = |status, body| JoinError::from_response(status, body);
assert_eq!(
e(
403,
r#"{"error":"ForbiddenOperationException","errorMessage":"Invalid token"}"#
),
JoinError::InvalidSession
);
assert_eq!(e(401, ""), JoinError::InvalidSession);
assert_eq!(
e(403, r#"{"error":"InsufficientPrivilegesException"}"#),
JoinError::InsufficientPrivileges
);
assert_eq!(
e(403, r#"{"error":"multiplayer.access.banned"}"#),
JoinError::Banned
);
assert_eq!(e(503, "down"), JoinError::Unavailable);
assert_eq!(
e(429, r#"{"errorMessage":"Too many"}"#),
JoinError::Other("Too many".into())
);
assert_eq!(
JoinError::InvalidSession.reason(),
Ok("disconnect.loginFailedInfo.invalidSession")
);
}
#[test]
fn discovery_endpoints() {
let doc = serde_json::json!({"discovery": {"session": {"endpoints": {"join": {"uri": "https://s/join"}}}}});
assert_eq!(
endpoint(&doc, "session", "join").as_deref(),
Some("https://s/join")
);
assert_eq!(endpoint(&doc, "session", "verify"), None);
}
}
+39 -1
View File
@@ -9,9 +9,13 @@ use crate::{
hud::{HudAtlas, HudBatch},
hud_layout::{self, GuiDraw, PoseOp},
screen_draw::{self as d, Draw, Measure, TextField},
text::{self, Style, Text},
text::{self, ClickEvent, Style, Text},
};
#[cfg(test)]
#[path = "chat_tests.rs"]
mod tests;
/// GuiMessageTag.systemSinglePlayer's indicator colour.
pub const SYSTEM_INDICATOR: u32 = 0xD0D0D0;
@@ -293,6 +297,35 @@ impl Chat {
let draws = self.layout(batch.height as i32, ticks, focused);
hud_layout::paint(batch, atlas, &draws);
}
/// The click action under a GUI-space cursor while chat is focused.
pub fn click_at(
&self,
font: &crate::font::Font,
height: i32,
x: f64,
y: f64,
) -> Option<ClickEvent> {
let scale = self.options.scale as f32;
let mut x = x / f64::from(scale) - 4.0;
let bottom = hud_layout::floor((height - 40) as f32 / scale);
let from_bottom = f64::from(bottom) - y / f64::from(scale);
if x < 0.0 || x >= f64::from(self.max_width()) || from_bottom <= 0.0 {
return None;
}
let row = (from_bottom / f64::from(self.options.line_height())).ceil() as usize - 1;
if row >= self.lines_per_page(true) {
return None;
}
let line = self.lines.get(self.scroll + row)?;
let content = line.content.resolve_legacy();
for (c, style) in content.chars() {
x -= f64::from(font.advance(c, style));
if x < 0.0 {
return style.click.clone();
}
}
None
}
/// Plain text of the newest messages (for tests and the control socket).
pub fn recent_lines(&self, n: usize) -> Vec<String> {
self.messages
@@ -420,6 +453,11 @@ impl ChatScreen {
pub fn value(&self) -> &str {
&self.input.value
}
/// Replace the input for a suggest-command link and refresh completions.
pub fn suggest_command(&mut self, m: &Measure, c: &Commands, command: &str) {
self.input.set_value(m, command);
self.edited(m, c);
}
/// `ChatScreen.resize`: a new screen with the current text.
pub fn resize(&mut self, m: &Measure, c: &Commands, width: i32, height: i32) {
if (width, height) != (self.width, self.height) {
+165
View File
@@ -0,0 +1,165 @@
use super::*;
use crate::{font::Font, hud::Rect};
use std::{collections::HashMap, path::Path};
fn font() -> Font {
// The missing-glyph metrics let these tests run without game assets.
Font::load(
Path::new("/nonexistent-horizon-chat-test-resources"),
&HashMap::new(),
&[],
(1, 1),
(0, 0),
Rect {
u0: 0.0,
v0: 0.0,
u1: 1.0,
v1: 1.0,
w: 1,
h: 1,
},
)
}
fn add(chat: &mut Chat, font: &Font, content: Text) {
for content in font.wrap_components(&content, chat.max_width()) {
chat.lines.insert(
0,
Line {
added: 0,
content,
indicator: None,
},
);
}
}
#[test]
fn clicking_seed_copies_the_raw_value_only_inside_the_link() {
let font = font();
for seed in [1, -42, i64::MIN, i64::MAX] {
let mut chat = Chat::default();
let seed_text = Text::copyable(seed.to_string()).with_color(text::GOLD);
assert_eq!(seed_text.plain(), format!("[{seed}]"));
assert_eq!(seed_text.spans[0].style.color, Some(text::GOLD));
assert_eq!(seed_text.spans[1].style.color, Some(text::GREEN));
assert_eq!(seed_text.spans[2].style.color, Some(text::GOLD));
add(&mut chat, &font, Text::literal("Seed: ").append(seed_text));
let expected = Some(ClickEvent::CopyToClipboard(seed.to_string()));
let start = 4.0 + f64::from(font.width("Seed: ["));
let end = start + f64::from(font.width(&seed.to_string()));
assert_eq!(chat.click_at(&font, 360, start, 315.0), expected);
assert_eq!(chat.click_at(&font, 360, end - 0.5, 315.0), expected);
for (x, y) in [
(start - 0.5, 315.0),
(end, 315.0),
(3.0, 315.0),
(start, 320.0),
(start, 310.0),
] {
assert_eq!(chat.click_at(&font, 360, x, y), None, "{x}, {y}");
}
}
}
#[test]
fn click_targets_match_rendered_spans_when_scaled_wrapped_and_scrolled() {
let font = font();
let screenshot = ClickEvent::OpenFile("/tmp/My screenshots/世界.png".into());
for scale in [0.5, 0.75, 1.0] {
for line_spacing in [0.0, 0.5, 1.0] {
let mut chat = Chat::default();
chat.options.scale = scale;
chat.options.width = 0.0;
chat.options.line_spacing = line_spacing;
for _ in 0..20 {
add(
&mut chat,
&font,
Text::literal("Saved screenshot as ").append(Text::styled(
"2026-10-14_18.55.14.png",
Style {
click: Some(screenshot.clone()),
bold: Some(true),
underlined: Some(true),
..Style::default()
},
)),
);
}
for scroll in [0, 3, 12] {
chat.scroll = scroll;
let mut links = 0;
for draw in chat.layout(361, 0, true) {
if let GuiDraw::Text { text, x, y, .. } = draw {
let mut at = x as f64;
for (c, style) in text.chars() {
let width = f64::from(font.advance(c, style));
let cursor_x = (4.0 + at + width / 2.0) * scale;
let cursor_y = (y as f64 + 3.0) * scale;
assert_eq!(
chat.click_at(&font, 361, cursor_x, cursor_y),
style.click,
"scale={scale}, spacing={line_spacing}, scroll={scroll}, char={c}"
);
links += usize::from(style.click.is_some());
at += width;
}
}
}
assert!(links > 0);
// The history above the focused viewport is not clickable.
let top = ((361 - 40) as f64 / scale).floor()
- chat.lines_per_page(true) as f64 * chat.options.line_height() as f64;
assert_eq!(
chat.click_at(&font, 361, 10.0 * scale, (top - 1.0) * scale),
None
);
}
}
}
}
#[test]
fn locate_coordinates_fill_chat_with_teleport_without_submitting() {
let font = font();
let m = Measure(&font);
let registries = Registries::default();
let commands = Commands {
dispatcher: crate::command::vanilla::game_dispatcher(),
registries: &registries,
};
// Structures and POIs use relative Y; biome results include absolute Y.
for (y, expected) in [
(None, "/tp @s -1136 ~ 848"),
(Some(73), "/tp @s -1136 73 848"),
] {
let link = Text::teleport_link(-1136, y, 848);
assert_eq!(link.component()["click_event"]["action"], "suggest_command");
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 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 {
panic!("locate coordinates must suggest a command");
};
screen.suggest_command(&m, &commands, &command);
assert_eq!(screen.value(), expected);
assert_eq!(screen.input.cursor, expected.chars().count());
assert_eq!(screen.input.highlight, screen.input.cursor);
// Submission is a separate, explicit Enter press.
assert_eq!(
screen.key(
&m,
&commands,
&[],
winit::keyboard::KeyCode::Enter,
false,
false
),
ChatAction::Submit(expected.to_owned())
);
}
}
+34 -1
View File
@@ -628,7 +628,8 @@ impl Enchantments {
} else {
spec
};
spec.is_null() && entity.is_some() || self.entity_matches(spec, entity)
(spec.is_null() && entity.is_some() || self.entity_matches(spec, entity))
&& movement_matches(&c["predicate"], role_state(c, ctx))
}
"minecraft:random_chance" => {
let chance = match &c["chance"] {
@@ -661,6 +662,38 @@ pub struct EffectContext<'a> {
pub this: Option<&'a str>,
pub attacker: Option<&'a str>,
pub direct_attacker: Option<&'a str>,
/// The direct attacker's fall distance and whether it flies (elytra or
/// abilities), for `movement` and `flags` predicates.
pub direct_motion: Option<(f64, bool)>,
}
/// The fall distance and flying flag known for an `entity_properties` role.
fn role_state(c: &Value, ctx: &EffectContext<'_>) -> Option<(f64, bool)> {
match c["entity"].as_str().unwrap_or("this") {
"direct_attacker" => ctx.direct_motion,
_ => None,
}
}
/// `EntityPredicate`'s `minecraft:movement` fall distance and
/// `minecraft:flags` is_flying (the parts enchantment requirements use); an
/// entity whose state is unknown matches neither.
fn movement_matches(predicate: &Value, state: Option<(f64, bool)>) -> bool {
let fall = &predicate["minecraft:movement"]["fall_distance"];
let flying = predicate["minecraft:flags"]["is_flying"].as_bool();
if fall.is_null() && flying.is_none() {
return true;
}
let Some((distance, is_flying)) = state else {
return false;
};
// MinMaxBounds.Doubles: a number is an exact bound.
let bound = |key: &str| {
fall.as_f64()
.or_else(|| fall.get(key).and_then(Value::as_f64))
};
// MinMaxBounds.Doubles.matches
bound("min").is_none_or(|min| min <= distance)
&& bound("max").is_none_or(|max| distance <= max)
&& flying.is_none_or(|f| f == is_flying)
}
fn next_int<R: RandomSource>(random: &mut R, bound: i32) -> i32 {
random.next_int_bound(bound.max(1)).unwrap_or(0)
+38
View File
@@ -0,0 +1,38 @@
//! `EndCrystalRenderer` and `EndCrystalModel.setupAnim`: the crystal's bob
//! and the poses of its base, glass and cube.
use crate::mobs::{Part, anim::Poses};
use horizon_core::geometry::trig::Mth;
/// `EndCrystalRenderer.getY`: the crystal's bob below its resting height.
pub fn y(age: f32) -> f32 {
let hh = (age * 0.2).msin() / 2.0 + 0.5;
(hh * hh + hh) * 0.4 - 1.4
}
/// `EndCrystalModel.setupAnim`: the base shown or not, the glass raised by
/// half the bob (in model pixels) and the three cubes turned with
/// `ModelPart.rotateBy`, which stores the composed rotation as ZYX angles.
pub fn poses(model: &Part, age: f32, show_bottom: bool) -> Poses {
let mut poses = Poses::new(model);
poses.visible("base", show_bottom);
let speed = age * 3.0;
let sin45 = std::f32::consts::FRAC_PI_4.sin();
let tilt = glam::Quat::from_axis_angle(
glam::Vec3::new(sin45, 0.0, sin45),
std::f32::consts::FRAC_PI_3,
);
let spin = glam::Quat::from_rotation_y(speed.to_radians());
poses.get("outer_glass")[1] += y(age) * 16.0 / 2.0;
for (part, rotation) in [
("outer_glass", spin * tilt),
("inner_glass", tilt * spin),
("cube", tilt * spin),
] {
let (z, y, x) = rotation.to_euler(glam::EulerRot::ZYX);
let pose = poses.get(part);
pose[3] = x;
pose[4] = y;
pose[5] = z;
}
poses
}
-74
View File
@@ -110,80 +110,6 @@ impl ItemEntity {
self.age < 6000 && self.position.y > -128.0
}
}
/// Arrows (`AbstractArrow.tick`): 0.99 drag, 0.05 gravity, sticking in blocks.
#[derive(Clone, Debug)]
pub struct Arrow {
/// Shot by the player (hits mobs) rather than a mob (hits the player).
pub from_player: bool,
pub critical: bool,
pub position: Vec3,
pub previous: Vec3,
pub velocity: Vec3,
pub stuck: bool,
pub age: u32,
pub base_damage: f64,
}
pub enum ArrowHit {
None,
Player(f32),
}
impl Arrow {
pub fn tick(
&mut self,
world: &World,
facts: &BlockFacts,
player: Option<Aabb>,
) -> (bool, ArrowHit) {
self.previous = self.position;
self.age += 1;
if self.stuck {
return (self.age < 1200, ArrowHit::None);
}
let steps = 4;
for _ in 0..steps {
let next = Vec3::new(
self.position.x + self.velocity.x / f64::from(steps),
self.position.y + self.velocity.y / f64::from(steps),
self.position.z + self.velocity.z / f64::from(steps),
);
if let Some(b) = player {
let (min, max) = (b.min_position(), b.max_position());
if next.x >= min.x
&& next.x <= max.x
&& next.y >= min.y
&& next.y <= max.y
&& next.z >= min.z
&& next.z <= max.z
{
let speed = (self.velocity.x.powi(2)
+ self.velocity.y.powi(2)
+ self.velocity.z.powi(2))
.sqrt();
// AbstractArrow.onHitEntity: ceil(speed * baseDamage).
let damage = (speed * self.base_damage).ceil().max(0.0) as f32;
return (false, ArrowHit::Player(damage));
}
}
let block = world.block(
next.x.floor() as i32,
next.y.floor() as i32,
next.z.floor() as i32,
);
if facts.get(block).full_collision {
self.stuck = true;
self.age = 0;
return (true, ArrowHit::None);
}
self.position = next;
}
self.velocity = Vec3::new(
self.velocity.x * 0.99,
self.velocity.y * 0.99 - 0.05,
self.velocity.z * 0.99,
);
(self.position.y > -128.0 && self.age < 1200, ArrowHit::None)
}
}
/// ExperienceOrb: gravity 0.03, homing towards the player within 8 blocks.
#[derive(Clone, Debug)]
pub struct ExperienceOrb {
+89 -54
View File
@@ -5,8 +5,10 @@
//! Horizon does not model (variants, attributes, equipment, custom names)
//! survive a Horizon save.
use crate::{
entities::{ArmorStand, Arrow, ExperienceOrb, ItemEntity, ItemFrame, Painting},
mobs::{Mob, MobType},
arrows::Pickup,
entities::{ArmorStand, ExperienceOrb, ItemEntity, ItemFrame, Painting},
mobs::{Mob, MobType, Who},
projectiles::{Projectile, ProjectileKind},
save::{
doubles, float, floats, item_from_nbt, item_to_nbt, number, put, read_doubles, text,
uuid_from_tag,
@@ -168,14 +170,11 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
}
match id {
"minecraft:creeper" => {
for (key, value) in [
("Fuse", Tag::Short(30)),
("ExplosionRadius", Tag::Byte(3)),
("ignited", Tag::Byte(0)),
] {
for (key, value) in [("Fuse", Tag::Short(30)), ("ExplosionRadius", Tag::Byte(3))] {
map.entry(key.into()).or_insert(value);
}
map.insert("powered".into(), Tag::Byte(i8::from(m.extra.charged)));
map.insert("ignited".into(), Tag::Byte(i8::from(m.extra.flag)));
}
"minecraft:cat" => {
if let Some(owner) = m.extra.owner {
@@ -600,6 +599,8 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.no_gravity = m.no_gravity || flag(tag, "NoGravity");
if m.species() == crate::mobs::Species::Creeper {
m.extra.charged = flag(tag, "powered");
// Creeper.readAdditionalSaveData: `ignited` lights the fuse.
m.extra.flag = flag(tag, "ignited");
}
if matches!(
m.species(),
@@ -907,68 +908,102 @@ pub fn orbs_from_nbt(tag: &Tag) -> Vec<ExperienceOrb> {
vec![orb; count]
}
/// `AbstractArrow`: damage, crit, inGround, life, pickup, item.
pub fn arrow_to_nbt(a: &Arrow, uuid: [i32; 4], owner: Option<[i32; 4]>) -> Tag {
let v = a.velocity;
let horizontal = (v.x * v.x + v.z * v.z).sqrt();
let rotation = [
(v.x.atan2(v.z).to_degrees()) as f32,
(v.y.atan2(horizontal).to_degrees()) as f32,
];
/// `Projectile` + `AbstractArrow.addAdditionalSaveData` of a live arrow;
/// `in_block` is its `inBlockState`, `raw` the compound it was loaded with.
pub fn arrow_to_nbt(
p: &Projectile,
uuid: [i32; 4],
owner: Option<[i32; 4]>,
in_block: Option<Tag>,
raw: Option<&Tag>,
) -> Option<Tag> {
let a = p.arrow.as_deref()?;
let ProjectileKind::Arrow {
base_damage,
critical,
..
} = p.kind
else {
return None;
};
let base = Base {
id: "minecraft:arrow",
uuid,
position: a.position,
motion: a.velocity,
rotation,
position: p.position,
motion: p.velocity,
rotation: [p.yaw, p.pitch],
on_ground: false,
fall_distance: 0.0,
fall_distance: a.fall_distance,
};
let mut tag = base.tag(None);
let mut tag = base.tag(raw);
for (key, value) in [
("damage", Tag::Double(a.base_damage.to_bits())),
("crit", Tag::Byte(i8::from(a.critical))),
("inGround", Tag::Byte(i8::from(a.stuck))),
(
"life",
Tag::Short(if a.stuck { a.age.min(1200) as i16 } else { 0 }),
),
// Pickup: allowed for the player's arrows, disallowed for mobs'.
("pickup", Tag::Byte(i8::from(a.from_player))),
("shake", Tag::Byte(0)),
("PierceLevel", Tag::Byte(0)),
("HasBeenShot", Tag::Byte(1)),
("SoundEvent", string("minecraft:entity.arrow.hit")),
(
"item",
Tag::compound([("id", string("minecraft:arrow")), ("count", Tag::Int(1))]),
),
("Fire", Tag::Short(a.fire_ticks as i16)),
("life", Tag::Short(a.life as i16)),
("shake", Tag::Byte(a.shake as i8)),
("inGround", Tag::Byte(i8::from(a.in_ground))),
("pickup", Tag::Byte(a.pickup.byte())),
("damage", Tag::Double(base_damage.to_bits())),
("crit", Tag::Byte(i8::from(critical))),
("PierceLevel", Tag::Byte(a.pierce as i8)),
("HasBeenShot", Tag::Byte(i8::from(a.has_been_shot))),
("item", item_to_nbt(&a.pickup_item)),
] {
put(&mut tag, key, value);
}
if let Tag::Compound(map) = &mut tag {
map.entry("SoundEvent".into())
.or_insert_with(|| string("minecraft:entity.arrow.hit"));
// Projectile: LeftOwner only when set; Owner as the UUID.
map.remove(&"LeftOwner".into());
map.remove(&"inBlockState".into());
}
if p.left_owner {
put(&mut tag, "LeftOwner", Tag::Byte(1));
}
if let Some(state) = in_block {
put(&mut tag, "inBlockState", state);
}
if let Some(owner) = owner {
put(&mut tag, "Owner", Tag::IntArray(owner.to_vec()));
}
tag
Some(tag)
}
pub fn arrow_from_nbt(tag: &Tag, player: Option<[i32; 4]>) -> Option<Arrow> {
/// A saved arrow as a live one (`readAdditionalSaveData`), with its
/// `inBlockState` compound for the caller to resolve. `effect` is the tipped
/// arrow's lasting effect from its item.
pub fn arrow_from_nbt(
tag: &Tag,
player: Option<[i32; 4]>,
effect: impl FnOnce(&crate::items::ItemStack) -> Option<(&'static str, i32)>,
) -> Option<(Projectile, Option<Tag>)> {
let position = position(tag)?;
let stuck = flag(tag, "inGround");
Some(Arrow {
from_player: player.is_some() && uuid_from_tag(tag.get("Owner")) == player
|| number(tag.get("pickup")) == Some(1),
critical: flag(tag, "crit"),
position,
previous: position,
velocity: motion(tag),
stuck,
age: if stuck {
number(tag.get("life")).unwrap_or(0).max(0) as u32
} else {
0
},
let owner = uuid_from_tag(tag.get("Owner"));
let from_player = player.is_some() && owner == player;
let item = tag
.get("item")
.and_then(item_from_nbt)
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:arrow", 1));
let kind = ProjectileKind::Arrow {
base_damage: float(tag.get("damage")).unwrap_or(2.0),
})
critical: flag(tag, "crit"),
effect: effect(&item),
};
let mut p = Projectile::new(kind, position, from_player.then_some(Who::Player));
p.velocity = motion(tag);
[p.yaw, p.pitch] = rotation(tag);
p.left_owner = flag(tag, "LeftOwner");
let a = p.arrow.as_mut()?;
a.life = number(tag.get("life")).unwrap_or(0) as i16 as i32;
a.shake = (number(tag.get("shake")).unwrap_or(0) as i8 as u8).into();
a.in_ground = flag(tag, "inGround");
a.pickup = Pickup::from_byte(number(tag.get("pickup")).unwrap_or(0));
a.pierce = number(tag.get("PierceLevel")).unwrap_or(0) as u8;
a.has_been_shot = flag(tag, "HasBeenShot");
a.fire_ticks = number(tag.get("Fire")).unwrap_or(0) as i16 as i32;
a.fall_distance = float(tag.get("fall_distance")).unwrap_or(0.0);
a.pickup_item = item;
p.stuck = a.in_ground;
Some((p, tag.get("inBlockState").cloned()))
}
/// `FallingBlockEntity`: BlockState, Time, DropItem, HurtEntities.
+796
View File
@@ -0,0 +1,796 @@
//! Horizon's optional extras (zoom, FPS counter, keystroke overlay): their
//! settings, kept in `horizon-extras.txt` next to `options.txt` so that file
//! stays exactly vanilla's, and the logic behind them. Every extra is off by
//! default; see `docs/extras.md`.
use std::{collections::VecDeque, fs, path::Path};
pub const FILE: &str = "horizon-extras.txt";
/// The name the options screen uses while the zoom key waits for a key.
pub const ZOOM_KEY: &str = "horizon.zoom";
/// Zoom levels the default cycles through, and the wheel's limits.
pub const ZOOM_LEVELS: [u8; 6] = [2, 3, 4, 6, 8, 10];
pub const ZOOM_MIN: f32 = 1.25;
/// `Camera.tickFov` keeps the field-of-view modifier at 0.1 or more.
pub const ZOOM_MAX: f32 = 10.0;
/// Each wheel step multiplies the zoom by this.
const ZOOM_STEP: f32 = 1.25;
/// The minimap's sizes in GUI pixels, and its zooms in blocks per pixel.
pub const MINIMAP_SIZES: [(u8, &str); 3] = [(64, "Small"), (96, "Medium"), (128, "Large")];
pub const MINIMAP_ZOOMS: [f32; 4] = [0.5, 1.0, 2.0, 4.0];
/// A screen corner for an overlay.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Corner {
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
impl Corner {
pub const ALL: [Corner; 4] = [
Corner::TopLeft,
Corner::TopRight,
Corner::BottomLeft,
Corner::BottomRight,
];
pub fn name(self) -> &'static str {
match self {
Corner::TopLeft => "top_left",
Corner::TopRight => "top_right",
Corner::BottomLeft => "bottom_left",
Corner::BottomRight => "bottom_right",
}
}
pub fn label(self) -> &'static str {
match self {
Corner::TopLeft => "Top left",
Corner::TopRight => "Top right",
Corner::BottomLeft => "Bottom left",
Corner::BottomRight => "Bottom right",
}
}
fn parse(s: &str, default: Corner) -> Corner {
Self::ALL
.into_iter()
.find(|c| c.name() == s)
.unwrap_or(default)
}
pub fn top(self) -> bool {
matches!(self, Corner::TopLeft | Corner::TopRight)
}
pub fn left(self) -> bool {
matches!(self, Corner::TopLeft | Corner::BottomLeft)
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Extras {
pub zoom: bool,
/// A vanilla key name (`key.keyboard.z`).
pub zoom_key: String,
/// The zoom the key starts at.
pub zoom_level: u8,
/// Ease through vanilla's FOV easing (as the spyglass does).
pub zoom_smooth: bool,
/// Divide mouse turning by the zoom.
pub zoom_sensitivity: bool,
pub fps: bool,
pub fps_corner: Corner,
/// Also show the minimum and 1% low.
pub fps_lows: bool,
pub keystrokes: bool,
pub keystrokes_corner: Corner,
/// Clicks per second under the mouse buttons.
pub keystrokes_cps: bool,
pub minimap: bool,
pub minimap_corner: Corner,
/// Side in GUI pixels (`MINIMAP_SIZES`).
pub minimap_size: u8,
pub minimap_round: bool,
/// Blocks per pixel (`MINIMAP_ZOOMS`).
pub minimap_zoom: f32,
/// Turn with the player (forward up) instead of north up.
pub minimap_rotate: bool,
/// Retry lost multiplayer connections (`reconnect`).
pub auto_reconnect: bool,
}
impl Default for Extras {
fn default() -> Self {
Self {
zoom: false,
zoom_key: "key.keyboard.z".into(),
zoom_level: 4,
zoom_smooth: true,
zoom_sensitivity: true,
fps: false,
fps_corner: Corner::TopLeft,
fps_lows: false,
keystrokes: false,
keystrokes_corner: Corner::TopLeft,
keystrokes_cps: true,
minimap: false,
minimap_corner: Corner::TopRight,
minimap_size: 96,
minimap_round: false,
minimap_zoom: 1.0,
minimap_rotate: false,
auto_reconnect: false,
}
}
}
fn bool_text(v: bool) -> &'static str {
if v { "true" } else { "false" }
}
impl Extras {
pub fn load(dir: &Path) -> Self {
fs::read_to_string(dir.join(FILE))
.map(|t| Self::parse(&t))
.unwrap_or_default()
}
pub fn parse(text: &str) -> Self {
let mut e = Self::default();
for line in text.lines() {
let Some((key, value)) = line.split_once(':') else {
continue;
};
let value = value.trim();
let flag = |d: bool| match value {
"true" => true,
"false" => false,
_ => d,
};
match key.trim() {
"zoom" => e.zoom = flag(e.zoom),
"zoomKey" if value.starts_with("key.") => e.zoom_key = value.to_owned(),
"zoomLevel" => {
if let Ok(v) = value.parse::<u8>() {
e.zoom_level = v.clamp(2, ZOOM_MAX as u8);
}
}
"zoomSmooth" => e.zoom_smooth = flag(e.zoom_smooth),
"zoomSensitivity" => e.zoom_sensitivity = flag(e.zoom_sensitivity),
"fps" => e.fps = flag(e.fps),
"fpsCorner" => e.fps_corner = Corner::parse(value, e.fps_corner),
"fpsLows" => e.fps_lows = flag(e.fps_lows),
"keystrokes" => e.keystrokes = flag(e.keystrokes),
"keystrokesCorner" => {
e.keystrokes_corner = Corner::parse(value, e.keystrokes_corner)
}
"keystrokesCps" => e.keystrokes_cps = flag(e.keystrokes_cps),
"minimap" => e.minimap = flag(e.minimap),
"minimapCorner" => e.minimap_corner = Corner::parse(value, e.minimap_corner),
"minimapSize" => {
if let Some(&(v, _)) = MINIMAP_SIZES.iter().find(|s| s.0.to_string() == value) {
e.minimap_size = v;
}
}
"minimapShape" => e.minimap_round = value == "round",
"minimapZoom" => {
if let Some(&z) = MINIMAP_ZOOMS.iter().find(|z| z.to_string() == value) {
e.minimap_zoom = z;
}
}
"minimapRotate" => e.minimap_rotate = flag(e.minimap_rotate),
"autoReconnect" => e.auto_reconnect = flag(e.auto_reconnect),
_ => {}
}
}
e
}
pub fn serialize(&self) -> String {
format!(
"zoom:{}\nzoomKey:{}\nzoomLevel:{}\nzoomSmooth:{}\nzoomSensitivity:{}\nfps:{}\nfpsCorner:{}\nfpsLows:{}\nkeystrokes:{}\nkeystrokesCorner:{}\nkeystrokesCps:{}\nminimap:{}\nminimapCorner:{}\nminimapSize:{}\nminimapShape:{}\nminimapZoom:{}\nminimapRotate:{}\nautoReconnect:{}\n",
bool_text(self.zoom),
self.zoom_key,
self.zoom_level,
bool_text(self.zoom_smooth),
bool_text(self.zoom_sensitivity),
bool_text(self.fps),
self.fps_corner.name(),
bool_text(self.fps_lows),
bool_text(self.keystrokes),
self.keystrokes_corner.name(),
bool_text(self.keystrokes_cps),
bool_text(self.minimap),
self.minimap_corner.name(),
self.minimap_size,
if self.minimap_round {
"round"
} else {
"square"
},
self.minimap_zoom,
bool_text(self.minimap_rotate),
bool_text(self.auto_reconnect),
)
}
/// Written only once something differs from the defaults, so a vanilla
/// setup gains no file.
pub fn save(&self, dir: &Path) {
let path = dir.join(FILE);
if *self == Self::default() && !path.exists() {
return;
}
let _ = fs::write(path, self.serialize());
}
}
/// The zoom key's state: held or not, and the zoom the wheel has set.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Zoom {
held: bool,
factor: f32,
}
impl Default for Zoom {
fn default() -> Self {
Self {
held: false,
factor: 1.0,
}
}
}
impl Zoom {
/// The key went down: start at the default level.
pub fn press(&mut self, level: u8) {
self.held = true;
self.factor = f32::from(level).clamp(ZOOM_MIN, ZOOM_MAX);
}
pub fn release(&mut self) {
self.held = false;
}
/// A press or release of the zoom key. Only a press while `playing` (no
/// screen or text field open) zooms; anywhere else the key belongs to
/// the screen, and the zoom lets go.
pub fn key(&mut self, pressed: bool, repeat: bool, playing: bool, level: u8) {
if !pressed || !playing {
self.release();
} else if !repeat {
self.press(level);
}
}
pub fn held(&self) -> bool {
self.held
}
/// Wheel steps while held (positive zooms in); false when not zooming.
pub fn scroll(&mut self, steps: f32) -> bool {
if !self.held {
return false;
}
self.factor = (self.factor * ZOOM_STEP.powf(steps)).clamp(ZOOM_MIN, ZOOM_MAX);
true
}
/// The zoom in effect: 1 when the key is up or the spyglass is in use
/// (scoping keeps vanilla's spyglass view).
pub fn factor(&self, scoping: bool) -> f32 {
if self.held && !scoping {
self.factor
} else {
1.0
}
}
}
/// Vanilla key mappings bound to the zoom key. The key still reaches them
/// (a key bound twice triggers both, as vanilla's do), so the Extras page
/// says so.
pub fn zoom_key_conflicts(e: &Extras, keys: &crate::keybinds::KeyBinds) -> Vec<&'static str> {
if e.zoom_key == "key.keyboard.unknown" {
return Vec::new();
}
crate::keybinds::MAPPINGS
.iter()
.map(|m| m.0)
.filter(|name| keys.get(name) == e.zoom_key)
.collect()
}
/// The field-of-view modifier target `Camera.tickFov` eases toward: vanilla's
/// (`getFieldOfViewModifier`) divided by the zoom. A zoom of 1 leaves it as is.
pub fn fov_target(vanilla: f32, zoom: f32) -> f32 {
if zoom == 1.0 { vanilla } else { vanilla / zoom }
}
/// The mouse turning scale while zoomed.
pub fn turn_scale(zoom: f32, lower_sensitivity: bool) -> f64 {
if lower_sensitivity && zoom > 1.0 {
1.0 / f64::from(zoom)
} else {
1.0
}
}
/// Frame times over the last few seconds: frames per second, the minimum
/// and the 1% low, recomputed twice a second.
pub struct FpsCounter {
/// (end time in seconds, frame milliseconds), oldest first.
frames: VecDeque<(f64, f32)>,
shown: FpsReading,
computed_at: f64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FpsReading {
pub fps: u32,
pub min: u32,
pub low: u32,
}
/// Seconds the minimum and 1% low look back.
const LOW_WINDOW: f64 = 5.0;
impl Default for FpsCounter {
fn default() -> Self {
Self {
frames: VecDeque::new(),
shown: FpsReading::default(),
computed_at: f64::NEG_INFINITY,
}
}
}
impl FpsCounter {
/// A frame that ended at `now` (seconds) and took `ms`.
pub fn record(&mut self, now: f64, ms: f32) {
self.frames.push_back((now, ms));
while self
.frames
.front()
.is_some_and(|&(t, _)| now - t > LOW_WINDOW)
{
self.frames.pop_front();
}
if now - self.computed_at >= 0.5 {
self.computed_at = now;
self.shown = self.compute(now);
}
}
fn compute(&self, now: f64) -> FpsReading {
let fps = self.frames.iter().filter(|&&(t, _)| now - t < 1.0).count() as u32;
let mut times: Vec<f32> = self.frames.iter().map(|f| f.1).collect();
if times.is_empty() {
return FpsReading::default();
}
times.sort_by(|a, b| b.total_cmp(a));
let to_fps = |ms: f32| (1000.0 / ms.max(0.001)).round() as u32;
// The 1% low: the frame rate of the 99th percentile frame time.
let low = times[(times.len() - 1) / 100];
FpsReading {
fps,
min: to_fps(times[0]),
low: to_fps(low),
}
}
pub fn reading(&self) -> FpsReading {
self.shown
}
pub fn clear(&mut self) {
*self = Self::default();
}
}
/// Clicks of one button in the last second.
#[derive(Default)]
pub struct Cps {
clicks: VecDeque<f64>,
}
impl Cps {
pub fn click(&mut self, now: f64) {
self.clicks.push_back(now);
self.forget(now);
}
fn forget(&mut self, now: f64) {
while self.clicks.front().is_some_and(|&t| now - t >= 1.0) {
self.clicks.pop_front();
}
}
pub fn per_second(&mut self, now: f64) -> usize {
self.forget(now);
self.clicks.len()
}
}
/// The settings the Extras page shows, one per row.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Item {
Zoom,
ZoomKey,
ZoomLevel,
ZoomSmooth,
ZoomSensitivity,
Fps,
FpsCorner,
FpsLows,
Keystrokes,
KeystrokesCorner,
KeystrokesCps,
Minimap,
MinimapCorner,
MinimapSize,
MinimapShape,
MinimapZoom,
MinimapRotate,
AutoReconnect,
}
/// The Extras page: headers and items.
pub fn rows() -> Vec<Result<Item, &'static str>> {
use Item::*;
vec![
Err("Zoom"),
Ok(Zoom),
Ok(ZoomKey),
Ok(ZoomLevel),
Ok(ZoomSmooth),
Ok(ZoomSensitivity),
Err("Minimap"),
Ok(Minimap),
Ok(MinimapCorner),
Ok(MinimapSize),
Ok(MinimapShape),
Ok(MinimapZoom),
Ok(MinimapRotate),
Err("FPS counter"),
Ok(Fps),
Ok(FpsCorner),
Ok(FpsLows),
Err("Keystrokes"),
Ok(Keystrokes),
Ok(KeystrokesCorner),
Ok(KeystrokesCps),
Err("Multiplayer"),
Ok(AutoReconnect),
]
}
/// "1 block", "2 blocks", "½ block".
fn block_count(n: f32) -> String {
if n < 1.0 {
"½ block".into()
} else if n == 1.0 {
"1 block".into()
} else {
format!("{n} blocks")
}
}
fn next<T: Copy + PartialEq>(all: &[T], current: T, back: bool) -> T {
let i = all.iter().position(|v| *v == current).unwrap_or(0);
let n = all.len();
all[if back { (i + n - 1) % n } else { (i + 1) % n }]
}
impl Item {
pub fn caption(self) -> &'static str {
match self {
Item::Zoom => "Zoom",
Item::ZoomKey => "Zoom key",
Item::ZoomLevel => "Starting zoom",
Item::ZoomSmooth => "Smooth zoom",
Item::ZoomSensitivity => "Lower sensitivity while zoomed",
Item::Fps => "FPS counter",
Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => "Corner",
Item::Minimap => "Minimap",
Item::MinimapSize => "Size",
Item::MinimapShape => "Shape",
Item::MinimapZoom => "Zoom",
Item::MinimapRotate => "Turn with the player",
Item::AutoReconnect => "Auto-reconnect",
Item::FpsLows => "Minimum and 1% low",
Item::Keystrokes => "Keystrokes",
Item::KeystrokesCps => "Clicks per second",
}
}
/// What the row says under its caption.
pub fn description(self) -> &'static str {
match self {
Item::Zoom => "Hold the zoom key to zoom; the wheel changes it while held.",
Item::ZoomKey => "Click, then press a key. Escape unbinds it.",
Item::ZoomLevel => "The zoom the key starts at.",
Item::ZoomSmooth => "Eases in and out like the spyglass.",
Item::ZoomSensitivity => "Turns slower the more you zoom in.",
Item::Fps => "Frames per second in a corner of the screen.",
Item::FpsCorner | Item::KeystrokesCorner | Item::MinimapCorner => {
"Overlays in one corner stack."
}
Item::Minimap => "A map of the loaded terrain around you, in map colours.",
Item::MinimapSize => "How big the map is on screen.",
Item::MinimapShape => "Square or round.",
Item::MinimapZoom => "Blocks per pixel: smaller shows more detail, larger more land.",
Item::MinimapRotate => "Forward is up; off keeps north up.",
Item::AutoReconnect => {
"Rejoins a server after a lost connection or a restart, never after a kick or ban."
}
Item::FpsLows => "The slowest frame and the 1% low of the last 5 seconds.",
Item::Keystrokes => "Movement keys, jump and mouse buttons as you press them.",
Item::KeystrokesCps => "Clicks in the last second under each mouse button.",
}
}
/// The frame-time cost the main switch of an extra shows.
pub fn cost(self) -> Option<crate::graphics_style::Cost> {
use crate::graphics_style::Cost;
match self {
Item::Zoom | Item::Fps | Item::Keystrokes => Some(Cost::None),
Item::Minimap => Some(Cost::Low),
Item::AutoReconnect => Some(Cost::None),
_ => None,
}
}
/// On/off items and their value.
pub fn switch(self, e: &Extras) -> Option<bool> {
Some(match self {
Item::Zoom => e.zoom,
Item::ZoomSmooth => e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity,
Item::Fps => e.fps,
Item::FpsLows => e.fps_lows,
Item::Keystrokes => e.keystrokes,
Item::KeystrokesCps => e.keystrokes_cps,
Item::Minimap => e.minimap,
Item::MinimapRotate => e.minimap_rotate,
Item::AutoReconnect => e.auto_reconnect,
_ => return None,
})
}
/// The value of the other items, as their button shows it.
pub fn value(self, e: &Extras) -> String {
match self {
Item::ZoomKey => crate::keybinds::display_name(&e.zoom_key).plain(),
Item::ZoomLevel => format!("{}x", e.zoom_level),
Item::FpsCorner => e.fps_corner.label().into(),
Item::KeystrokesCorner => e.keystrokes_corner.label().into(),
Item::MinimapCorner => e.minimap_corner.label().into(),
Item::MinimapSize => MINIMAP_SIZES
.iter()
.find(|s| s.0 == e.minimap_size)
.map_or("Medium", |s| s.1)
.into(),
Item::MinimapShape => if e.minimap_round { "Round" } else { "Square" }.into(),
Item::MinimapZoom => format!("{} per pixel", block_count(e.minimap_zoom)),
other => match other.switch(e) {
Some(true) => "On".into(),
_ => "Off".into(),
},
}
}
/// A click (`back` for the right button). The zoom key binds instead.
pub fn cycle(self, e: &mut Extras, back: bool) {
match self {
Item::Zoom => e.zoom = !e.zoom,
Item::ZoomSmooth => e.zoom_smooth = !e.zoom_smooth,
Item::ZoomSensitivity => e.zoom_sensitivity = !e.zoom_sensitivity,
Item::Fps => e.fps = !e.fps,
Item::FpsLows => e.fps_lows = !e.fps_lows,
Item::Keystrokes => e.keystrokes = !e.keystrokes,
Item::KeystrokesCps => e.keystrokes_cps = !e.keystrokes_cps,
Item::ZoomLevel => e.zoom_level = next(&ZOOM_LEVELS, e.zoom_level, back),
Item::FpsCorner => e.fps_corner = next(&Corner::ALL, e.fps_corner, back),
Item::KeystrokesCorner => {
e.keystrokes_corner = next(&Corner::ALL, e.keystrokes_corner, back)
}
Item::Minimap => e.minimap = !e.minimap,
Item::MinimapRotate => e.minimap_rotate = !e.minimap_rotate,
Item::AutoReconnect => e.auto_reconnect = !e.auto_reconnect,
Item::MinimapCorner => e.minimap_corner = next(&Corner::ALL, e.minimap_corner, back),
Item::MinimapSize => {
let sizes: Vec<u8> = MINIMAP_SIZES.iter().map(|s| s.0).collect();
e.minimap_size = next(&sizes, e.minimap_size, back);
}
Item::MinimapShape => e.minimap_round = !e.minimap_round,
Item::MinimapZoom => e.minimap_zoom = next(&MINIMAP_ZOOMS, e.minimap_zoom, back),
Item::ZoomKey => {}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn everything_is_off_by_default_and_round_trips() {
let d = Extras::default();
assert!(!d.zoom && !d.fps && !d.keystrokes && !d.minimap && !d.auto_reconnect);
assert_eq!(Extras::parse(""), d);
assert_eq!(Extras::parse(&d.serialize()), d);
let mut e = d.clone();
e.zoom = true;
e.zoom_key = "key.keyboard.c".into();
e.zoom_level = 6;
e.fps_corner = Corner::BottomRight;
e.keystrokes = true;
e.keystrokes_cps = false;
e.minimap = true;
e.minimap_size = 128;
e.minimap_round = true;
e.minimap_zoom = 0.5;
e.minimap_rotate = true;
e.minimap_corner = Corner::BottomLeft;
e.auto_reconnect = true;
assert_eq!(Extras::parse(&e.serialize()), e);
}
#[test]
fn bad_lines_keep_defaults() {
let e = Extras::parse("zoom:maybe\nzoomLevel:99\nfpsCorner:middle\nzoomKey:z\nnoise");
assert!(!e.zoom);
assert_eq!(e.zoom_level, 10);
assert_eq!(e.fps_corner, Corner::TopLeft);
assert_eq!(e.zoom_key, "key.keyboard.z");
}
#[test]
fn default_zoom_key_is_free_in_vanilla() {
let key = Extras::default().zoom_key;
assert!(crate::keybinds::key_code(&key).is_some());
assert!(
crate::keybinds::MAPPINGS.iter().all(|m| m.1 != key),
"{key} is a vanilla binding"
);
}
#[test]
fn zoom_is_vanilla_unless_held_and_not_scoping() {
let mut z = Zoom::default();
assert_eq!(z.factor(false), 1.0);
assert_eq!(fov_target(1.1, z.factor(false)), 1.1);
assert!(!z.scroll(1.0), "the wheel is the hotbar's when not zooming");
z.press(4);
assert_eq!(z.factor(false), 4.0);
assert_eq!(z.factor(true), 1.0, "the spyglass wins");
assert!((fov_target(1.0, 4.0) - 0.25).abs() < 1e-6);
assert!(z.scroll(1.0));
assert!((z.factor(false) - 5.0).abs() < 1e-5);
for _ in 0..40 {
z.scroll(1.0);
}
assert_eq!(z.factor(false), ZOOM_MAX);
for _ in 0..80 {
z.scroll(-1.0);
}
assert_eq!(z.factor(false), ZOOM_MIN);
z.release();
assert_eq!(z.factor(false), 1.0);
z.press(2);
assert_eq!(z.factor(false), 2.0, "each press starts at the default");
}
#[test]
fn zoom_target_eases_like_the_spyglass() {
// Camera.tickFov halves the distance to the target each tick.
let mut camera = crate::camera::Camera::default();
camera.tick(None, 1.0);
for _ in 0..30 {
camera.tick(None, 1.0);
}
let target = fov_target(1.0, 4.0);
camera.tick(None, target);
let first = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false);
assert!((first - 70.0 * 0.625).abs() < 1e-3, "{first}");
for _ in 0..30 {
camera.tick(None, target);
}
let settled = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false);
assert!((settled - 70.0 / 4.0).abs() < 1e-3, "{settled}");
// Deeper than the 0.1 floor stops there, as vanilla clamps.
for _ in 0..30 {
camera.tick(None, fov_target(1.0, 20.0));
}
let floor = camera.calculate_fov(1.0, 70, 1.0, None, Default::default(), false);
assert!((floor - 7.0).abs() < 1e-3, "{floor}");
}
#[test]
fn the_zoom_key_only_zooms_while_playing() {
let mut z = Zoom::default();
// In chat, a sign, a text field or any screen: no zoom.
z.key(true, false, false, 4);
assert!(!z.held());
z.key(true, false, true, 4);
assert!(z.held());
// A screen opening while held lets go (its key presses are the screen's).
z.key(true, true, false, 4);
assert!(!z.held());
// Key repeats do not restart a zoom the wheel changed.
z.key(true, false, true, 4);
z.scroll(1.0);
z.key(true, true, true, 4);
assert!((z.factor(false) - 5.0).abs() < 1e-5);
z.key(false, false, true, 4);
assert!(!z.held());
}
#[test]
fn zoom_key_conflicts_name_the_vanilla_mappings() {
let mut e = Extras::default();
let mut keys = crate::keybinds::KeyBinds::default();
assert!(zoom_key_conflicts(&e, &keys).is_empty());
e.zoom_key = "key.keyboard.c".into();
assert_eq!(
zoom_key_conflicts(&e, &keys),
[
"key.saveToolbarActivator",
"key.debug.crash",
"key.debug.copyLocation"
]
);
keys.set("key.drop", "key.keyboard.z");
e.zoom_key = "key.keyboard.z".into();
assert_eq!(zoom_key_conflicts(&e, &keys), ["key.drop"]);
e.zoom_key = "key.keyboard.unknown".into();
keys.set("key.smoothCamera", "key.keyboard.unknown");
assert!(zoom_key_conflicts(&e, &keys).is_empty());
}
#[test]
fn sensitivity_scales_with_zoom() {
assert_eq!(turn_scale(1.0, true), 1.0);
assert_eq!(turn_scale(4.0, false), 1.0);
assert_eq!(turn_scale(4.0, true), 0.25);
}
#[test]
fn fps_counter_reports_rate_minimum_and_low() {
let mut c = FpsCounter::default();
let mut t = 0.0;
// Two seconds at 100 fps with one 50 ms hitch.
for i in 0..200 {
let ms = if i == 150 { 50.0 } else { 10.0 };
t += f64::from(ms) / 1000.0;
c.record(t, ms);
}
c.computed_at = f64::NEG_INFINITY;
c.record(t + 0.01, 10.0);
let r = c.reading();
assert!((95..=101).contains(&r.fps), "{r:?}");
assert_eq!(r.min, 20);
assert_eq!(r.low, 100, "one frame in 200 is under the 1% mark");
// Hitches beyond 1% of frames pull the 1% low down.
let mut c = FpsCounter::default();
let mut t = 0.0;
for i in 0..100 {
let ms = if i % 25 == 0 { 40.0 } else { 10.0 };
t += f64::from(ms) / 1000.0;
c.record(t, ms);
}
c.computed_at = f64::NEG_INFINITY;
c.record(t, 10.0);
assert_eq!(c.reading().low, 25);
}
#[test]
fn old_frames_leave_the_window() {
let mut c = FpsCounter::default();
c.record(0.0, 100.0);
for i in 1..=700 {
c.record(f64::from(i) / 100.0, 10.0);
}
assert_eq!(c.reading().min, 100, "the 100 ms frame is 7 s old");
}
#[test]
fn cps_counts_the_last_second() {
let mut cps = Cps::default();
for i in 0..10 {
cps.click(f64::from(i) * 0.1);
}
assert_eq!(cps.per_second(0.95), 10);
assert_eq!(cps.per_second(1.25), 7);
assert_eq!(cps.per_second(3.0), 0);
}
#[test]
fn items_cycle_through_their_values() {
let mut e = Extras::default();
Item::ZoomLevel.cycle(&mut e, false);
assert_eq!(e.zoom_level, 6);
Item::ZoomLevel.cycle(&mut e, true);
Item::ZoomLevel.cycle(&mut e, true);
assert_eq!(e.zoom_level, 3);
Item::FpsCorner.cycle(&mut e, true);
assert_eq!(e.fps_corner, Corner::BottomRight);
Item::Zoom.cycle(&mut e, false);
assert_eq!(Item::Zoom.switch(&e), Some(true));
assert_eq!(Item::ZoomKey.value(&e), "Z");
Item::MinimapZoom.cycle(&mut e, true);
assert_eq!(Item::MinimapZoom.value(&e), "½ block per pixel");
Item::MinimapSize.cycle(&mut e, false);
assert_eq!(Item::MinimapSize.value(&e), "Large");
assert_eq!(
Extras::parse("minimapSize:7\nminimapZoom:3").minimap_zoom,
1.0
);
for item in rows().into_iter().flatten() {
assert!(!item.caption().is_empty() && !item.description().is_empty());
}
}
}
+247
View File
@@ -0,0 +1,247 @@
//! The extras' HUD overlays (FPS counter, keystrokes): small boxes in the
//! vanilla font, in GUI pixels, stacked per corner (`docs/extras.md`).
use crate::{
extras::{Corner, FpsReading},
hud::{HudAtlas, HudBatch, Rect, rgba},
};
/// The gap between an overlay and the screen edge or the next overlay.
const MARGIN: f32 = 2.0;
const BACKGROUND: u32 = 0x7800_0000;
/// Where the next overlay goes in each corner.
pub struct Corners {
width: f32,
height: f32,
/// Distance from the corner's top or bottom edge, per `Corner::ALL`.
used: [f32; 4],
}
impl Corners {
/// `top_right` reserves the status effect icons' rows.
pub fn new(width: f32, height: f32, top_right: f32) -> Self {
Self {
width,
height,
used: [0.0, top_right, 0.0, 0.0],
}
}
/// The top-left position of a `w` x `h` box in `corner`, below (or
/// above) what the corner already holds.
pub fn place(&mut self, corner: Corner, w: f32, h: f32) -> (f32, f32) {
let i = Corner::ALL.iter().position(|c| *c == corner).unwrap_or(0);
let edge = self.used[i] + MARGIN;
self.used[i] = edge + h;
let x = if corner.left() {
MARGIN
} else {
self.width - MARGIN - w
};
let y = if corner.top() {
edge
} else {
self.height - edge - h
};
(x, y)
}
}
/// How the minimap shows: its corner and side in GUI pixels, its image (an
/// atlas rect), the player arrow (the map item's decoration sprite) turned
/// `arrow` degrees clockwise from up, and the rim's N toward `north` when the
/// map turns.
pub struct MinimapLook {
pub corner: Corner,
pub size: f32,
pub image: Rect,
pub arrow: f32,
pub north: Option<(f32, f32)>,
}
pub fn draw_minimap(
batch: &mut HudBatch,
atlas: &HudAtlas,
corners: &mut Corners,
look: &MinimapLook,
) {
let MinimapLook {
corner,
size,
image,
arrow,
north,
} = *look;
let (x, y) = corners.place(corner, size, size);
batch.rect_uv(x, y, size, size, image, u32::MAX);
let (cx, cy) = (x + size / 2.0, y + size / 2.0);
if let Some(r) = atlas.sprites.get("map/decorations/player").copied() {
// MapRenderer's decorations draw the sprite flipped: its arrow
// points down the texture, so up on screen is half a turn.
let (s, c) = (arrow + 180.0).to_radians().sin_cos();
let p = |dx: f32, dy: f32| [cx + dx * c - dy * s, cy + dx * s + dy * c];
let h = 4.0;
batch.quad(
[p(-h, h), p(h, h), p(h, -h), p(-h, -h)],
[[r.u0, r.v0], [r.u1, r.v0], [r.u1, r.v1], [r.u0, r.v1]],
u32::MAX,
);
}
if let Some((nx, ny)) = north {
let reach = size / 2.0 - 6.0;
let tw = HudBatch::text_width(atlas, "N");
let (tx, ty) = (cx + nx * reach - tw / 2.0, cy + ny * reach - 4.0);
batch.text(
atlas,
"N",
tx.round(),
ty.round(),
rgba(255, 255, 255, 255),
true,
);
}
}
/// The FPS counter's text.
pub fn fps_text(r: FpsReading, lows: bool) -> String {
if lows {
format!("{} fps min {} 1% {}", r.fps, r.min, r.low)
} else {
format!("{} fps", r.fps)
}
}
pub fn draw_fps(
batch: &mut HudBatch,
atlas: &HudAtlas,
corners: &mut Corners,
corner: Corner,
reading: FpsReading,
lows: bool,
) {
let text = fps_text(reading, lows);
let w = HudBatch::text_width(atlas, &text) + 4.0;
let (x, y) = corners.place(corner, w, 12.0);
batch.fill(atlas, x, y, w, 12.0, BACKGROUND);
batch.text(
atlas,
&text,
x + 2.0,
y + 2.0,
rgba(255, 255, 255, 255),
true,
);
}
/// What the keystroke overlay shows.
pub struct Keystrokes {
/// Forward, left, back, right: held, and the bound key's name.
pub moves: [(bool, String); 4],
pub jump: bool,
pub attack: bool,
pub use_: bool,
/// Clicks per second of the left and right buttons, when shown.
pub cps: Option<(usize, usize)>,
}
const KEY: f32 = 22.0;
const GAP: f32 = 2.0;
/// The overlay's size.
pub fn keystrokes_size() -> (f32, f32) {
(3.0 * KEY + 2.0 * GAP, 3.0 * KEY + 3.0 * GAP + 10.0)
}
fn key_box(batch: &mut HudBatch, atlas: &HudAtlas, rect: [f32; 4], held: bool, lines: &[&str]) {
let [x, y, w, h] = rect;
let (fill, ink) = if held {
(rgba(255, 255, 255, 176), rgba(20, 20, 20, 255))
} else {
(BACKGROUND, rgba(255, 255, 255, 255))
};
batch.fill(atlas, x, y, w, h, fill);
let total = lines.len() as f32 * 9.0 - 1.0;
for (i, line) in lines.iter().enumerate() {
let tw = HudBatch::text_width(atlas, line);
let tx = (x + (w - tw) / 2.0).round();
let ty = (y + (h - total) / 2.0).round() + i as f32 * 9.0;
batch.text(atlas, line, tx, ty, ink, !held);
}
}
pub fn draw_keystrokes(
batch: &mut HudBatch,
atlas: &HudAtlas,
corners: &mut Corners,
corner: Corner,
k: &Keystrokes,
) {
let (w, h) = keystrokes_size();
let (x, y) = corners.place(corner, w, h);
let step = KEY + GAP;
let [forward, left, back, right] = &k.moves;
key_box(
batch,
atlas,
[x + step, y, KEY, KEY],
forward.0,
&[&forward.1],
);
for (i, key) in [left, back, right].into_iter().enumerate() {
key_box(
batch,
atlas,
[x + i as f32 * step, y + step, KEY, KEY],
key.0,
&[&key.1],
);
}
let mw = (w - GAP) / 2.0;
let my = y + 2.0 * step;
for (i, (held, label, cps)) in [
(k.attack, "LMB", k.cps.map(|c| c.0)),
(k.use_, "RMB", k.cps.map(|c| c.1)),
]
.into_iter()
.enumerate()
{
let rate = cps.map(|n| format!("{n} CPS"));
let lines: Vec<&str> = std::iter::once(label).chain(rate.as_deref()).collect();
key_box(
batch,
atlas,
[x + i as f32 * (mw + GAP), my, mw, KEY],
held,
&lines,
);
}
// The space bar: a line in a short key.
let sy = my + step;
key_box(batch, atlas, [x, sy, w, 10.0], k.jump, &[]);
let ink = if k.jump {
rgba(20, 20, 20, 255)
} else {
rgba(255, 255, 255, 255)
};
batch.fill(atlas, x + w / 2.0 - 12.0, sy + 4.0, 24.0, 2.0, ink);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn corners_stack_away_from_their_edge() {
let mut c = Corners::new(400.0, 300.0, 26.0);
assert_eq!(c.place(Corner::TopLeft, 50.0, 12.0), (2.0, 2.0));
assert_eq!(c.place(Corner::TopLeft, 70.0, 20.0), (2.0, 16.0));
// Top right starts under the effect icons.
assert_eq!(c.place(Corner::TopRight, 50.0, 12.0), (348.0, 28.0));
assert_eq!(c.place(Corner::BottomRight, 50.0, 12.0), (348.0, 286.0));
assert_eq!(c.place(Corner::BottomRight, 50.0, 10.0), (348.0, 274.0));
assert_eq!(c.place(Corner::BottomLeft, 10.0, 10.0), (2.0, 288.0));
}
#[test]
fn fps_text_with_and_without_lows() {
let r = FpsReading {
fps: 144,
min: 61,
low: 98,
};
assert_eq!(fps_text(r, false), "144 fps");
assert_eq!(fps_text(r, true), "144 fps min 61 1% 98");
}
}
+57
View File
@@ -211,6 +211,9 @@ pub struct FogInputs<'a> {
pub blindness: Option<(i32, bool)>,
/// The darkness effect's blend factor, while the effect is on.
pub darkness: Option<f32>,
/// `BossHealthOverlay.shouldCreateWorldFog`: a boss bar with
/// `createWorldFog` is shown (the Ender Dragon's).
pub boss_world_fog: bool,
}
/// `FogRenderer.setupFog` + `computeFogColor`.
@@ -338,6 +341,12 @@ pub fn setup_fog(tables: &FogTables, state: &FogState, input: &FogInputs) -> Fog
fog.environmental_end = min_end.max(sky.fog_end + -256.0 * state.rain_fog_multiplier);
fog.sky_end = rd.min(512.0);
fog.cloud_end = ((input.cloud_range_chunks * 16) as f32).min(sky.cloud_fog_end);
if input.boss_world_fog {
fog.environmental_start = fog.environmental_start.min(10.0);
fog.environmental_end = fog.environmental_end.min(96.0);
fog.sky_end = fog.environmental_end;
fog.cloud_end = fog.environmental_end;
}
}
}
let span = (rd / 10.0).clamp(4.0, 64.0);
@@ -385,9 +394,57 @@ mod tests {
skybox: true,
blindness: None,
darkness: None,
boss_world_fog: false,
}
}
#[test]
fn boss_world_fog_closes_in() {
// AtmosphericFogEnvironment.setupFog under a createWorldFog boss bar.
let sky = Sky {
fog_end: 1024.0,
cloud_fog_end: 2048.0,
..Sky::default()
};
let tables = FogTables {
water_fog_end: vec![1.0],
};
let mut input = inputs(&sky);
input.boss_world_fog = true;
let fog = setup_fog(&tables, &FogState::default(), &input);
assert_eq!(
(fog.environmental_start, fog.environmental_end),
(0.0, 96.0)
);
assert_eq!((fog.sky_end, fog.cloud_end), (96.0, 96.0));
// Under water the water environment applies instead.
input.fog_type = FogType::Water;
let water = setup_fog(&tables, &FogState::default(), &input);
assert_eq!(water.environmental_start, -8.0);
}
#[test]
fn void_darkness_starts_32_above_the_floor() {
let sky = Sky {
fog_end: 1024.0,
fog_color: [0.5; 3],
sky_color: [0.5; 3],
..Sky::default()
};
let tables = FogTables {
water_fog_end: vec![1.0],
};
let mut input = inputs(&sky);
// The End's floor is y 0: y 16 is halfway into the darkness.
input.min_y = 0;
input.camera_y = 16.0;
let fog = setup_fog(&tables, &FogState::default(), &input);
assert_eq!(fog.color[0], 0.5 * 0.25);
input.camera_y = 32.0;
assert_eq!(
setup_fog(&tables, &FogState::default(), &input).color[0],
0.5
);
}
#[test]
fn render_distance_fog_span() {
let sky = Sky {
fog_end: 1024.0,
+135 -114
View File
@@ -38,6 +38,7 @@ const REFRESH: u64 = id("mp.refresh", 0);
const FIELD_A: u64 = id("mp.field", 0);
const FIELD_B: u64 = id("mp.field", 1);
const DONE: u64 = id("mp.done", 0);
const CANCEL_RETRY: u64 = id("mp.cancel_retry", 0);
/// The launcher's opening (`launcher/src/main.rs`): the wordmark holds over
/// the backdrop, then the interface comes in. A click or a key skips ahead.
@@ -80,7 +81,12 @@ impl Default for Opening {
fn page(mode: &Mode) -> usize {
match mode {
Mode::Main => 0,
Mode::Select { .. } | Mode::Create { .. } => 1,
Mode::Select { .. }
| Mode::Create { .. }
| Mode::Edit { .. }
| Mode::Backup { .. }
| Mode::Delete { .. }
| Mode::Error { .. } => 1,
Mode::Multiplayer(_) => 2,
}
}
@@ -90,17 +96,30 @@ impl Title {
/// Horizon's layout for every title mode. `backdrop` is how much of the
/// live backdrop is visible (0 shows the plain cold background).
pub fn draw_horizon(&self, ui: &mut Ui, backdrop: f32) {
if matches!(
self.mode,
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. }
) {
self.draw(ui.atlas, ui.batch, ui.cursor);
return;
}
let reveal = self.opening_phase(backdrop >= 1.0);
if backdrop < 1.0 {
ui.cold_background(1.0 - backdrop);
}
let shade = t::ease_out_cubic(reveal);
// The world stays in view on the home page; deeper pages veil it more.
let veil = if matches!(self.mode, Mode::Main) {
0.42
horizon_theme::HOME_VEIL
} else {
0.66
horizon_theme::VEIL
};
ui.atmosphere(veil * shade, shade);
ui.muted = if matches!(self.mode, Mode::Main) {
color::MUTED
} else {
color::FAINT
};
ui.atmosphere(veil, shade);
let side = t::ease_out_cubic((reveal - 0.2) / 0.7);
let main = t::ease_out_cubic((reveal - 0.35) / 0.65);
@@ -134,6 +153,7 @@ impl Title {
let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2);
multiplayer_page(ui, x, w, screen, caret);
}
_ => unreachable!("World-management screens use the classic layout"),
}
}
ui.opacity = 1.0;
@@ -142,7 +162,7 @@ impl Title {
// The wordmark rises and fades as the interface comes in.
let word = 1.0 - t::ease_out_cubic(reveal / 0.6);
ui.opacity = word;
let tw = ui.measure(Face::Display, t::WORDMARK, "Horizon");
let tw = ui.measure(Face::Display, t::WORDMARK, "horizon");
let line = (t::WORDMARK * 1.2).round();
ui.text_line(
Face::Display,
@@ -150,8 +170,8 @@ impl Title {
line,
((ui.w - tw) / 2.0).round(),
(ui.h - line) / 2.0 - 28.0 * (1.0 - word),
color::WHITE,
"Horizon",
color::TEXT,
"horizon",
);
ui.opacity = 1.0;
}
@@ -174,19 +194,9 @@ impl Title {
skipped
}
fn sidebar(&self, ui: &mut Ui) {
let h = ui.h;
ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8));
ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER);
ui.text_line(
Face::Display,
22.0,
30.0,
22.0,
16.0,
color::TEXT,
"Horizon",
);
ui.sidebar_list(NAV, 12.0, 66.0, SIDEBAR - 24.0, &PAGES, page(&self.mode));
let (h, muted) = (ui.h, ui.muted);
ui.sidebar_frame("Horizon");
ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &PAGES, page(&self.mode));
let qy = h - 12.0 - 18.0 - 12.0 - CONTROL;
let hover = ui.interact(QUIT, 12.0, qy, SIDEBAR - 24.0, CONTROL, true);
ui.rounded(
@@ -194,51 +204,45 @@ impl Title {
qy,
SIDEBAR - 24.0,
CONTROL,
t::RADIUS,
color::with_alpha(color::HOVER, 0.7 * hover),
t::PILL,
color::with_alpha(color::RAISED, 0.8 * hover),
);
ui.text_line(
Face::Regular,
BODY,
CONTROL,
22.0,
24.0,
qy,
color::mix(color::MUTED, color::TEXT, hover),
color::mix(muted, color::TEXT, hover),
"Quit game",
);
ui.text(
Face::Regular,
SMALL,
22.0,
h - 12.0 - 18.0,
color::FAINT,
"Horizon 26.3",
);
ui.caps(24.0, h - 12.0 - 18.0, muted, "Horizon 26.3");
}
/// Home: the launcher's Play page over the backdrop.
fn home(&self, ui: &mut Ui, x: f32, w: f32) {
ui.wordmark(x, w, ui.h - 64.0, 220.0);
let muted = ui.muted;
let mut y = 36.0 + 28.0;
ui.text(
Face::Medium,
SMALL,
ui.caps(
x,
y,
color::FAINT,
muted,
"Minecraft 26.3 · Java Edition, rewritten in Rust",
);
y += 22.0;
ui.text_line(Face::Display, t::HERO, 58.0, x, y, color::TEXT, "Horizon");
y += 58.0 + 12.0;
y += 24.0;
let line = (t::HERO * 1.1).round();
ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, "Horizon");
y += line + 10.0;
ui.text(
Face::Regular,
t::LARGE,
x,
y,
color::MUTED,
muted,
"The world you know, rebuilt from the ground up.",
);
y += 22.0 + 24.0;
let pw = ui.button_width("Singleplayer", true).max(120.0);
y += 22.0 + 28.0;
let pw = ui.button_width("Singleplayer", true).max(132.0);
ui.button(
PLAY,
[x, y, pw, CONTROL_LARGE],
@@ -254,7 +258,8 @@ impl Title {
Kind::Secondary,
true,
);
y += CONTROL_LARGE + 24.0;
y += CONTROL_LARGE + 32.0;
ui.row_index = 0;
ui.divider(x, y, w);
let worlds = self.recent_worlds();
let last = worlds.first();
@@ -284,14 +289,11 @@ impl Title {
};
y += ui.row(x, y, "Saves", &count, w - t::ROW_LABEL - 16.0);
ui.divider(x, y, w);
let note = "Not affiliated with Mojang or Microsoft";
ui.text(
Face::Regular,
SMALL,
ui.caps(
x,
ui.h - 12.0 - 18.0,
color::FAINT,
note,
muted,
"Not affiliated with Mojang or Microsoft",
);
}
/// A click in Horizon's layout (`x`, `y` in GUI pixels).
@@ -305,6 +307,12 @@ impl Title {
if self.skip_opening() {
return Action::None;
}
if matches!(
self.mode,
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. }
) {
return self.click(x, y, (batch.width, batch.height)).0;
}
let hit = {
let mut ui = Ui::dry(atlas, batch, (x, y));
self.draw_horizon(&mut ui, 1.0);
@@ -390,6 +398,7 @@ impl Title {
MAKE => return self.create_action(),
_ => {}
},
Mode::Edit { .. } | Mode::Backup { .. } | Mode::Delete { .. } | Mode::Error { .. } => {}
Mode::Multiplayer(screen) => {
let id = match hit {
JOIN => Some(40),
@@ -404,6 +413,7 @@ impl Title {
Screen::Direct { .. } => 53,
Screen::Disconnected { .. } => 54,
}),
CANCEL_RETRY => Some(55),
DONE => Some(match screen {
Screen::Direct { .. } => 52,
_ => 50,
@@ -469,8 +479,9 @@ fn actions_right(ui: &mut Ui, right: f32, y: f32, items: &[(u64, &str, Kind, boo
}
rx
}
/// A selectable list row: the launcher's row look with a hover layer and
/// the raised selection with its 1px border. Returns the row height.
/// A selectable list row: its number, the name and a line under it, a mono
/// detail on the right; a soft plate fades in under the pointer and stays
/// under the selection, reaching past the row. Returns the row height.
#[allow(clippy::too_many_arguments)]
fn list_row(
ui: &mut Ui,
@@ -484,50 +495,60 @@ fn list_row(
right: &str,
dot: Option<u32>,
) -> f32 {
let h = 60.0;
let hover = ui.interact(rid, x - 12.0, y + 2.0, w + 24.0, h - 4.0, true);
let h = 64.0;
let hover = ui.interact(rid, x - 16.0, y + 2.0, w + 32.0, h - 4.0, true);
let sel = ui.tween(rid ^ 0x5e1ec7, if selected { 1.0 } else { 0.0 }, t::quick());
ui.rounded(
x - 12.0,
y + 4.0,
w + 24.0,
h - 8.0,
t::RADIUS,
color::with_alpha(color::HOVER, 0.7 * hover),
x - 16.0,
y + 3.0,
w + 32.0,
h - 6.0,
t::RADIUS_PLATE,
color::with_alpha(color::RAISED, (0.7 * hover).max(sel)),
);
ui.rounded(
x - 12.0,
y + 4.0,
w + 24.0,
h - 8.0,
t::RADIUS,
color::with_alpha(color::RAISED, sel),
ui.row_index += 1;
let n = format!("{:02}", ui.row_index);
ui.text(
Face::Mono,
t::MICRO,
x,
y + 15.0,
color::mix(color::FAINT, color::TEXT, sel),
&n,
);
ui.border(
x - 12.0,
y + 4.0,
w + 24.0,
h - 8.0,
t::RADIUS,
color::with_alpha(color::BORDER, sel),
);
let mut tx = x;
let mut tx = x + t::INDEX;
if let Some(dot) = dot {
ui.rounded(x, y + 17.0, 6.0, 6.0, 3.0, dot);
ui.rounded(tx, y + 19.0, 6.0, 6.0, 3.0, dot);
tx += 16.0;
}
let title = ui.fit(Face::Medium, BODY, title, w - 200.0);
ui.text(Face::Medium, BODY, tx, y + 10.0, color::TEXT, &title);
let meta = ui.fit(Face::Regular, SMALL, meta, w - 200.0);
ui.text(Face::Regular, SMALL, tx, y + 31.0, color::MUTED, &meta);
ui.text_right(Face::Regular, SMALL, x + w, y + 21.0, color::FAINT, right);
let title = ui.fit(Face::Medium, t::LARGE + 2.0, title, w - 240.0);
ui.text(
Face::Medium,
t::LARGE + 2.0,
tx,
y + 10.0,
color::TEXT,
&title,
);
let meta = ui.fit(Face::Regular, SMALL, meta, w - 240.0);
ui.text(Face::Regular, SMALL, tx, y + 35.0, color::FAINT, &meta);
let right = right.to_uppercase();
ui.text_right(Face::Mono, t::MICRO, x + w, y + 25.0, color::FAINT, &right);
ui.divider(x, y + h, w);
h
}
/// An empty list: a serif line and a hint.
/// An empty list: a short line in heading type and a hint.
fn empty(ui: &mut Ui, x: f32, y: f32, title: &str, hint: &str) {
ui.text_line(Face::Display, 22.0, 30.0, x, y + 32.0, color::TEXT, title);
ui.text(Face::Regular, BODY, x, y + 66.0, color::MUTED, hint);
ui.text_line(
Face::Display,
t::HEADING,
28.0,
x,
y + 32.0,
color::TEXT,
title,
);
ui.text(Face::Regular, BODY, x, y + 64.0, color::FAINT, hint);
}
fn worlds_page(
@@ -809,7 +830,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
ui.divider(x, y + rh, w);
}
Screen::Disconnected { reason } => {
Screen::Disconnected { reason, retry } => {
let mut y = header(
ui,
x,
@@ -821,8 +842,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
// The launcher's error note: a danger dot beside the message.
let lines = wrap(ui, reason, w - 40.0);
let box_h = 24.0 + lines.len() as f32 * 19.0;
ui.rounded(x, y, w, box_h, t::RADIUS, color::RAISED);
ui.border(x, y, w, box_h, t::RADIUS, color::BORDER);
ui.rounded(x, y, w, box_h, t::RADIUS_PLATE, color::RAISED);
ui.rounded(x + 12.0, y + 18.0, 6.0, 6.0, 3.0, color::DANGER);
for (i, line) in lines.iter().enumerate() {
ui.text_line(
@@ -836,6 +856,12 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
);
}
y += box_h + 16.0;
if let Some(r) = retry {
// Auto-reconnect's countdown, with a way out.
let text = r.text(std::time::Instant::now());
ui.text_line(Face::Regular, BODY, 19.0, x, y, color::MUTED, &text);
y += 19.0 + 12.0;
}
let bw = ui.button_width("Back to servers", false);
ui.button(
BACK,
@@ -844,6 +870,16 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) {
Kind::Secondary,
true,
);
if retry.is_some() {
let cw = ui.button_width("Cancel reconnecting", false);
ui.button(
CANCEL_RETRY,
[x + bw + 8.0, y, cw, CONTROL],
"Cancel reconnecting",
Kind::Ghost,
true,
);
}
}
}
}
@@ -882,44 +918,28 @@ pub mod pause {
let (w, h) = (ui.w, ui.h);
let p = t::ease_out_quint(opened.elapsed().as_secs_f32() / t::move_());
ui.opacity = p;
ui.atmosphere(0.35, 1.0);
ui.atmosphere(horizon_theme::VEIL, 1.0);
ui.offset = (-16.0 * (1.0 - p), 0.0);
ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8));
ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER);
ui.text_line(
Face::Display,
22.0,
30.0,
22.0,
16.0,
color::TEXT,
"Horizon",
);
ui.sidebar_frame("Horizon");
ui.sidebar_list(
id("pause.nav", 0),
12.0,
66.0,
72.0,
SIDEBAR - 24.0,
&["Game", "Advancements", "Statistics", "Options"],
0,
);
ui.text(
Face::Regular,
SMALL,
22.0,
h - 12.0 - 18.0,
color::FAINT,
"Horizon 26.3",
);
ui.caps(24.0, h - 12.0 - 18.0, color::FAINT, "Horizon 26.3");
ui.offset = (0.0, 8.0 * (1.0 - p));
let x = SIDEBAR + 48.0;
let cw = (w - x - 48.0).min(760.0);
let mut y = 36.0;
ui.text(Face::Medium, SMALL, x, y, color::FAINT, "Game paused");
y += 22.0;
let mut y = 36.0 + 28.0;
ui.caps(x, y, color::FAINT, "Game paused");
y += 24.0;
let line = (t::HERO * 1.1).round();
let title = ui.fit(Face::Display, t::HERO, world, cw);
ui.text_line(Face::Display, t::HERO, 58.0, x, y, color::TEXT, &title);
y += 58.0 + 24.0;
ui.text_line(Face::Display, t::HERO, line, x, y, color::TEXT, &title);
y += line + 32.0;
let bw = ui.button_width("Back to game", true).max(120.0);
ui.button(
act(0),
@@ -936,7 +956,8 @@ pub mod pause {
Kind::Secondary,
true,
);
y += CONTROL_LARGE + 24.0;
y += CONTROL_LARGE + 32.0;
ui.row_index = 0;
ui.divider(x, y, cw);
let rh = ui.row(
x,
+278 -169
View File
@@ -34,6 +34,7 @@ mod dragon;
mod enchant_effects;
mod end;
mod explosion;
mod extras;
mod fangs;
mod fireworks;
mod fishing;
@@ -58,6 +59,7 @@ mod level_particles;
mod lightning;
mod llamas;
mod loom;
mod mace;
mod machines;
mod maps;
mod minecarts;
@@ -88,6 +90,7 @@ mod recipe_book;
mod remote;
mod render_control;
mod render_tick;
mod respawn_anchor;
mod scoreboard;
mod screens;
mod sculk;
@@ -127,7 +130,7 @@ use horizon_client::{
containers::{BlockEntity, Providers},
crafting::Recipes,
creative::{Creative, Names},
entities::{Arrow, Experience, ExperienceOrb, ItemEntity},
entities::{Experience, ExperienceOrb, ItemEntity},
environment::Environment,
gfx::{Frame, Renderer},
hud::{HudAtlas, HudBatch, rgba},
@@ -246,12 +249,13 @@ impl Options {
player_name: std::env::var("HORIZON_PLAYER_NAME").unwrap_or_else(|_| "Player".into()),
dedicated: None,
};
let mut session_file = std::env::var("HORIZON_SESSION_FILE").ok();
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--help" | "-h" => {
println!(
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
"Horizon — Minecraft Java Edition 26.3 in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --smoke-report PATH Write a JSON report on exit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default Player)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause."
);
return Ok(None);
}
@@ -295,6 +299,7 @@ impl Options {
"--world" => o.world = Some(value),
"--server" => o.server = Some(value),
"--name" => o.player_name = value,
"--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()),
"--time" => o.time = Some(value.parse()?),
"--weather" => o.weather = Some(value),
@@ -314,6 +319,17 @@ impl Options {
}
}
}
// The launcher's account: online-mode servers need it. A bad file
// only leaves the game offline.
if let Some(path) = session_file.filter(|p| !p.is_empty()) {
match horizon_client::auth::AuthSession::load(path.as_ref()) {
Ok(session) => {
o.player_name = session.name.clone();
horizon_client::auth::set_current(session);
}
Err(e) => eprintln!("Horizon: not signed in: {e}"),
}
}
Ok(Some(o))
}
}
@@ -542,6 +558,8 @@ impl LevelAccess for GameLevel<'_> {
#[derive(Clone, Debug)]
struct FallingBlock {
state: BlockStateId,
/// `DATA_START_POS`: spawn position used to select weighted block models.
start_pos: BlockPos,
position: Vec3,
previous: Vec3,
velocity: Vec3,
@@ -716,7 +734,6 @@ struct Game<'a> {
/// A new player's spawn search, while its candidates' chunks load.
player_spawn: Option<horizon_client::world_spawn::PlayerSpawnFinder>,
mobs: Vec<Mob>,
arrows: Vec<Arrow>,
creatures: creatures::Creatures,
sculk: sculk::SculkState,
raiding: raids::Raiding,
@@ -791,6 +808,11 @@ struct Game<'a> {
portals: nether_portal::Portals,
/// The pending travel goes through an End portal (EndPortalBlock destinations).
end_travel: bool,
/// The respawn point when it is not the world spawn or a bed: a respawn
/// anchor (`game/respawn_anchor.rs`).
respawn_config: Option<respawn_anchor::RespawnConfig>,
/// A respawn travelling to its anchor's dimension and chunks.
respawn_travel: Option<respawn_anchor::RespawnConfig>,
/// The next enter_dimension call comes from an End portal.
end_portal_travel: bool,
end: end::EndState,
@@ -812,6 +834,8 @@ struct Game<'a> {
armor_stand_assets: armor_stands::ArmorStandAssets,
boats: Vec<boats::Boat>,
boat_models: boats::BoatModels,
/// EndCrystalModel's baked layer.
crystal_model: Option<horizon_client::mobs::Part>,
carts: Vec<minecarts::Minecart>,
/// Songs playing from jukeboxes (tracked sound handles).
jukebox_sounds: HashMap<(i32, i32, i32), u64>,
@@ -863,6 +887,8 @@ struct Game<'a> {
pending_bench: Option<(Instant, std::sync::mpsc::Sender<String>)>,
/// Recent frame times for the performance overlay.
frame_graph: horizon_client::perf_overlay::FrameGraph,
/// Horizon's extras (zoom, FPS counter, keystrokes): `game/extras.rs`.
extras: extras::ExtrasState,
/// Meshed sections waiting for an upload budget (Horizon settings).
pending_uploads: Vec<((i32, i32, i32), horizon_client::mesher::SectionMesh)>,
/// This frame's view frustum, for culling entities and block entities.
@@ -1634,6 +1660,16 @@ impl Game<'_> {
LevelEvent::LevelEvent { id: 2004, pos, .. } => {
self.spawner_burst([pos.x, pos.y, pos.z])
}
LevelEvent::LevelEvent {
id: 2015,
pos,
data,
} => self.dragon_egg_particles([pos.x, pos.y, pos.z], data),
LevelEvent::LevelEvent {
id: 2013,
pos,
data,
} => self.smash_dust(pos, data),
LevelEvent::LevelEvent {
id: id @ 3002..=3005,
pos,
@@ -1693,6 +1729,7 @@ impl Game<'_> {
);
self.falling.push(FallingBlock {
state,
start_pos: pos,
position: p,
previous: p,
velocity: Vec3::ZERO,
@@ -1705,6 +1742,9 @@ impl Game<'_> {
}
LevelEvent::Player { pos, effect, .. } => match effect {
PlayerEffect::OpenMenu => self.open_menu([pos.x, pos.y, pos.z]),
PlayerEffect::Sleep if self.beds_destroy_on_use() => {
self.destroy_bed_on_use([pos.x, pos.y, pos.z])?
}
PlayerEffect::Sleep => self.try_sleep([pos.x, pos.y, pos.z]),
PlayerEffect::GiveItem(item) => {
if let Some(rest) = self.give(ItemStack {
@@ -1725,7 +1765,10 @@ impl Game<'_> {
food.saturation = (food.saturation + 0.4).min(food.food as f32);
}
}
PlayerEffect::InteractLoot(_) | PlayerEffect::RespawnAnchor => {}
PlayerEffect::RespawnAnchor => {
self.respawn_anchor_used([pos.x, pos.y, pos.z])?
}
PlayerEffect::InteractLoot(_) => {}
},
LevelEvent::PrimeTnt { pos, rot } => self.add_primed_tnt(pos, rot, 80),
LevelEvent::BlockEvent {
@@ -2119,6 +2162,7 @@ impl Game<'_> {
return Ok(());
}
let sneaking = self.keys.contains(&KeyCode::ShiftLeft);
let mut anchor_passed = None;
// MultiPlayerGameMode.useItemOn: blocks react first unless sneaking with an item.
if !(sneaking && self.held().is_some())
&& let Some(hit) = self.pick()
@@ -2136,6 +2180,15 @@ impl Game<'_> {
self.swing_arm();
return Ok(());
}
match self.use_respawn_anchor(hit.pos, held.as_ref())? {
respawn_anchor::AnchorUse::Charged => {
self.swing_arm();
return Ok(());
}
// The main hand passes; its item is used, then the off hand's glowstone.
respawn_anchor::AnchorUse::Pass => anchor_passed = Some(hit.pos),
respawn_anchor::AnchorUse::Other => {}
}
let face = match hit.face {
[0, 1, 0] => Direction::Up,
[0, -1, 0] => Direction::Down,
@@ -2157,17 +2210,21 @@ impl Game<'_> {
};
let at = Vec3::new(hit.point[0], hit.point[1], hit.point[2]);
let item = held.as_ref().map(|s| s.item.to_string());
let result = self.with_level(|b, level, ticks| {
b.use_item_on(
level,
ticks,
BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
at,
player,
item.as_deref(),
)
});
let result = if anchor_passed.is_some() {
horizon_world::level::InteractionResult::Pass
} else {
self.with_level(|b, level, ticks| {
b.use_item_on(
level,
ticks,
BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
face,
at,
player,
item.as_deref(),
)
})
};
self.process_level_events()?;
if result.consumes_action() {
self.swing_arm();
@@ -2175,6 +2232,12 @@ impl Game<'_> {
}
}
let Some(stack) = self.held().cloned() else {
// Minecraft.startUseItem goes on to the off hand.
if let Some(pos) = anchor_passed
&& self.charge_anchor_from_offhand(pos)?
{
return Ok(());
}
self.use_offhand();
return Ok(());
};
@@ -2239,6 +2302,11 @@ impl Game<'_> {
return Ok(());
};
if info.block.is_none() {
if let Some(pos) = anchor_passed
&& self.charge_anchor_from_offhand(pos)?
{
return Ok(());
}
self.use_offhand();
return Ok(());
}
@@ -2585,7 +2653,10 @@ impl Game<'_> {
self.streaming.center = (cx, cz);
if (-2..=2).all(|dz| (-2..=2).all(|dx| self.streaming.is_lit(cx + dx, cz + dz))) {
let (player, target) = self.travelling.take().ok_or("travel")?;
if self.end_travel {
if let Some(config) = self.respawn_travel.take() {
drop(player);
self.place_respawned(config)?;
} else if self.end_travel {
self.place_after_end_travel(player, target)?;
} else {
self.place_after_travel(player, target)?;
@@ -2790,6 +2861,8 @@ impl Game<'_> {
.iter()
.flatten()
.any(|s| immune.is_some_and(|t| t.contains(&*s.item)));
// The dimension's FAST_LAVA: the Nether's lava pushes harder.
player.fluids.fast_lava = self.dim == Dim::Nether;
let grounded = player.ground.on_ground;
let before = (
grounded,
@@ -2876,6 +2949,40 @@ impl Game<'_> {
MotionEvent::Snowflake { position, velocity } => self.snowflake(position, velocity),
MotionEvent::EnterBlock { state } => self.trigger_enter_block(state),
MotionEvent::InsidePortal { pos } => self.player_inside_nether_portal(pos),
MotionEvent::SmashLanding {
state,
position,
fall_distance,
} => self.smash_landing_particles(state, position, fall_distance),
MotionEvent::Splash {
high_speed,
volume,
pitch,
} => {
let name = if high_speed {
"minecraft:entity.player.splash.high_speed"
} else {
"minecraft:entity.player.splash"
};
self.audio.play(name, Some(feet), volume, pitch);
}
MotionEvent::SplashParticle {
bubble,
position,
velocity,
} => {
use horizon_client::particles::{ParticleOptions, ParticleType};
let kind = if bubble {
ParticleType::Bubble
} else {
ParticleType::Splash
};
self.particles.add(
&ParticleOptions::simple(kind),
[position.x, position.y, position.z],
[velocity.x, velocity.y, velocity.z],
);
}
_ => {}
}
}
@@ -2965,6 +3072,7 @@ impl Game<'_> {
if running {
horizon_client::spans::time("entity_portals", || self.handle_entity_portals());
horizon_client::spans::time("tick_items", || self.tick_items());
horizon_client::spans::time("touch_arrows", || self.touch_arrows());
}
horizon_client::spans::time("spawn_loaded_entities", || self.spawn_loaded_entities());
if running {
@@ -3103,7 +3211,8 @@ impl Game<'_> {
x_rot_o: self.pitch,
y_rot_o: self.yaw,
};
rotation.turn(xo, yo);
let zoom = self.zoom_turn_scale();
rotation.turn(xo * zoom, yo * zoom);
self.yaw = rotation.y_rot;
self.pitch = rotation.x_rot;
}
@@ -3111,6 +3220,7 @@ impl Game<'_> {
/// `Minecraft.pause`: a single-player game with a pausing screen open.
fn pauses_game(&self) -> bool {
self.remote.is_none()
&& self.lan.is_none()
&& self.title.is_none()
&& (matches!(
self.screen,
@@ -3184,6 +3294,9 @@ impl Game<'_> {
self.draw_options(&mut batch);
return batch;
}
if let Some(title) = &mut self.title {
title.poll_backup();
}
if let Some(title) = &self.title {
if horizon_client::ui_theme::horizon() {
let fade = self.backdrop_fade();
@@ -3223,11 +3336,15 @@ impl Game<'_> {
self.draw_spyglass(&mut batch);
// Hud.extractCrosshair / extractItemHotbar / extractPlayerHealth /
// extractVehicleHealth and the experience bar, laid out by hud_layout.
// Horizon has no attack cooldown yet: the strength is always full.
let indicator = self.settings.attack_indicator;
let delay = horizon_client::attack_strength::delay(self.main_hand_attack_speed());
let strength = self.hand_strength.scale(0.0, self.main_hand_attack_speed());
if self.camera_type.first_person() && !spectator {
let attack = (indicator == 1).then_some(1.0);
let draws = hud_layout::crosshair(wi, hi, attack, false);
let attack = (indicator == 1).then_some(strength);
let full = attack.is_some_and(|a| {
hud_layout::full_attack_indicator(a, delay, self.crosshair_living())
});
let draws = hud_layout::crosshair(wi, hi, attack, full);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
}
if !spectator {
@@ -3237,7 +3354,7 @@ impl Game<'_> {
offhand: self.offhand.is_some(),
slots: std::array::from_fn(|i| self.inventory[i].as_ref().map(|_| 0.0)),
offhand_pop: 0.0,
attack: (indicator == 2).then_some(1.0),
attack: (indicator == 2).then_some(strength),
};
let draws = hud_layout::hotbar(wi, hi, &inputs);
hud_layout::paint(&mut batch, &self.res.atlas, &draws);
@@ -3257,6 +3374,7 @@ impl Game<'_> {
self.draw_effect_icons(&mut batch);
// Hud: the action bar and titles draw over the hotbar (nextStratum).
self.draw_boss_bars(&mut batch);
self.draw_extras(&mut batch);
}
// Hud.extractSleepOverlay, under the sidebar, titles and chat.
if let Some((_, ticks)) = self.sleeping {
@@ -4686,56 +4804,6 @@ impl Game<'_> {
self.guest_model_geometry(camera, alpha, &mut out);
self.fangs_geometry(camera, alpha, &mut out);
self.name_tag_geometry(camera, alpha, &mut out);
// Arrows: two crossed quads along the flight direction.
if let Some(r) = self
.res
.atlas
.sprites
.get("entity/projectiles/arrow")
.copied()
{
for a in &self.arrows {
let p = glam::DVec3::new(
a.previous.x + (a.position.x - a.previous.x) * alpha,
a.previous.y + (a.position.y - a.previous.y) * alpha,
a.previous.z + (a.position.z - a.previous.z) * alpha,
) - camera;
let dir = glam::Vec3::new(
a.velocity.x as f32,
a.velocity.y as f32,
a.velocity.z as f32,
)
.normalize_or(glam::Vec3::X);
let side = dir.cross(glam::Vec3::Y).normalize_or(glam::Vec3::Z) * 0.08;
let up = dir.cross(side).normalize_or(glam::Vec3::Y) * 0.08;
let c = p.as_vec3();
let (u1, v1) = (
r.u0 + (r.u1 - r.u0) * 0.5,
r.v0 + (r.v1 - r.v0) * (5.0 / 32.0),
);
for off in [side, up] {
let q = [
c - dir * 0.25 - off,
c + dir * 0.25 - off,
c + dir * 0.25 + off,
c - dir * 0.25 + off,
];
for (v, uv) in q
.iter()
.zip([[r.u0, v1], [u1, v1], [u1, r.v0], [r.u0, r.v0]])
{
out.push(Vertex {
normal: [0; 4],
pos: v.to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: 240 | 240 << 8,
});
}
}
}
}
// Entity shadows (EntityRenderer.extractShadow).
if let Some(sprite) = self.res.atlas.sprites.get("misc/shadow").copied() {
let ambient = if self.dim == Dim::Nether { 0.1 } else { 0.0 };
@@ -4897,12 +4965,9 @@ impl Game<'_> {
}
}
}
// Falling blocks: a unit cube with the block's texture.
for f in self.falling.clone() {
let Some((sprite, tint)) = self.particle_sprite(f.state) else {
continue;
};
let Some(r) = self.res.atlas.sprites.get(&sprite).copied() else {
// Falling blocks use their baked model, including non-cubic shapes.
for f in &self.falling {
let Some((_, tint)) = self.particle_sprite(f.state) else {
continue;
};
let p = glam::DVec3::new(
@@ -4917,50 +4982,17 @@ impl Game<'_> {
f.position.z.floor() as i32,
);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
let v = |x: f32, y: f32, z: f32| o + glam::Vec3::new(x, y, z);
let faces = [
(
[v(0., 1., 1.), v(1., 1., 1.), v(1., 1., 0.), v(0., 1., 0.)],
1.0,
),
(
[v(0., 0., 0.), v(1., 0., 0.), v(1., 0., 1.), v(0., 0., 1.)],
0.5,
),
(
[v(1., 0., 0.), v(0., 0., 0.), v(0., 1., 0.), v(1., 1., 0.)],
0.8,
),
(
[v(0., 0., 1.), v(1., 0., 1.), v(1., 1., 1.), v(0., 1., 1.)],
0.8,
),
(
[v(0., 0., 0.), v(0., 0., 1.), v(0., 1., 1.), v(0., 1., 0.)],
0.6,
),
(
[v(1., 0., 1.), v(1., 0., 0.), v(1., 1., 0.), v(1., 1., 1.)],
0.6,
),
];
for (corners, shade) in faces {
let c = |sft: u32| (((tint >> sft) & 255) as f32 * shade) as u32;
let color = 0xFF00_0000 | c(0) << 16 | c(8) << 8 | c(16);
for (p, uv) in
corners
.iter()
.zip([[r.u0, r.v1], [r.u1, r.v1], [r.u1, r.v0], [r.u0, r.v0]])
{
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 0,
color,
light: packed,
});
}
let start = out.len();
self.block_model_vertices(
f.state,
f.start_pos,
glam::Mat4::from_translation(o),
packed,
&mut out,
);
let tint = horizon_client::mobs::render::abgr(tint);
for vertex in &mut out[start..] {
vertex.color = horizon_client::hud_layout::multiply(vertex.color, tint);
}
}
self.tnt_geometry(camera, alpha, &mut out);
@@ -5145,19 +5177,20 @@ impl Game<'_> {
let delay = 20.0 / speed;
let scale = ((self.attack_ticks as f32 + 0.5) / delay).clamp(0.0, 1.0);
let mut amount = damage * (0.2 + scale * scale * 0.8);
let target_kind = self.mobs[index].kind.id.clone();
let target_kind = format!("minecraft:{}", target_kind.trim_start_matches("minecraft:"));
// Item.getAttackDamageBonus (a mace's smash), before the critical hit.
amount += self.smash_damage_bonus(&target_kind);
let player = self.player.as_ref();
// Player.canCriticalAttack: falling, off the ground, not sprinting.
let falling =
player.is_some_and(|p| !p.ground.on_ground && p.velocity.y < 0.0 && !p.sprinting);
player.is_some_and(|p| !p.ground.on_ground && p.fall_distance > 0.0 && !p.sprinting);
let crit = scale > 0.9 && falling;
if crit {
amount *= 1.5;
}
// Enchantment damage (sharpness, smite, bane) scaled by the attack strength.
let target_kind = self.mobs[index].kind.id.clone();
amount += self.enchant_damage_bonus(&format!(
"minecraft:{}",
target_kind.trim_start_matches("minecraft:")
)) * scale;
amount += self.enchant_damage_bonus(&target_kind) * scale;
self.attack_ticks = 0;
if let Some(p) = self.player.as_mut()
&& !self.creative
@@ -5169,21 +5202,23 @@ impl Game<'_> {
self.swing_arm();
// LivingEntity.setLastHurtMob (tamed wolves join in).
self.combat.last_hurt_mob = Some((self.mobs[index].id, self.world.game_time));
let mob = &mut self.mobs[index];
let center = [
mob.position.x,
mob.position.y + mob.kind.height / 2.0,
mob.position.z,
];
let dealt = (amount.min(mob.health.max(0.0)) * 10.0).round() as i32;
if mob.hurt(amount, from, &mut self.world.random) {
self.stats.custom("damage_dealt", dealt);
let old_health = self.mobs[index].health;
let source = match from {
Some(f) => self.attack_source(f),
None => horizon_client::mobs::Damage::of(horizon_client::mobs::DamageKind::Generic),
};
if self.hurt_by_player(index, amount, source) {
let mob = &self.mobs[index];
// Player.damageStatsAndHearts: the damage the hit actually did.
let actual = old_health - mob.health;
// Player.attack: crit emitter and damage indicator hearts.
let (feet, width, height) = (
[mob.position.x, mob.position.y, mob.position.z],
mob.kind.width,
mob.kind.height,
);
self.stats
.custom("damage_dealt", (actual * 10.0).round() as i32);
if crit {
self.particles.tracking_emitter(
horizon_client::particles::ParticleOptions::simple(
@@ -5194,7 +5229,7 @@ impl Game<'_> {
height,
);
}
if amount > 2.0 {
if actual > 2.0 {
let indicator = horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::DamageIndicator,
);
@@ -5203,10 +5238,10 @@ impl Game<'_> {
[feet[0], feet[1] + height * 0.5, feet[2]],
[0.1, 0.0, 0.1],
0.2,
(amount * 0.5) as u32,
(actual * 0.5) as u32,
);
}
self.last_hurt_by_player.insert(mob.id);
self.last_hurt_by_player.insert(self.mobs[index].id);
let sound = if crit {
"minecraft:entity.player.attack.crit"
} else if scale > 0.9 {
@@ -5214,33 +5249,21 @@ impl Game<'_> {
} else {
"minecraft:entity.player.attack.weak"
};
self.audio.play(sound, Some(center), 1.0, 1.0);
// Player.playServerSideSound: at the player.
self.audio.play(sound, from, 1.0, 1.0);
// The hurt or death sound the mob raised (getHurtSound / getDeathSound,
// its voice pitch from its own random).
let queued = std::mem::take(&mut self.mobs[index].outbox);
for event in queued {
if let horizon_client::mobs::MobEvent::Sound(s, _, volume, pitch) = event {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(center), volume, pitch);
}
}
self.post_attack(index);
if let Some(stack) = self.inventory[self.selected].clone()
&& let Some(max) = self
.res
.items
.get(&stack.item)
.filter(|i| i.max_damage > 0)
.map(|i| i.max_damage)
{
let loss = self.durability_loss(&stack, 1);
if let Some(stack) = self.inventory[self.selected].as_mut() {
stack.damage += loss;
if stack.damage >= max {
self.inventory[self.selected] = None;
}
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
}
}
self.weapon_hit(index);
} else {
self.audio
.play("minecraft:entity.player.attack.nodamage", from, 1.0, 1.0);
}
true
}
@@ -5652,6 +5675,17 @@ impl Game<'_> {
self.travelling = None;
self.player = None;
self.spawn = None;
self.respawn_travel = None;
self.respawn_config =
self.level
.respawn_elsewhere
.as_ref()
.map(|(dim, pos, yaw, forced)| respawn_anchor::RespawnConfig {
dim: Dim::from_id(dim),
pos: *pos,
yaw: *yaw,
forced: *forced,
});
self.spawn_search = 0;
self.spawn_origin = None;
self.spawn_spiral = Default::default();
@@ -5659,7 +5693,7 @@ impl Game<'_> {
self.mobs.clear();
self.creatures.reset_trader();
self.portals = Default::default();
self.arrows.clear();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.orbs.clear();
@@ -5810,7 +5844,7 @@ impl Game<'_> {
self.falling.clear();
self.tnts.clear();
self.mobs.clear();
self.arrows.clear();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.orbs.clear();
@@ -5940,6 +5974,7 @@ impl Game<'_> {
if self.remote.is_none() {
self.stats.custom("leave_game", 1);
}
self.lan_close(false);
self.save_game()
}
fn close_world(&mut self) -> Result<()> {
@@ -5953,12 +5988,13 @@ impl Game<'_> {
}
self.stats.custom("leave_game", 1);
self.save_game()?;
self.lan_close(false);
horizon_client::crash::clear_detail("World");
self.streaming.paused = true;
self.world = World::new(self.res.facts.air, 0);
self.player = None;
self.mobs.clear();
self.arrows.clear();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.screen = Screen::Playing;
@@ -6728,6 +6764,25 @@ impl Game<'_> {
p,
Some(horizon_client::mobs::Who::Player),
);
// ProjectileWeaponItem.useAmmo: creative and Infinity draw without
// using the ammo, so the arrow is CREATIVE_ONLY; else setOwner(player)
// lets it be picked up.
let ammo = arrow_slot
.and_then(|i| self.inventory[i].clone())
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(&horizon_client::arrows::drawn_ammo(
&ammo,
self.creative || infinity,
));
a.set_owner(Some(horizon_client::mobs::Who::Player));
}
// Flame: the arrow is spawned burning (EnchantmentHelper.onProjectileSpawned).
if let Some(seconds) = self.bow_projectile_ignite()
&& let Some(a) = arrow.arrow.as_mut()
{
a.ignite_for_seconds(seconds);
}
let (velocity, on_ground) = self
.player
.as_ref()
@@ -6903,6 +6958,7 @@ impl Game<'_> {
&assets.pixels,
assets.sprite_size,
assets.texture_layers,
&assets.sprite_mips,
&assets.animations,
(
&self.res.atlas.pixels,
@@ -6913,6 +6969,10 @@ impl Game<'_> {
))
}
fn apply_settings(&mut self) {
if let Some(r) = &self.renderer {
self.settings
.clamp_gui_scale([r.config.width as i32, r.config.height as i32]);
}
self.streaming.radius = self.settings.render_distance;
self.streaming.biome_blend = self.settings.biome_blend;
self.streaming.smooth_lighting = self.settings.smooth_lighting;
@@ -7100,6 +7160,8 @@ impl Game<'_> {
f64::from(head[1]) + 0.6,
f64::from(head[2]) + 0.5,
));
// The bed replaces a respawn anchor.
self.respawn_config = None;
self.level.spawn = Some([
f64::from(head[0]),
f64::from(head[1]) + 1.0,
@@ -7478,6 +7540,9 @@ impl Game<'_> {
level.weather = self.world.weather;
level.day_time = self.world.day_time;
level.spawn = self.spawn.map(|s| [s.x, s.y, s.z]);
level.respawn_elsewhere = self
.respawn_config
.map(|c| (c.dim.id().to_owned(), c.pos, c.yaw, c.forced));
level.rotation = [self.yaw, self.pitch];
level.xp_level = self.experience.level;
level.xp_progress = self.experience.progress;
@@ -8138,9 +8203,16 @@ impl ApplicationHandler for Game<'_> {
// The Window constructor: created fullscreen when options.txt says so.
let fullscreen = self.settings.fullscreen;
self.fullscreen = horizon_client::window::FullscreenState::new(fullscreen);
let attributes = Window::default_attributes()
.with_title("Horizon")
.with_window_icon(horizon_client::window::icon());
// Wayland names the window by its app id, which the horizon.desktop entry matches.
#[cfg(target_os = "linux")]
let attributes = winit::platform::wayland::WindowAttributesExtWayland::with_name(
attributes, "horizon", "horizon",
);
let window = match event_loop.create_window(
Window::default_attributes()
.with_title("Horizon")
attributes
.with_inner_size(winit::dpi::LogicalSize::new(1280.0, 720.0))
.with_fullscreen(fullscreen.then_some(winit::window::Fullscreen::Borderless(None))),
) {
@@ -8160,6 +8232,7 @@ impl ApplicationHandler for Game<'_> {
}
}
self.window = Some(window);
self.apply_settings();
self.previous = Instant::now();
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
@@ -8286,8 +8359,20 @@ impl ApplicationHandler for Game<'_> {
}) * wheel_sensitivity
};
let d = scaled(raw_y) as f32;
if let Some(title) = &mut self.title
&& !horizon_client::ui_theme::horizon()
{
let size = self
.window
.as_ref()
.map(|w| w.inner_size())
.unwrap_or_default();
let batch = HudBatch::new([size.width, size.height]);
title.scroll_worlds(d, self.cursor, (batch.width, batch.height));
}
if self.screen == Screen::Playing
&& self.player.is_some()
&& !self.extras_scroll(d)
&& let Some((wheel, _)) =
self.mouse
.on_scroll(raw_x, raw_y, discrete, wheel_sensitivity)
@@ -8339,13 +8424,19 @@ impl ApplicationHandler for Game<'_> {
.unwrap_or([1, 1]);
let mut b = HudBatch::new(size);
let atlas = &self.res.atlas;
let action = self.title.as_mut().map_or(Action::None, |t| {
let (action, sound) = self.title.as_mut().map_or((Action::None, false), |t| {
if horizon_client::ui_theme::horizon() {
t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1)
(
t.click_horizon(atlas, &mut b, self.cursor.0, self.cursor.1),
false,
)
} else {
t.click(self.cursor.0, self.cursor.1, (b.width, b.height))
}
});
if sound {
self.audio.play_button_click();
}
match action {
Action::Quit => event_loop.exit(),
Action::Options => self.open_options(true),
@@ -8391,6 +8482,7 @@ impl ApplicationHandler for Game<'_> {
self.capture(true);
return Ok(());
}
self.extras_mouse(button, pressed);
match self.settings.keys.translate_mouse(button) {
Some(Err(b)) => self.play_mouse(b, pressed)?,
Some(Ok(k)) if pressed => {
@@ -8423,11 +8515,17 @@ impl ApplicationHandler for Game<'_> {
Screen::Creative if button == MouseButton::Left => {
self.creative_screen.release();
}
Screen::Paused if pressed && self.pause_menu => self.pause_click()?,
Screen::Paused
if pressed && button == MouseButton::Left && self.pause_menu =>
{
self.pause_click()?
}
Screen::WorldOptions if pressed && button == MouseButton::Left => {
self.world_options_click()
}
Screen::Dead if pressed => self.death_click()?,
Screen::Dead if pressed && button == MouseButton::Left => {
self.death_click()?
}
Screen::Advancements if button == MouseButton::Left => {
let size = self
.renderer
@@ -8529,6 +8627,11 @@ impl ApplicationHandler for Game<'_> {
return Ok(());
}
match event.physical_key {
PhysicalKey::Code(KeyCode::Enter | KeyCode::NumpadEnter) => {
if let Some(t) = self.title.as_mut() {
t.confirm_edit();
}
}
PhysicalKey::Code(KeyCode::Backspace) => self.title_edit(None, true),
PhysicalKey::Code(KeyCode::Tab) => {
if let Some(t) = self.title.as_mut() {
@@ -8548,6 +8651,7 @@ impl ApplicationHandler for Game<'_> {
let PhysicalKey::Code(key) = event.physical_key else {
return Ok(());
};
self.extras_key(key, event.state == ElementState::Pressed, event.repeat);
// key.smoothCamera toggles the cinematic camera.
if self.screen == Screen::Playing
&& event.state == ElementState::Pressed
@@ -8612,6 +8716,8 @@ impl ApplicationHandler for Game<'_> {
self.sprint_report(&report);
}
}
self.extras_frame(elapsed);
self.extras_retry()?;
self.apply_mouse_look();
self.pad_look(elapsed.as_secs_f32());
self.advance_flight();
@@ -9003,7 +9109,6 @@ pub fn run() -> Result<()> {
spawn_spiral: Default::default(),
player_spawn: None,
mobs: Vec::new(),
arrows: Vec::new(),
creatures: Default::default(),
sculk: Default::default(),
raiding: Default::default(),
@@ -9054,6 +9159,8 @@ pub fn run() -> Result<()> {
travelling: None,
portals: Default::default(),
end_travel: false,
respawn_config: None,
respawn_travel: None,
end_portal_travel: false,
end: Default::default(),
block_ticks: Ticks::new(0),
@@ -9072,6 +9179,7 @@ pub fn run() -> Result<()> {
armor_stand_assets: armor_stands::ArmorStandAssets::load(&root),
boats: Vec::new(),
boat_models: boats::BoatModels::load(&root),
crystal_model: horizon_client::mobs::load_model(&root, "minecraft:end_crystal#main"),
carts: Vec::new(),
jukebox_sounds: HashMap::new(),
bolts: Vec::new(),
@@ -9115,6 +9223,7 @@ pub fn run() -> Result<()> {
view_frustum: None,
pending_uploads: Vec::new(),
frame_graph: Default::default(),
extras: Default::default(),
sky_darken_memo: Default::default(),
persist: Default::default(),
remote: None,
+24 -1
View File
@@ -490,6 +490,22 @@ impl Game<'_> {
"focus": match focus { 0 => "name", 1 => "seed", _ => "none" },
"creative": creative,
}),
Mode::Edit {
world,
name,
focused,
} => {
json!({ "mode": "edit-world", "folder": world.folder, "fields": { "name": name }, "focus": if *focused { "name" } else { "none" } })
}
Mode::Backup { world, .. } => {
json!({ "mode": "creating-backup", "folder": world.folder })
}
Mode::Delete { world } => {
json!({ "mode": "delete-world", "folder": world.folder, "name": world.name })
}
Mode::Error { message, .. } => {
json!({ "mode": "world-operation-error", "message": message })
}
Mode::Multiplayer(_) => json!({ "mode": "multiplayer" }),
}
}
@@ -1312,7 +1328,14 @@ impl Game<'_> {
}
}
}
_ => return Err("--field works on the create-world screen".into()),
horizon_client::title::Mode::Edit { focused, .. } if field == "name" => {
*focused = true
}
_ => {
return Err(
"--field works on the create-world or edit-world screen".into()
);
}
}
}
if replace {
+44 -9
View File
@@ -7,7 +7,7 @@ use horizon_client::{
gamerules::GameRules,
hud::{HudBatch, rgba},
screen_draw::Measure,
text::Text,
text::{ClickEvent, Style, Text},
};
use std::collections::BTreeMap;
use winit::{
@@ -78,8 +78,8 @@ pub struct UiState {
pub hide_gui: bool,
/// Death message key set by the cause of death (e.g. /kill).
pub death_cause: Option<String>,
/// File name of an F2 screenshot waiting for its frame.
pub screenshot_message: Option<String>,
/// Path of an F2 screenshot waiting for its frame.
pub screenshot_message: Option<std::path::PathBuf>,
/// The options screens.
pub options: horizon_client::options_ui::OptionsUi,
/// The prepared resources before resource packs are layered on.
@@ -538,14 +538,37 @@ impl Game<'_> {
let height = self.renderer.as_ref().map_or(720.0, |r| {
HudBatch::new([r.config.width, r.config.height]).height
});
let _ = height;
let m = Measure(&self.res.atlas.font);
let c = Commands {
dispatcher: vanilla::game_dispatcher(),
registries: &self.ui.registries,
};
if let Some(screen) = self.ui.chat_screen.as_mut() {
screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64);
if screen.click(&m, &c, cursor.0 as f64, cursor.1 as f64) {
return;
}
} else {
return;
}
match self.ui.chat.click_at(
&self.res.atlas.font,
height as i32,
cursor.0 as f64,
cursor.1 as f64,
) {
Some(ClickEvent::CopyToClipboard(value)) => {
use horizon_client::clipboard::Clipboard;
self.clipboard.set(&value);
}
Some(ClickEvent::OpenFile(path)) => {
super::packs::open_folder(std::path::Path::new(&path));
}
Some(ClickEvent::SuggestCommand(command)) => {
if let Some(screen) = self.ui.chat_screen.as_mut() {
screen.suggest_command(&m, &c, &command);
}
}
None => {}
}
}
/// Chat lines over the HUD (focused while the chat screen is open).
@@ -745,16 +768,28 @@ impl Game<'_> {
let Some(renderer) = self.renderer.as_mut() else {
return;
};
renderer.screenshot = Some(dir.join(&name));
self.ui.screenshot_message = Some(name);
let path = dir.join(name);
renderer.screenshot = Some(path.clone());
self.ui.screenshot_message = Some(path);
}
/// After a frame: report a finished F2 screenshot in chat.
pub(super) fn finish_screenshot(&mut self, result: &std::result::Result<[u32; 2], String>) {
let Some(name) = self.ui.screenshot_message.take() else {
let Some(path) = self.ui.screenshot_message.take() else {
return;
};
let message = match result {
Ok(_) => Text::translate("screenshot.success", &[Text::literal(name).underlined()]),
Ok(_) => {
let name = path.file_name().unwrap_or_default().to_string_lossy();
let link = Text::styled(
name,
Style {
underlined: Some(true),
click: Some(ClickEvent::OpenFile(path.to_string_lossy().into_owned())),
..Style::default()
},
);
Text::translate("screenshot.success", &[link])
}
Err(e) => Text::translate("screenshot.failure", &[Text::literal(e.clone())]),
};
let focused = self.screen == Screen::Chat;
+7 -1
View File
@@ -47,7 +47,7 @@ impl Game<'_> {
return;
};
if let Some((id, value, max)) = title.focused_field() {
Self::append_shortcut(
let changed = Self::append_shortcut(
&mut self.text_selection,
&mut self.clipboard,
id,
@@ -55,6 +55,9 @@ impl Game<'_> {
shortcut,
max,
);
if changed {
title.search_changed();
}
}
}
/// Typing or a backspace in an append-only field of the title screens:
@@ -66,6 +69,9 @@ impl Game<'_> {
let cleared = title
.focused_field()
.is_some_and(|(id, value, _)| self.text_selection.take(id, value));
if cleared {
title.search_changed();
}
if backspace {
if !cleared {
title.backspace();
+27 -56
View File
@@ -109,7 +109,7 @@ impl Game<'_> {
let Some(input) = &e.input else { return };
let cursor = e.cursor.min(input.len());
let suggest = Style {
suggest: Some(format!("/{command}")),
click: Some(text::ClickEvent::SuggestCommand(format!("/{command}"))),
..Style::default()
};
let mut context = Text::empty();
@@ -228,7 +228,8 @@ impl Game<'_> {
.get(i)
.map(|o| [o.position.x, o.position.y, o.position.z]),
Target::Arrow(i) => self
.arrows
.creatures
.projectiles
.get(i)
.map(|a| [a.position.x, a.position.y, a.position.z]),
Target::Stand(id) => self
@@ -392,7 +393,14 @@ impl Game<'_> {
);
candidates.extend(self.dropped.iter().map(|i| Target::Item(i.id)));
candidates.extend((0..self.orbs.len()).map(Target::Orb));
candidates.extend((0..self.arrows.len()).map(Target::Arrow));
candidates.extend(
self.creatures
.projectiles
.iter()
.enumerate()
.filter(|(_, p)| p.arrow.is_some())
.map(|(i, _)| Target::Arrow(i)),
);
candidates.extend(self.armor_stands.iter().map(|a| Target::Stand(a.id)));
candidates.extend(self.item_frames.iter().map(|f| Target::Frame(f.id)));
candidates.extend(self.paintings.iter().map(|p| Target::Painting(p.id)));
@@ -569,14 +577,7 @@ impl Game<'_> {
"difficulty" => self.cmd_difficulty(ctx),
"seed" => {
let seed = self.level.seed.to_string();
let green = Style {
color: Some(text::GREEN),
suggest: None,
..Style::default()
};
let value = Text::literal("[")
.append(Text::styled(seed.clone(), green))
.append("]");
let value = Text::copyable(seed);
self.system_message(Text::translate("commands.seed.success", &[value]));
Ok(self.level.seed as i32)
}
@@ -960,7 +961,7 @@ impl Game<'_> {
}
}
Target::Arrow(i) => {
if let Some(a) = self.arrows.get_mut(i) {
if let Some(a) = self.creatures.projectiles.get_mut(i) {
a.position = v;
a.previous = v;
}
@@ -1294,8 +1295,13 @@ impl Game<'_> {
}
}
Target::Arrow(i) => {
if i < self.arrows.len() {
self.arrows[i].age = u32::MAX / 2;
if let Some(a) = self
.creatures
.projectiles
.get_mut(i)
.and_then(|p| p.arrow.as_mut())
{
a.removed = true;
}
}
Target::Stand(id) => self.armor_stands.retain(|a| a.id != id),
@@ -1325,7 +1331,9 @@ impl Game<'_> {
self.kill_target(t);
}
self.orbs.retain(|o| o.age < u32::MAX / 2);
self.arrows.retain(|a| a.age < u32::MAX / 2);
self.creatures
.projectiles
.retain(|p| !p.arrow.as_ref().is_some_and(|a| a.removed));
let message = if targets.len() == 1 {
Text::translate("commands.kill.success.single", &[names[0].clone()])
} else {
@@ -2010,6 +2018,7 @@ impl Game<'_> {
f64::from(pos[1]),
f64::from(pos[2]) + 0.5,
));
self.respawn_config = None;
let dim = Text::literal(self.dim.id());
let p = pos.map(|v| Text::literal(v.to_string()));
let mut args = vec![
@@ -2341,22 +2350,7 @@ impl Game<'_> {
&[&poi],
)));
};
let coords = Text::translate(
"chat.coordinates",
&[
Text::literal(p[0].to_string()),
Text::literal("~"),
Text::literal(p[2].to_string()),
],
);
let link = Text::literal("[")
.append(coords)
.append("]")
.with_style(&Style {
color: Some(text::GREEN),
suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])),
..Style::default()
});
let link = Text::teleport_link(p[0], None, p[2]);
let (dx, dz) = (p[0] - from[0], p[2] - from[2]);
let distance = ((dx * dx + dz * dz) as f32).sqrt().floor() as i32;
let shown = if poi.starts_with('#') {
@@ -2412,15 +2406,7 @@ impl Game<'_> {
} else {
biome.clone()
};
let coords = Text::tr("chat.coordinates", &[&p[0], &p[1], &p[2]]);
let link = Text::literal("[")
.append(coords)
.append("]")
.with_style(&Style {
color: Some(text::GREEN),
suggest: Some(format!("/tp @s {} {} {}", p[0], p[1], p[2])),
..Style::default()
});
let link = Text::teleport_link(p[0], Some(p[1]), p[2]);
let distance = (d2 as f32).sqrt().floor() as i32;
self.feedback(Text::translate(
"commands.locate.biome.success",
@@ -2448,22 +2434,7 @@ impl Game<'_> {
&[&s],
)));
};
let coords = Text::translate(
"chat.coordinates",
&[
Text::literal(p[0].to_string()),
Text::literal("~"),
Text::literal(p[2].to_string()),
],
);
let link = Text::literal("[")
.append(coords)
.append("]")
.with_style(&Style {
color: Some(text::GREEN),
suggest: Some(format!("/tp @s {} ~ {}", p[0], p[2])),
..Style::default()
});
let link = Text::teleport_link(p[0], None, p[2]);
let (dx, dz) = (f64::from(p[0] - from[0]), f64::from(p[2] - from[2]));
let distance = (dx * dx + dz * dz).sqrt().floor() as i32;
let shown = if s.starts_with('#') {
@@ -109,9 +109,18 @@ impl Game<'_> {
}
Target::Orb(i) => entity_nbt::orb_to_nbt(self.orbs.get(i)?, random_uuid()),
Target::Arrow(i) => {
let a = self.arrows.get(i)?;
let owner = if a.from_player { player_uuid } else { None };
entity_nbt::arrow_to_nbt(a, random_uuid(), owner)
let p = self.creatures.projectiles.get(i)?;
let owner = if p.owner == Some(horizon_client::mobs::Who::Player) {
player_uuid
} else {
None
};
let in_block = p
.arrow
.as_ref()
.and_then(|a| a.last_state)
.map(|s| self.state_to_nbt(s));
entity_nbt::arrow_to_nbt(p, random_uuid(), owner, in_block, None)?
}
})
}
@@ -320,10 +320,10 @@ impl Game<'_> {
let color = self.waypoint_icon(*t).color.unwrap_or(-1) as u32 & 0xFF_FFFF;
let style = Style {
color: Some(color),
suggest: Some(format!(
click: Some(text::ClickEvent::SuggestCommand(format!(
"/execute in {dimension} run tp @s {} {} {}",
pos[0], pos[1], pos[2]
)),
))),
hover: Some(Box::new(Text::translate("chat.coordinates.tooltip", &[]))),
..Style::default()
};
@@ -701,7 +701,7 @@ impl Game<'_> {
let mut t = Text::translate("chat.square_brackets", &[inner]);
if let Some(cmd) = run {
t = t.with_style(&Style {
suggest: None,
click: None,
..Style::default()
});
let _ = cmd;
@@ -328,7 +328,7 @@ impl Game<'_> {
let message = self.expand_selectors(&raw);
let hover = text::Style {
hover: Some(Box::new(Text::translate("chat.type.team.hover", &[]))),
suggest: Some("/teammsg ".into()),
click: Some(text::ClickEvent::SuggestCommand("/teammsg ".into())),
..text::Style::default()
};
let team_name = team.formatted_display_name().with_style(&hover);
@@ -89,6 +89,7 @@ impl Game<'_> {
fn damage_kind(ty: &str) -> DamageKind {
match ty.trim_start_matches("minecraft:") {
"player_attack" => DamageKind::PlayerAttack,
"mace_smash" => DamageKind::MaceSmash,
"mob_attack" | "mob_attack_no_aggro" => DamageKind::MobAttack,
"arrow" => DamageKind::Arrow,
"thrown" | "trident" | "mob_projectile" => DamageKind::Thrown,
+16 -2
View File
@@ -163,6 +163,12 @@ impl Game<'_> {
self.debug_key(key, KeyAction::Release);
}
}
// The zoom extra sees the key as the keyboard hook does.
let action = arg(2)?;
self.extras_key(physical, action != "up", false);
if action == "tap" {
self.extras_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" {
@@ -228,9 +234,17 @@ impl Game<'_> {
.into());
}
match arg(2)? {
"down" => self.play_mouse(button, true)?,
"up" => self.play_mouse(button, false)?,
"down" => {
self.extras_mouse(button, true);
self.play_mouse(button, true)?
}
"up" => {
self.extras_mouse(button, false);
self.play_mouse(button, false)?
}
"click" => {
self.extras_mouse(button, true);
self.extras_mouse(button, false);
self.play_mouse(button, true)?;
self.play_mouse(button, false)?;
}
+250 -9
View File
@@ -99,6 +99,60 @@ impl ProjectileWorld for ProjWorld<'_, '_> {
.full_collision
}
}
/// `FlameFeatureRenderer`: fire quads stacked up a burning entity's box,
/// turned to the camera around Y, at full block light. `at` is the entity's
/// feet relative to the camera.
fn flame_geometry(
atlas: &horizon_client::hud::HudAtlas,
at: glam::Vec3,
width: f32,
height: f32,
camera_yaw: f32,
light: u8,
out: &mut Vec<Vertex>,
) {
let (Some(fire0), Some(fire1)) = (
atlas.sprites.get("block/fire_0").copied(),
atlas.sprites.get("block/fire_1").copied(),
) else {
return;
};
let s = width * 1.4;
let mut h = height / s;
// Mth.rotationAroundAxis(Y, camera.orientation): the camera's turn about Y.
let turn = glam::Mat3::from_rotation_y(std::f32::consts::PI - camera_yaw.to_radians());
let lift = 0.3 - (h as i32) as f32 * 0.02;
let packed = (u32::from(light >> 4) * 16) | ((15 * 16) << 8);
let (mut r, mut yo, mut zo, mut ss) = (0.5f32, 0.0f32, 0.0f32, 0);
while h > 0.0 {
let tex = if ss % 2 == 0 { fire0 } else { fire1 };
let (mut u0, v0, mut u1, v1) = (tex.u0, tex.v0, tex.u1, tex.v1);
if ss / 2 % 2 == 0 {
std::mem::swap(&mut u0, &mut u1);
}
for (x, y, uv) in [
(-r, -yo, [u1, v1]),
(r, -yo, [u0, v1]),
(r, 1.4 - yo, [u0, v0]),
(-r, 1.4 - yo, [u1, v0]),
] {
let p = at + turn * glam::Vec3::new(x, y, zo + lift) * s;
out.push(Vertex {
normal: [0; 4],
pos: p.to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: packed,
});
}
h -= 0.45;
yo -= 0.45;
r *= 0.9;
zo -= 0.03;
ss += 1;
}
}
pub(super) fn seen(m: &Mob, player: Option<[i32; 4]>) -> Seen {
m.seen(player)
}
@@ -324,6 +378,7 @@ impl Game<'_> {
world: &self.world,
registry: self.res.assets.registry,
facts: &self.res.facts,
movement: &self.motion.blocks,
collision: self.collision,
data: &self.res.mob_data,
player: self.player_view(),
@@ -681,6 +736,7 @@ impl Game<'_> {
pub(super) fn handle_mob_events(&mut self, events: Vec<MobEvent>) -> Result<()> {
for e in events {
match e {
MobEvent::RabbitHop { mob, at } => self.lan_entity_event(mob as i32, 1, at),
MobEvent::Sound(name, at, volume, pitch)
| MobEvent::LocalSound(name, at, volume, pitch) => {
self.audio
@@ -1354,10 +1410,68 @@ impl Game<'_> {
let _ = player.hurt(&self.motion.health, self.world.health_rules, id, amount);
}
}
/// `Player.aiStep` touching arrows in its box grown by (1, 0.5, 1):
/// `AbstractArrow.playerTouch`, then `Player.take`'s pickup sound at the
/// arrow (`ClientPacketListener.handleTakeItemEntity`).
pub(super) fn touch_arrows(&mut self) {
use horizon_client::arrows::Touch;
let Some(p) = self.player.as_ref() else {
return;
};
if p.health.dead_or_dying() || self.spectator() {
return;
}
let w = f64::from(p.dimensions.width) / 2.0;
let reach = Aabb::new(
Vec3::new(p.position.x - w, p.position.y, p.position.z - w),
Vec3::new(
p.position.x + w,
p.position.y + f64::from(p.dimensions.height),
p.position.z + w,
),
)
.inflate(Vec3::new(1.0, 0.5, 1.0));
// Player.hasInfiniteMaterials.
let creative = self.creative;
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
projectiles.retain(|shot| {
let Some(a) = shot.arrow.as_ref().filter(|a| !a.removed) else {
return true;
};
let at = shot.position;
let bounds = Aabb::new(
Vec3::new(at.x - 0.25, at.y, at.z - 0.25),
Vec3::new(at.x + 0.25, at.y + 0.5, at.z + 0.25),
);
if !bounds.intersects(reach) {
return true;
}
let taken = match a.player_touch(creative) {
Touch::Ignore => false,
Touch::Take => true,
// Inventory.add: a creative player takes what does not fit.
Touch::Give(stack) => self.give(stack).is_none() || creative,
};
if taken {
let r = &mut self.world.random;
let pitch = (r.next_float() - r.next_float()) * 1.4 + 2.0;
self.audio.play(
"minecraft:entity.item.pickup",
Some([at.x, at.y, at.z]),
0.2,
pitch,
);
}
!taken
});
self.creatures.projectiles = projectiles;
}
fn tick_projectiles(&mut self) -> Result<()> {
let mut projectiles = std::mem::take(&mut self.creatures.projectiles);
let mut hits = Vec::new();
let mut deflections: Vec<[f64; 3]> = Vec::new();
let mut arrow_events = Vec::new();
{
let mut targets: Vec<(Who, Aabb)> = self
.mobs
@@ -1390,9 +1504,33 @@ impl Game<'_> {
self.world.random.next_float()
};
let w = self.mob_world_base(&[]);
// Level.isRainingAt: raining, open to the sky (the biome's
// precipitation is not checked here).
let (raining, world) = (w.raining, w.world);
let rain = move |p: BlockPos| raining && world.light(p.x, p.y, p.z) >> 4 == 15;
let scene = horizon_client::arrows::ArrowScene {
world: w.world,
registry: w.registry,
facts: w.facts,
collision: w.collision,
fluids: &self.motion.fluids,
raining: &rain,
mob_griefing: self.ui.rules.bool("mob_griefing"),
tnt_explodes: self.ui.rules.bool("tnt_explodes"),
};
// Arrows also hit minecarts (VehicleEntity is pickable).
let mut arrow_targets = targets.clone();
arrow_targets.extend(self.carts.iter().map(|c| (Who::Mob(c.id), c.bounds())));
let pw = ProjWorld { w: &w, targets };
projectiles.retain_mut(|p| {
let (keep, hit) = p.tick(&pw);
let (keep, hit) = if p.arrow.is_some() {
horizon_client::arrows::tick(p, &scene, &arrow_targets)
} else {
p.tick(&pw)
};
if let Some(a) = p.arrow.as_mut() {
arrow_events.extend(a.events.drain(..).map(|e| (p.position, e)));
}
let wind = matches!(
p.kind,
ProjectileKind::WindCharge | ProjectileKind::BreezeWindCharge
@@ -1406,6 +1544,9 @@ impl Game<'_> {
&& breezes.contains(&id)
{
super::wind::reverse(p, jitter);
if let Some(a) = p.arrow.as_mut() {
a.removed = false;
}
deflections.push([at.x, at.y, at.z]);
return true;
}
@@ -1431,12 +1572,93 @@ impl Game<'_> {
self.audio
.play("minecraft:entity.breeze.deflect", Some(at), 1.0, 1.0);
}
for (at, event) in arrow_events {
self.arrow_event(at, event);
}
self.creatures.projectiles.append(&mut projectiles);
for (p, hit) in hits {
self.projectile_hit(&p, hit)?;
}
Ok(())
}
/// What an arrow's tick asked for: its particles and sounds.
fn arrow_event(&mut self, at: Vec3, event: horizon_client::arrows::ArrowEvent) {
use horizon_client::arrows::{ArrowEvent, ArrowParticle, ArrowSound, BlockReaction};
use horizon_client::particles::{ParticleOptions, ParticleType};
let kind = |k| match k {
ArrowParticle::Bubble => ParticleType::Bubble,
ArrowParticle::Crit => ParticleType::Crit,
ArrowParticle::Splash => ParticleType::Splash,
};
match event {
ArrowEvent::Particle {
kind: k,
position,
velocity,
} => self.particles.add(
&ParticleOptions::simple(kind(k)),
[position.x, position.y, position.z],
[velocity.x, velocity.y, velocity.z],
),
ArrowEvent::Sound {
sound,
volume,
pitch,
} => {
let name = match sound {
ArrowSound::Splash => "minecraft:entity.generic.splash",
ArrowSound::HitGround => "minecraft:entity.arrow.hit",
ArrowSound::Extinguish => "minecraft:entity.generic.extinguish_fire",
};
self.audio
.play(name, Some([at.x, at.y, at.z]), volume, pitch);
}
ArrowEvent::BubbleColumnParticles { pos } => {
// Entity.sendBubbleColumnParticles: the level random places them.
for _ in 0..2 {
let r = &mut self.world.random;
let splash = [
f64::from(pos.x) + r.next_double(),
f64::from(pos.y + 1),
f64::from(pos.z) + r.next_double(),
];
let bubble = [
f64::from(pos.x) + r.next_double(),
f64::from(pos.y + 1),
f64::from(pos.z) + r.next_double(),
];
self.particles.send_particles(
&ParticleOptions::simple(ParticleType::Splash),
splash,
[0.0; 3],
1.0,
1,
);
self.particles.send_particles(
&ParticleOptions::simple(ParticleType::Bubble),
bubble,
[0.0, 0.01, 0.0],
0.2,
1,
);
}
}
ArrowEvent::Block { pos, reaction } => match reaction {
BlockReaction::PrimeTnt => {
self.spawn_primed_tnt(pos, false);
self.with_level(|b, level, ticks| b.remove_block(level, ticks, pos, false));
let _ = self.process_level_events();
}
BlockReaction::Light(lit) => {
let _ = self.level_set([pos.x, pos.y, pos.z], lit);
}
},
ArrowEvent::SplashEvent => {
self.projectile_event("minecraft:splash", None, [at.x, at.y, at.z]);
}
ArrowEvent::ShootEvent => {}
}
}
fn projectile_hit(&mut self, p: &Projectile, hit: Hit) -> Result<()> {
self.combat.projectile_owner = match p.owner {
Some(Who::Mob(id)) => Some(id),
@@ -1465,6 +1687,25 @@ impl Game<'_> {
self.hit_special(id, amount, p.owner == Some(Who::Player));
return Ok(());
}
if let (
ProjectileKind::Arrow { .. },
Hit::Entity {
who: Who::Mob(id), ..
},
) = (&p.kind, hit)
&& let Some(i) = self.carts.iter().position(|c| c.id == id)
{
// AbstractArrow.onHitEntity on a minecart.
let amount = p.arrow_damage(&mut self.world.random) + p.bonus.damage;
let burning = p.arrow.as_ref().is_some_and(|a| a.on_fire());
let creative = p.owner == Some(Who::Player) && self.creative;
self.arrow_hits_cart(i, amount, p.velocity, burning, creative);
if let Some((sound, volume, pitch)) = arrow_impact_sound(&mut self.world.random, true) {
self.audio
.play(sound, Some([at.x, at.y, at.z]), volume, pitch);
}
return Ok(());
}
let atp = [at.x, at.y, at.z];
// Projectile.onHit: the landing is heard.
self.projectile_event("minecraft:projectile_land", p.owner, atp);
@@ -1492,7 +1733,8 @@ impl Game<'_> {
velocity: [p.velocity.x * k, 0.1, p.velocity.z * k],
}])?;
}
if p.bonus.flame {
// AbstractArrow.onHitEntity: a burning arrow sets its target alight.
if p.arrow.as_ref().is_some_and(|a| a.on_fire()) {
self.handle_mob_events(vec![MobEvent::Ignite {
target: who,
seconds: 5,
@@ -1528,13 +1770,8 @@ impl Game<'_> {
self.audio.play(sound, Some(atp), volume, pitch);
}
}
(ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {
if let Some((sound, volume, pitch)) =
arrow_impact_sound(&mut self.world.random, true)
{
self.audio.play(sound, Some(atp), volume, pitch);
}
}
// AbstractArrow.onHitBlock plays its sound itself (ArrowEvent).
(ProjectileKind::Arrow { .. }, Hit::Block { .. }) => {}
(ProjectileKind::Snowball, hit) => {
if let Hit::Entity {
who: Who::Mob(id), ..
@@ -2498,6 +2735,9 @@ impl Game<'_> {
});
}
}
if a.arrow.as_ref().is_some_and(|s| s.on_fire()) {
flame_geometry(atlas, c, 0.5, 0.5, self.yaw, light, out);
}
continue;
}
// WindChargeRenderer.
@@ -2572,6 +2812,7 @@ fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool) -> &'static
use horizon_client::mobs::DamageKind as K;
match kind {
K::PlayerAttack => "minecraft:player_attack",
K::MaceSmash => "minecraft:mace_smash",
K::MobAttack => "minecraft:mob_attack",
K::Arrow => "minecraft:arrow",
K::Thrown => "minecraft:thrown",
+15 -3
View File
@@ -88,8 +88,12 @@ impl Game<'_> {
} else {
1
};
let slot_ammo = self.arrow_slot();
let ammo = slot_ammo
.and_then(|i| self.inventory[i].clone())
.unwrap_or_else(|| ItemStack::new("minecraft:arrow", 1));
if !self.creative {
let Some(i) = self.arrow_slot() else { return };
let Some(i) = slot_ammo else { return };
if let Some(s) = self.inventory[i].as_mut() {
s.count -= 1;
if s.count == 0 {
@@ -97,8 +101,12 @@ impl Game<'_> {
}
}
}
// useAmmo: the extra multishot arrows and creative's are intangible.
let drawn = (0..shots)
.map(|i| horizon_client::arrows::drawn_ammo(&ammo, self.creative || i > 0))
.collect();
if let Some(bow) = self.inventory[slot].as_mut() {
bow.data_mut().charged = vec![ItemStack::new("minecraft:arrow", 1); shots];
bow.data_mut().charged = drawn;
}
let pitch = 1.0 / (self.world.random.next_float() * 0.5 + 1.0) + 0.2;
self.audio.play(sounds[2], at, 1.0, pitch);
@@ -119,7 +127,7 @@ impl Game<'_> {
let spread = if count > 1 { 10.0 } else { 0.0 };
let view = glam::DVec3::from_array(view_vector(self.yaw, self.pitch));
let up = glam::DVec3::from_array(view_vector(self.yaw, self.pitch - 90.0));
for (index, _) in charged.iter().enumerate() {
for (index, ammo) in charged.iter().enumerate() {
let angle = if count > 1 {
-spread + 2.0 * spread * index as f64 / (count - 1) as f64
} else {
@@ -142,6 +150,10 @@ impl Game<'_> {
Vec3::new(eye[0], eye[1] - 0.1, eye[2]),
Some(Who::Player),
);
if let Some(a) = arrow.arrow.as_mut() {
a.set_item(ammo);
a.set_owner(Some(Who::Player));
}
arrow.shoot(&mut self.world.random, dir.to_array(), 3.15, 1.0);
self.creatures.projectiles.push(arrow);
self.player_projectile_shot();
@@ -59,8 +59,18 @@ pub(super) fn record_events(events: &[horizon_world::level::LevelEvent]) {
}
}
/// Java's `String.format("%.6f")`: the exact value rounded half up (away
/// from zero) where Rust rounds a tie to even.
fn num(v: f64) -> String {
format!("{v:.6}")
let exact = format!("{:.40}", v.abs());
let tie = exact
.split_once('.')
.is_some_and(|(_, f)| f[6..].starts_with('5') && f[7..].bytes().all(|b| b == b'0'));
if tie {
format!("{:.6}", v + 0.5e-6_f64.copysign(v))
} else {
format!("{v:.6}")
}
}
fn floor_pos(p: [f64; 3]) -> String {
format!(
@@ -137,6 +147,8 @@ impl Game<'_> {
// Hopper cooldowns of an earlier case.
self.hoppers.clear();
self.ui.rules = Default::default();
self.dim = super::Dim::Overworld;
self.respawn_config = None;
// The oracle level plays on normal difficulty.
self.ui.difficulty = 2;
// The oracle level has world seed 0 and fresh random sequences.
@@ -162,6 +174,11 @@ impl Game<'_> {
}
}
self.world.game_time = case["time"].as_i64().unwrap_or(0);
match case["dim"].as_str() {
Some("nether") => self.dim = super::Dim::Nether,
Some("end") => self.dim = super::Dim::End,
_ => {}
}
// The oracle level's clock stands at day time 6000.
self.world.day_time = 6000;
if let Some(rules) = case["rules"].as_object() {
@@ -272,6 +289,28 @@ impl Game<'_> {
used = self.fixture_use(origin, op)?;
} else if let Some(op) = case.get("use_item") {
used = self.fixture_use_item(origin, op)?;
} else if let Some(op) = case.get("respawn_at") {
// ServerPlayer.findRespawnAndUseSpawnBlock for a respawn point at the origin.
let config = super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos: [origin.x, origin.y, origin.z],
yaw: 0.0,
forced: op["forced"].as_bool().unwrap_or(false),
};
let found =
self.find_respawn_and_use(config, op["consume"].as_bool().unwrap_or(true))?;
used.push(match found {
Some((p, yaw)) => format!(
"respawn {} {} {} {}",
num(p.x),
num(p.y),
num(p.z),
yaw.to_bits() as i32
),
None => "respawn none".to_owned(),
});
} else if let Some(op) = case.get("attack") {
used = self.fixture_attack(op, &targets)?;
} else if case.get("hopper").is_some() {
// HopperBlockEntity.pushItemsTick, once.
self.hopper_try_move_items((origin.x, origin.y, origin.z));
@@ -447,14 +486,24 @@ impl Game<'_> {
GameMode::Survival
};
self.creative = self.mode == GameMode::Creative;
let distance = op["distance"].as_f64().unwrap_or(3.0);
let mut player = PlayerMotion::new(
self.motion,
horizon_core::geometry::Vec3::new(
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 3.5,
f64::from(pos.z) + 0.5 + distance,
),
)?;
if let Some(r) = op["respawn"].as_array() {
let p = |i: usize| r.get(i).and_then(Value::as_i64).unwrap_or(0) as i32;
self.respawn_config = Some(super::respawn_anchor::RespawnConfig {
dim: self.dim,
pos: [p(0), p(1), p(2)],
yaw: 0.0,
forced: false,
});
}
player.health.food.food = op["food"].as_i64().unwrap_or(20) as i32;
self.player = Some(player);
self.yaw = 0.0;
@@ -488,7 +537,10 @@ impl Game<'_> {
let key = m.component()["translate"]
.as_str()
.map_or_else(|| m.plain(), str::to_owned);
out.push(format!("msg {key}"));
// The oracle player's advancements are not tracked.
if !key.starts_with("chat.type.advancement") {
out.push(format!("msg {key}"));
}
}
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
@@ -504,11 +556,134 @@ impl Game<'_> {
"held {} using {using}",
canon_stack(self.inventory[self.selected].as_ref())
));
out.push(match self.respawn_config {
Some(c) => format!(
"respawn {} {},{},{}",
c.dim.id(),
c.pos[0],
c.pos[1],
c.pos[2]
),
None => "respawn -".to_owned(),
});
self.player = None;
self.using = None;
Ok(out)
}
/// The player's hit on the first target with the case's item, from the
/// attack strength's scaled `base` damage on: the item's damage bonus and
/// source, the hurt with the weapon's armor effects, then `weapon_hit`
/// (the mace's smash, post-attack enchantments, the wear), as
/// `VanillaDispenserOracle.attack` prints them.
fn fixture_attack(&mut self, op: &Value, targets: &[Target]) -> Result<Vec<String>> {
let stack = parse_stack(op["item"].as_str().unwrap_or("-"))?;
self.mode = if op["creative"].as_bool().unwrap_or(false) {
GameMode::Creative
} else {
GameMode::Survival
};
self.creative = self.mode == GameMode::Creative;
let v3 = |v: &Value| {
horizon_core::geometry::Vec3::new(
v[0].as_f64().unwrap_or(0.0),
v[1].as_f64().unwrap_or(0.0),
v[2].as_f64().unwrap_or(0.0),
)
};
let mut player = PlayerMotion::new(self.motion, v3(&op["player"]))?;
player.velocity = v3(&op["motion"]);
player.fall_distance = op["fall"].as_f64().unwrap_or(0.0);
player.fall_flying = op["fall_flying"].as_bool().unwrap_or(false);
player.flying = op["flying"].as_bool().unwrap_or(false);
player.may_fly = self.creative;
if !op["impact"].is_null() {
player.impulse.impact_position = Some(v3(&op["impact"]));
}
let feet = [player.position.x, player.position.y, player.position.z];
self.player = Some(player);
self.inventory[self.selected] = stack.clone();
let used_before = stack
.as_ref()
.map_or(0, |s| self.stats.get("used", &s.item));
let Some(&Target::Mob(id)) = targets.first() else {
return Err("an attack case hits a mob".into());
};
let index = self
.mobs
.iter()
.position(|m| m.id == id)
.ok_or("the target is gone")?;
let kind = self.mobs[index].kind.id.clone();
let base = op["base"].as_f64().unwrap_or(0.0) as f32;
let bonus = self.smash_damage_bonus(&kind);
let source = self.attack_source(feet);
let hurt = self.hurt_by_player(index, base + bonus, source);
// The hurt sound the mob raised, where it stands.
for event in std::mem::take(&mut self.mobs[index].outbox) {
if let horizon_client::mobs::MobEvent::Sound(s, at, volume, pitch) = event {
self.audio
.play(&format!("minecraft:{s}"), Some(at), volume, pitch);
}
}
if hurt {
self.weapon_hit(index);
}
self.process_level_events()?;
let mut out = Vec::new();
if let Some(s) = &stack {
let used = self.stats.get("used", &s.item) - used_before;
if used != 0 {
out.push(format!("stat {} minecraft:used {used}", s.item));
}
}
let source = match source.kind {
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
_ => "minecraft:player_attack",
};
out.push(format!(
"attack bonus={} source={source} hurt={hurt}",
num(f64::from(bonus))
));
for (i, t) in targets.iter().enumerate() {
let (health, v) = match *t {
Target::Mob(id) => match self.mobs.iter().find(|m| m.id == id) {
Some(m) => (num(f64::from(m.health)), m.velocity),
None => continue,
},
Target::Stand(id) => match self.armor_stands.iter().find(|s| s.id == id) {
Some(s) => ("-".to_owned(), s.velocity),
None => continue,
},
};
out.push(format!(
"V {i} {health} {} {} {}",
num(v.x),
num(v.y),
num(v.z)
));
}
if let Some(p) = self.player.take() {
let impact = p.impulse.impact_position.map_or("-".to_owned(), |i| {
format!("{},{},{}", num(i.x), num(i.y), num(i.z))
});
out.push(format!(
"P {} {} {} fall={} impact={impact} grace={} extra={}",
num(p.velocity.x),
num(p.velocity.y),
num(p.velocity.z),
num(p.fall_distance),
p.impulse.reset_grace_time,
p.spawn_extra_particles_on_fall
));
}
out.push(format!(
"held {}",
canon_stack(self.inventory[self.selected].as_ref())
));
Ok(out)
}
/// A stack in a block entity's slot: a container's, a jukebox's record, a
/// lectern's book, or the items of a block entity Horizon keeps as saved.
fn fixture_fill(&mut self, p: (i32, i32, i32), slot: usize, stack: Option<ItemStack>) {
@@ -628,8 +803,10 @@ impl Game<'_> {
self.next_entity += 1;
let id = self.next_entity;
if kind == "minecraft:armor_stand" {
self.armor_stands
.push(horizon_client::entities::ArmorStand::new(id, at, yaw));
let mut stand = horizon_client::entities::ArmorStand::new(id, at, yaw);
stand.marker = e["marker"].as_bool().unwrap_or(false);
stand.on_ground = e["ground"].as_bool().unwrap_or(false);
self.armor_stands.push(stand);
return Ok(Target::Stand(id));
}
let t = self
@@ -678,6 +855,14 @@ impl Game<'_> {
if flag("loot") {
mob.extra.pick_up_loot = true;
}
mob.on_ground = flag("ground");
if let Some(health) = e["health"].as_f64() {
mob.attrs.max_health = health as f32;
mob.health = health as f32;
}
if let Some(resistance) = e["knockback_resistance"].as_f64() {
mob.attrs.knockback_resistance = resistance;
}
if flag("brown") && s == Species::Mooshroom {
mob.extra.variant = 1;
}
+20 -12
View File
@@ -967,18 +967,7 @@ impl Game<'_> {
"minecraft:tipped_arrow" => ProjectileKind::Arrow {
base_damage: 2.0,
critical: false,
effect: stack
.potion()
.and_then(horizon_client::brewing::potion)
.and_then(|def| {
def.effects
.iter()
.find(|(id, _, _)| {
!horizon_client::brewing::effect(id)
.is_some_and(|e| e.instant)
})
.map(|(id, duration, _)| (*id, (duration / 8).max(1)))
}),
effect: tipped_effect(&stack),
},
"minecraft:fire_charge" | "minecraft:wind_charge" => {
// asProjectile aims with the level's random first; the
@@ -1001,6 +990,12 @@ impl Game<'_> {
_ => ProjectileKind::Snowball,
};
let mut shot = Projectile::new(kind, at, None);
// ArrowItem/SpectralArrowItem.asProjectile: dispensed arrows
// may be picked up.
if let Some(a) = shot.arrow.as_mut() {
a.set_item(&one);
a.pickup = horizon_client::arrows::Pickup::Allowed;
}
shot.shoot(&mut own, dir, power, uncertainty);
self.creatures.projectiles.push(shot);
}
@@ -2135,3 +2130,16 @@ impl Game<'_> {
))
}
}
/// A tipped arrow's lasting effect at an eighth of the potion's duration
/// (`Arrow.doPostHurtEffects`).
pub(super) fn tipped_effect(stack: &ItemStack) -> Option<(&'static str, i32)> {
stack
.potion()
.and_then(horizon_client::brewing::potion)
.and_then(|def| {
def.effects
.iter()
.find(|(id, _, _)| !horizon_client::brewing::effect(id).is_some_and(|e| e.instant))
.map(|(id, duration, _)| (*id, (duration / 8).max(1)))
})
}
+8 -5
View File
@@ -1849,7 +1849,7 @@ impl Game<'_> {
/// raids' and the custom bars, in that order.
pub(super) fn draw_boss_bars(&self, batch: &mut HudBatch) {
let mut bars = Vec::new();
if let Some(d) = self.dragon.as_ref().filter(|_| self.dim == Dim::End) {
if let Some(d) = self.dragon.as_ref().filter(|_| self.dragon_bar_shown()) {
bars.push(hud_overlays::BossBar {
name: Text::literal(
self.translate("entity.minecraft.ender_dragon", "Ender Dragon"),
@@ -1870,6 +1870,11 @@ impl Game<'_> {
);
hud_layout::paint(batch, &self.res.atlas, &draws);
}
/// The dragon fight's boss bar shows (`EnderDragonFight.dragonEvent`,
/// with `setCreateWorldFog`).
pub(super) fn dragon_bar_shown(&self) -> bool {
self.dim == Dim::End && self.dragon.is_some()
}
/// `music.dragon` while the boss bar plays music.
pub(super) fn boss_music(&self) -> bool {
self.dim == Dim::End && self.dragon.is_some() || self.wither_near()
@@ -2066,9 +2071,7 @@ impl Game<'_> {
}
// The healing beam to the nearest crystal.
if let Some(c) = d.nearest_crystal.and_then(|i| self.crystals.get(i)) {
let age = c.time as f32 + a;
let hh = (age * 0.2).sin() / 2.0 + 0.5;
let bob = f64::from((hh * hh + hh) * 0.4 - 1.4);
let bob = f64::from(horizon_client::end_crystal::y(c.time as f32 + a));
let to = glam::DVec3::new(c.position.x, c.position.y + bob, c.position.z);
self.crystal_beam(pos, to - pos, self.ticks as f32 + a, camera, out);
}
@@ -2122,7 +2125,7 @@ impl Game<'_> {
}
/// `submitCrystalBeams`: an eight-sided tube from `from` (+2 up) along
/// `delta`, the beam texture scrolling along it.
fn crystal_beam(
pub(super) fn crystal_beam(
&self,
from: glam::DVec3,
delta: glam::DVec3,
@@ -165,6 +165,69 @@ impl Game<'_> {
self.potions.burning.retain(|(m, _)| *m != id);
self.potions.burning.push((id, (ignite * 20.0) as i32));
}
self.post_attack_bursts(&held, &kind);
}
/// `minecraft:post_attack` explode effects on the attacker (wind burst):
/// a burst at the player's feet that only knocks back and triggers
/// blocks (`ExplodeEffect` with `block_interaction: trigger`).
fn post_attack_bursts(&mut self, held: &ItemStack, victim: &str) {
let Some(p) = self.player.as_ref() else {
return;
};
// EntityFlagsPredicate.isFlying: gliding or flying.
let motion = (p.fall_distance, p.fall_flying || p.flying);
let feet = [p.position.x, p.position.y, p.position.z];
let ctx = EffectContext {
this: Some(victim),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
items: Some(&self.res.items),
direct_motion: Some(motion),
..Default::default()
};
let mut bursts = Vec::new();
for (id, level) in held.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:post_attack"]
.as_array()
.into_iter()
.flatten()
{
let e = &effect["effect"];
if effect["enchanted"] != "attacker"
|| effect["affected"] != "attacker"
|| e["type"] != "minecraft:explode"
|| e["block_interaction"] != "trigger"
{
continue;
}
let ok = effect.get("requirements").is_none_or(|r| {
self.res.stations.enchantments.condition(
r,
*level,
&ctx,
&mut self.world.random,
)
});
if !ok {
continue;
}
let radius = horizon_client::enchant::level_value(&e["radius"], *level).max(0.0);
// ExplosionDamageCalculator.getKnockbackMultiplier: 1 unless given.
let knockback = if e["knockback_multiplier"].is_null() {
1.0
} else {
horizon_client::enchant::level_value(&e["knockback_multiplier"], *level)
};
bursts.push((radius, knockback));
}
}
for (radius, knockback) in bursts {
let _ = self.wind_burst(feet, radius, knockback, false, false);
}
}
/// Burning mobs (fire aspect): one damage every 20 ticks, flame particles.
pub(super) fn tick_burning(&mut self) {
@@ -349,6 +412,45 @@ impl Game<'_> {
) == 0.0;
(f64::from(power), infinity)
}
/// `EnchantmentHelper.onProjectileSpawned` ignite effects of the held bow
/// (flame): the seconds the new arrow burns for.
pub(super) fn bow_projectile_ignite(&mut self) -> Option<f32> {
let bow = self.inventory[self.selected].clone()?;
let ctx = EffectContext {
this: Some("minecraft:arrow"),
items: Some(&self.res.items),
..Default::default()
};
let mut ignite: Option<f32> = None;
for (id, level) in bow.enchantments() {
let Some(def) = self.res.stations.enchantments.get(id) else {
continue;
};
for effect in def.effects["minecraft:projectile_spawned"]
.as_array()
.into_iter()
.flatten()
{
if effect["effect"]["type"] != "minecraft:ignite" {
continue;
}
let ok = effect.get("requirements").is_none_or(|r| {
self.res.stations.enchantments.condition(
r,
*level,
&ctx,
&mut self.world.random,
)
});
if ok {
let seconds =
horizon_client::enchant::level_value(&effect["effect"]["duration"], *level);
ignite = Some(ignite.map_or(seconds, |s: f32| s.max(seconds)));
}
}
}
ignite
}
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
pub(super) fn apply_enchantment_attributes(&mut self) {
let mut wanted: Vec<(String, String, f64, String)> = Vec::new();
+46 -107
View File
@@ -494,14 +494,16 @@ impl Game<'_> {
Ok(())
}
/// Dying in the End respawns in the Overworld.
/// Dying away from the Overworld respawns at the world spawn there.
pub(super) fn respawn_out_of_end(&mut self) -> Result<()> {
if self.dim != Dim::End || self.player.is_none() {
if self.dim == Dim::Overworld || self.player.is_none() {
return Ok(());
}
self.end_portal_travel = true;
let result = self.enter_dimension(Dim::Overworld);
self.end_portal_travel = false;
// The arrival places a fresh player at the spawn.
self.end_travel = true;
result
}
@@ -879,130 +881,67 @@ impl Game<'_> {
Ok(())
}
/// The End crystals on the spikes and thrown eyes of ender, as
/// camera-relative entity geometry (End portals and gateways are block
/// entities).
/// End crystals (on the spikes, or placed in any dimension) and thrown
/// eyes of ender, as camera-relative entity geometry (End portals and
/// gateways are block entities).
pub(super) fn end_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
if self.dim == Dim::End {
self.end_crystal_geometry(camera, out);
}
self.end_crystal_geometry(camera, out);
self.eye_geometry(camera, out);
}
/// EndCrystalRenderer and EndCrystalModel for the end crystals.
/// EndCrystalRenderer and EndCrystalModel for the end crystals, and the
/// beam to a crystal's target (the spikes being summoned back).
fn end_crystal_geometry(&self, camera: glam::DVec3, out: &mut Vec<Vertex>) {
let Some(r) = self
.res
.atlas
.sprites
.get("entity/end_crystal/end_crystal")
.copied()
else {
let (Some(model), Some(r)) = (
self.crystal_model.as_ref(),
self.res
.atlas
.sprites
.get("entity/end_crystal/end_crystal")
.copied(),
) else {
return;
};
let sin45 = std::f32::consts::FRAC_PI_4.sin();
let axis = glam::Vec3::new(sin45, 0.0, sin45).normalize();
let tilt = glam::Quat::from_axis_angle(axis, std::f32::consts::FRAC_PI_3);
// A 8×8×8 model box at texture offset (u, v) of the 64×32 texture.
let uv = |u: f32, v: f32, w: f32, h: f32| {
let su = |x: f32| r.u0 + (r.u1 - r.u0) * x / 64.0;
let sv = |y: f32| r.v0 + (r.v1 - r.v0) * y / 32.0;
(su(u), su(u + w), sv(v), sv(v + h))
};
let uv = [r.u0, r.v0, r.u1, r.v1];
let partial = self.clock.fraction() as f32;
for crystal in &self.crystals {
let feet = glam::DVec3::new(crystal.position.x, crystal.position.y, crystal.position.z);
let age = crystal.time as f32 + self.clock.fraction() as f32;
let spin = glam::Quat::from_rotation_y((age * 3.0).to_radians());
let hh = (age * 0.2).sin() / 2.0 + 0.5;
let bob = (hh * hh + hh) * 0.4 - 1.4;
let rel = feet - camera;
if rel.length_squared() > 256.0 * 256.0 {
continue;
}
let age = crystal.time as f32 + partial;
let light = self.world.light(
feet.x.floor() as i32,
feet.y.floor() as i32,
feet.z.floor() as i32,
);
let packed = (u32::from(light >> 4) * 16) | ((u32::from(light & 15) * 16) << 8);
// poseStack.scale(2) then translate(0, -0.5, 0); outer_glass at y 24 px + bob.
let center = rel.as_vec3() + glam::Vec3::new(0.0, 2.0 * (24.0 / 16.0 - 0.5) + bob, 0.0);
let outer = spin * tilt;
let inner = tilt * spin;
let parts = [
(outer, 1.0, 0.0),
(outer * inner, 0.875, 0.0),
(outer * inner * inner, 0.875 * 0.765_625, 32.0),
];
for (rotation, scale, u) in parts {
// Half extent: 4 px, times the renderer's scale of 2.
let h = 0.25 * 2.0 * scale;
let corner = |x: f32, y: f32, z: f32| {
center + rotation * glam::Vec3::new(x * h, y * h, z * h)
};
let faces: [([f32; 3], [f32; 3], [f32; 3], (f32, f32, f32, f32)); 6] = [
(
[-1.0, 1.0, -1.0],
[1.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
uv(u + 8.0, 0.0, 8.0, 8.0),
),
(
[-1.0, -1.0, -1.0],
[1.0, 0.0, 0.0],
[0.0, 0.0, 1.0],
uv(u + 16.0, 0.0, 8.0, 8.0),
),
(
[-1.0, -1.0, -1.0],
[0.0, 0.0, 1.0],
[0.0, 1.0, 0.0],
uv(u, 8.0, 8.0, 8.0),
),
(
[-1.0, -1.0, -1.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
uv(u + 8.0, 8.0, 8.0, 8.0),
),
(
[1.0, -1.0, -1.0],
[0.0, 0.0, 1.0],
[0.0, 1.0, 0.0],
uv(u + 16.0, 8.0, 8.0, 8.0),
),
(
[-1.0, -1.0, 1.0],
[1.0, 0.0, 0.0],
[0.0, 1.0, 0.0],
uv(u + 24.0, 8.0, 8.0, 8.0),
),
];
for (o, a, b, (u0, u1, v0, v1)) in faces {
let p = |s: f32, t: f32| {
corner(
o[0] + 2.0 * (a[0] * s + b[0] * t),
o[1] + 2.0 * (a[1] * s + b[1] * t),
o[2] + 2.0 * (a[2] * s + b[2] * t),
)
};
let quad = [
(p(0.0, 0.0), [u0, v1]),
(p(1.0, 0.0), [u1, v1]),
(p(1.0, 1.0), [u1, v0]),
(p(0.0, 1.0), [u0, v0]),
];
for (pos, uv) in quad {
out.push(Vertex {
normal: [0; 4],
pos: pos.to_array(),
uv,
layer: 0,
color: 0xFFFF_FFFF,
light: packed,
});
}
}
let poses = horizon_client::end_crystal::poses(model, age, crystal.show_bottom);
// poseStack.scale(2) then translate(0, -0.5, 0), not flipped.
let base = glam::Mat4::from_translation(rel.as_vec3())
* glam::Mat4::from_scale(glam::Vec3::splat(2.0))
* glam::Mat4::from_translation(glam::Vec3::new(0.0, -0.5, 0.0));
horizon_client::mobs::render::draw(
model,
base,
&poses,
uv,
0xFFFF_FFFF,
packed,
0,
out,
);
if let Some(target) = crystal.beam {
// The beam from the target's centre up to the bobbing crystal.
let from = glam::DVec3::new(
f64::from(target[0]) + 0.5,
f64::from(target[1]) + 0.5,
f64::from(target[2]) + 0.5,
);
let delta = feet - from
+ glam::DVec3::new(0.0, f64::from(horizon_client::end_crystal::y(age)), 0.0);
self.crystal_beam(from, delta, age, camera, out);
}
}
}
+143 -53
View File
@@ -3,14 +3,64 @@
//! draws), entity damage with exposure and knockback, block interaction with
//! merged drops and TNT chain priming, and optional fire.
use super::Game;
use horizon_client::{Result, blocks::Fluid, items::ItemStack};
use horizon_client::{Result, blocks::Fluid, collisions::SceneCollisions, items::ItemStack};
use horizon_core::{
geometry::Vec3,
geometry::{Vec3, VoxelShape},
position::BlockPos,
random::{LegacyRandom, RandomSource},
};
use horizon_world::java_hash_map::{JavaHashMap, JavaKey};
use std::cmp::Ordering;
use horizon_world::{
collision_context::{CollisionContext, CollisionEntity, CollisionItem},
entity_obstruction::EntityIdentity,
java_hash_map::{JavaHashMap, JavaKey},
registry::BlockStateId,
world_ray::{RayBlockMode, RayFluidMode, RayWorld, clip_world},
};
use std::{cmp::Ordering, io};
/// `Level.clip` with `ClipContext.Block.COLLIDER`, no fluids and the
/// collision context of the entity whose exposure is measured.
struct ColliderRays<'a, 'r> {
scene: SceneCollisions<'a, 'r>,
context: CollisionContext<'static>,
}
impl RayWorld for ColliderRays<'_, '_> {
type Error = io::Error;
type Block = BlockStateId;
type Fluid = ();
fn block_state(&mut self, p: BlockPos) -> io::Result<BlockStateId> {
Ok(self.scene.world.block(p.x, p.y, p.z))
}
fn fluid_state(&mut self, _: BlockPos) -> io::Result<()> {
Ok(())
}
fn block_shape(
&mut self,
state: BlockStateId,
p: BlockPos,
_: RayBlockMode,
) -> io::Result<VoxelShape> {
let binding = self.scene.binding;
binding
.collision_shape_with_context(&mut self.scene, state, p, &self.context)
.map_err(|e| io::Error::other(format!("{e:?}")))
}
fn interaction_shape(&mut self, _: BlockStateId, _: BlockPos) -> io::Result<VoxelShape> {
Ok(VoxelShape::empty())
}
fn fluid_is_source(&mut self, _: ()) -> io::Result<bool> {
Ok(false)
}
fn fluid_is_empty(&mut self, _: ()) -> io::Result<bool> {
Ok(true)
}
fn fluid_is_water(&mut self, _: ()) -> io::Result<bool> {
Ok(false)
}
fn fluid_shape(&mut self, _: (), _: BlockPos) -> io::Result<VoxelShape> {
Ok(VoxelShape::empty())
}
}
/// `BlockPos` with Java `Vec3i.hashCode` / `compareTo`.
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -48,35 +98,6 @@ pub(super) fn client_float() -> f32 {
}
impl Game<'_> {
/// `Level.clip(from, to, COLLIDER, NONE)` missing every block, with full
/// collision cubes as obstacles.
fn clear_line(&self, from: [f64; 3], to: [f64; 3]) -> bool {
let d = [to[0] - from[0], to[1] - from[1], to[2] - from[2]];
let length = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let steps = (length / 0.1).ceil().max(1.0) as i32;
let mut last = [i32::MIN; 3];
for i in 0..=steps {
let t = f64::from(i) / f64::from(steps);
let b = [
(from[0] + d[0] * t).floor() as i32,
(from[1] + d[1] * t).floor() as i32,
(from[2] + d[2] * t).floor() as i32,
];
if b == last {
continue;
}
last = b;
if self
.res
.facts
.get(self.world.block(b[0], b[1], b[2]))
.full_collision
{
return false;
}
}
true
}
/// `ServerExplosion.getSeenPercent` for an entity box.
pub(super) fn seen_percent(&self, center: [f64; 3], min: [f64; 3], max: [f64; 3]) -> f32 {
let xs = 1.0 / ((max[0] - min[0]) * 2.0 + 1.0);
@@ -87,6 +108,23 @@ impl Game<'_> {
if xs < 0.0 || ys < 0.0 || zs < 0.0 {
return 0.0;
}
// ClipContext(..., entity): the entity standing at the box's bottom.
let mut rays = ColliderRays {
scene: SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
},
context: CollisionContext::for_entity(
CollisionEntity {
identity: EntityIdentity(0),
y: min[1],
descending: false,
main_hand: Some(CollisionItem::EMPTY),
},
false,
),
};
let (mut hits, mut count) = (0, 0);
let mut xx = 0.0;
while xx <= 1.0 {
@@ -97,7 +135,18 @@ impl Game<'_> {
let x = min[0] + (max[0] - min[0]) * xx;
let y = min[1] + (max[1] - min[1]) * yy;
let z = min[2] + (max[2] - min[2]) * zz;
if self.clear_line([x + x_offset, y, z + z_offset], center) {
let from = Vec3::new(x + x_offset, y, z + z_offset);
let to = Vec3::new(center[0], center[1], center[2]);
let missed = clip_world(
&mut rays,
from,
to,
RayBlockMode::Collider,
RayFluidMode::None,
4096,
)
.is_ok_and(|r| r.miss);
if missed {
hits += 1;
}
count += 1;
@@ -109,8 +158,14 @@ impl Game<'_> {
}
hits as f32 / count as f32
}
/// `ServerExplosion.calculateExplodedPositions`.
fn exploded_positions(&mut self, center: [f64; 3], radius: f32) -> Vec<[i32; 3]> {
/// `ServerExplosion.calculateExplodedPositions`; `resists` overrides one
/// block's resistance (`ExplosionDamageCalculator.getBlockExplosionResistance`).
fn exploded_positions(
&mut self,
center: [f64; 3],
radius: f32,
resists: Option<([i32; 3], f32)>,
) -> Vec<[i32; 3]> {
let (min_y, max_y) = self.with_level(|_, level, _| {
use horizon_world::level::LevelAccess;
(level.min_y(), level.max_y())
@@ -147,8 +202,14 @@ impl Game<'_> {
} else {
0.0
};
if !self.res.facts.is_air(state) || f.fluid != Fluid::None {
power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3;
match resists {
Some((at, resistance)) if at == pos => {
power -= (resistance + 0.3) * 0.3;
}
_ if !self.res.facts.is_air(state) || f.fluid != Fluid::None => {
power -= (f.explosion_resistance.max(fluid) + 0.3) * 0.3;
}
_ => {}
}
if power > 0.0 {
set.put(Key(pos), ());
@@ -163,8 +224,9 @@ impl Game<'_> {
}
set.entries().map(|(k, _)| k.0).collect()
}
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT).
fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32) {
/// `ServerExplosion.hurtEntities` (player, mobs, items, primed TNT);
/// the player takes `damage_type`.
fn explosion_hurt_entities(&mut self, center: [f64; 3], radius: f32, damage_type: &str) {
if radius < 1.0e-5 {
return;
}
@@ -223,7 +285,7 @@ impl Game<'_> {
let mut hurt = false;
let creative = self.creative;
if let Some(p) = self.player.as_mut()
&& let Some(id) = self.motion.health.damage.id("minecraft:explosion")
&& let Some(id) = self.motion.health.damage.id(damage_type)
{
// Creative players are invulnerable to explosions.
if !creative && player_hurtable {
@@ -334,6 +396,26 @@ impl Game<'_> {
radius: f32,
interaction: BlockInteraction,
fire: bool,
) -> Result<()> {
self.server_explode_as(
center,
radius,
interaction,
fire,
"minecraft:explosion",
None,
)
}
/// `server_explode` with the damage type the player takes and a block
/// whose explosion resistance the damage calculator overrides.
pub(super) fn server_explode_as(
&mut self,
center: [f64; 3],
radius: f32,
interaction: BlockInteraction,
fire: bool,
damage_type: &str,
resists: Option<([i32; 3], f32)>,
) -> Result<()> {
if let Some(p) = &self.player {
let d = [
@@ -344,11 +426,11 @@ impl Game<'_> {
let distance = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
self.pad_rumble(horizon_client::gamepad::Rumble::Explosion { distance, radius });
}
let mut targets = self.exploded_positions(center, radius);
// Explosion.explode: the blast is heard.
let ctx = horizon_client::sculk::Context::default();
self.post_game_event("minecraft:explode", center, ctx);
self.explosion_hurt_entities(center, radius);
let mut targets = self.exploded_positions(center, radius, resists);
self.explosion_hurt_entities(center, radius, damage_type);
if interaction != BlockInteraction::Keep {
// Util.shuffle(list, level.random)
for i in (2..=targets.len()).rev() {
@@ -375,8 +457,12 @@ impl Game<'_> {
.facts
.get(self.world.block(pos[0], pos[1] - 1, pos[2]))
.solid_render
&& let Some(fire) = self.res.assets.registry.default_state("minecraft:fire")
{
// BaseFireBlock.getState: soul fire on its base blocks,
// fire shaped by its neighbours elsewhere.
let at = BlockPos::new(pos[0], pos[1], pos[2]);
let fire =
self.with_level(|b, level, ticks| b.fire_state_for(level, ticks, at));
self.level_set(pos, fire)?;
}
}
@@ -420,32 +506,36 @@ impl Game<'_> {
}
if !is_tnt {
let dynamic = self.pending.dynamic(pos);
let drops = self.res.items.block_drops_full(
// LootContextParams.EXPLOSION_RADIUS under DESTROY_WITH_DECAY: the
// tables' survives_explosion and explosion_decay draw from their
// random sequence.
let decay = (interaction == BlockInteraction::DestroyWithDecay).then_some(radius);
let drops = self.res.items.block_drops_exploded(
self.res.assets.registry,
state,
None,
&dynamic,
&mut self.world.random,
Some((&mut self.rand_sequences, self.level.seed)),
decay,
);
for mut stack in drops {
if &*stack.item == "minecraft:air" || stack.count == 0 {
continue;
}
self.pending.attach(pos, &mut stack);
// survives_explosion / explosion_decay: 1 / radius per stack.
if interaction == BlockInteraction::DestroyWithDecay
&& self.world.random.next_float() > 1.0 / radius
{
continue;
}
add_or_append_stack(stacks, stack, pos);
}
}
self.pending.clear(pos);
self.level_set(pos, self.world.air)?;
if is_tnt {
self.spawn_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), true);
// TntBlock.wasExploded: new PrimedTnt (its push drawn first), then
// getRandomShortFuse(80); no game event.
if is_tnt && self.ui.rules.bool("tnt_explodes") {
let r = &mut self.world.random;
let rot = r.next_double() * f64::from(std::f32::consts::TAU);
let fuse = r.next_int_bound(20).unwrap_or(0) + 10;
self.add_primed_tnt(BlockPos::new(pos[0], pos[1], pos[2]), rot, fuse);
}
Ok(())
}
+304
View File
@@ -0,0 +1,304 @@
//! Horizon's extras in the game (`docs/extras.md`): the zoom key and wheel,
//! clicks for the keystroke overlay, frame times for the FPS counter, the
//! minimap's tiles and image, and their HUD. Each hook does nothing while its
//! extra is off.
use super::{Dim, Game, Screen};
use horizon_client::{
extras::{Corner, Cps, FpsCounter, Zoom, fov_target, turn_scale},
extras_hud::{self, Corners, Keystrokes},
hud::{HudBatch, MINIMAP_SPRITE},
keybinds,
minimap::{self, Layer, Minimap, View},
multiplayer,
reconnect::{Retry, Tracker},
title::Mode,
};
use std::time::Duration;
use winit::{event::MouseButton, keyboard::KeyCode};
#[derive(Default)]
pub(super) struct ExtrasState {
zoom: Zoom,
fps: FpsCounter,
/// Left and right mouse buttons: held, and their clicks.
mouse: [bool; 2],
cps: [Cps; 2],
minimap: Minimap,
/// The dimension the minimap's tiles belong to.
minimap_dim: Option<Dim>,
/// Auto-reconnect's attempts at the current server.
reconnect: Tracker,
}
/// CPU time the minimap's tiles may take per frame.
const MINIMAP_BUDGET: Duration = Duration::from_micros(300);
impl Game<'_> {
fn extras_now(&self) -> f64 {
self.started.elapsed().as_secs_f64()
}
fn zoom_key(&self) -> Option<KeyCode> {
let e = &self.settings.extras;
e.zoom.then(|| keybinds::key_code(&e.zoom_key)).flatten()
}
/// A key press or release. The zoom key zooms only while playing with
/// no text open; the key itself always goes on to the screen and the key
/// binds, as a vanilla key mapping's would.
pub(super) fn extras_key(&mut self, key: KeyCode, pressed: bool, repeat: bool) {
if self.zoom_key() != Some(key) {
return;
}
let playing = self.screen == Screen::Playing
&& self.title.is_none()
&& self.sign_edit.is_none()
&& self.book.is_none();
let level = self.settings.extras.zoom_level;
self.extras.zoom.key(pressed, repeat, playing, level);
}
/// Wheel steps while playing; true when zooming took them from the hotbar.
pub(super) fn extras_scroll(&mut self, steps: f32) -> bool {
self.settings.extras.zoom && self.extras.zoom.scroll(steps)
}
/// Mouse buttons while playing, for the keystroke overlay.
pub(super) fn extras_mouse(&mut self, button: MouseButton, pressed: bool) {
let i = match button {
MouseButton::Left => 0,
MouseButton::Right => 1,
_ => return,
};
self.extras.mouse[i] = pressed;
if pressed && self.settings.extras.keystrokes {
let now = self.extras_now();
self.extras.cps[i].click(now);
}
}
/// Once per frame: the frame's time, and keys let go behind screens.
pub(super) fn extras_frame(&mut self, elapsed: Duration) {
// Under agent control the window may lack focus without pausing.
let focused = self.focused || self.control.is_some();
let playing = self.screen == Screen::Playing && self.title.is_none() && focused;
if !playing || !self.settings.extras.zoom {
self.extras.zoom.release();
}
if !playing {
self.extras.mouse = [false; 2];
}
self.update_minimap();
if self.settings.extras.fps {
let now = self.extras_now();
self.extras.fps.record(now, elapsed.as_secs_f32() * 1000.0);
} else {
self.extras.fps.clear();
}
}
/// 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);
}
/// Auto-reconnect: the server let the player in.
pub(super) fn extras_joined(&mut self) {
self.extras.reconnect.joined(std::time::Instant::now());
}
/// Auto-reconnect: the player left the server on purpose.
pub(super) fn extras_left(&mut self) {
self.extras.reconnect.reset();
}
/// Auto-reconnect's next attempt after a disconnect, when it is on and
/// the reason allows one.
pub(super) fn reconnect_after(&mut self, reason: &str, from_server: bool) -> Option<Retry> {
if !self.settings.extras.auto_reconnect {
self.extras.reconnect.reset();
return None;
}
let now = std::time::Instant::now();
self.extras.reconnect.ended(reason, from_server, now)
}
/// Show the attempt's countdown on the Disconnected screen.
pub(super) fn offer_reconnect(&mut self, retry: Option<Retry>) {
let Some(retry) = retry else {
return;
};
if let Some(title) = self.title.as_mut()
&& let Mode::Multiplayer(multiplayer::Screen::Disconnected { retry: slot, .. }) =
&mut title.mode
{
log::info!(
"Horizon: reconnecting to {} in {} s",
retry.address,
retry.seconds_left(std::time::Instant::now())
);
*slot = Some(retry);
}
}
/// Auto-reconnect: connect again once the countdown is over. An
/// online-mode server gets the signed-in account again: `connect_server`
/// takes it from `auth::current()`, held in memory for the whole run
/// (the launcher's session file is gone after the first read).
pub(super) fn extras_retry(&mut self) -> horizon_client::Result<()> {
if let Some(retry) = self.title.as_mut().and_then(|t| t.due_retry()) {
self.connect_server(&retry.address, &retry.name)?;
}
Ok(())
}
/// The minimap's view of the player, if it shows.
fn minimap_view(&self) -> Option<View> {
let e = &self.settings.extras;
let p = self.player.as_ref()?;
let shown = e.minimap && self.title.is_none() && !self.ui.hide_gui;
shown.then_some(View {
x: p.position.x,
z: p.position.z,
yaw: self.yaw,
rotate: e.minimap_rotate,
blocks_per_pixel: e.minimap_zoom,
round: e.minimap_round,
})
}
/// Refresh the minimap's tiles within the frame budget, recompose its
/// image when the view or a tile changed, and queue the upload.
fn update_minimap(&mut self) {
let Some(view) = self.minimap_view() else {
if !self.settings.extras.minimap || self.player.is_none() {
self.extras.minimap.clear();
self.extras.minimap_dim = None;
}
return;
};
if self.extras.minimap_dim != Some(self.dim) {
self.extras.minimap.clear();
self.extras.minimap_dim = Some(self.dim);
}
let Some(p) = self.player.as_ref() else {
return;
};
let head = (p.position.y + f64::from(p.dimensions.eye_height)).floor() as i32;
let (bx, bz) = (view.x.floor() as i32, view.z.floor() as i32);
// Underground, under a roof or in the Nether: the floor around the player.
let covered = self.world.light(bx, head, bz) >> 4 == 0;
let layer = if self.dim == Dim::Nether || covered {
Layer::Below(head)
} else {
Layer::Surface
};
// The chunks the image can reach (its corners when it turns).
let reach = minimap::SIZE as f32 / 2.0 * view.blocks_per_pixel * std::f32::consts::SQRT_2;
let radius = ((reach / 16.0).ceil() as i32 + 1).min(self.settings.render_distance.max(2));
self.extras.minimap.update(
&self.world,
&self.res.facts,
(bx >> 4, bz >> 4),
radius,
layer,
MINIMAP_BUDGET,
);
if !self.extras.minimap.compose(view) {
return;
}
let Some(rect) = self.res.atlas.sprites.get(MINIMAP_SPRITE).copied() else {
return;
};
let (w, h) = (self.res.atlas.width as f32, self.res.atlas.height as f32);
self.map_patches.push(horizon_client::font::Patch {
x: (rect.u0 * w).round() as u32,
y: (rect.v0 * h).round() as u32,
width: minimap::SIZE as u32,
height: minimap::SIZE as u32,
rgba: self.extras.minimap.image.clone(),
});
}
/// The zoom in effect (1 unless the key is held).
fn zoom_factor(&self) -> f32 {
self.extras.zoom.factor(self.scoping())
}
/// The field-of-view modifier target, divided by a smooth zoom.
pub(super) fn zoomed_fov_target(&self, vanilla: f32) -> f32 {
if self.settings.extras.zoom_smooth {
fov_target(vanilla, self.zoom_factor())
} else {
vanilla
}
}
/// The field of view in degrees, divided by an instant zoom.
pub(super) fn zoomed_fov_degrees(&self, fov: f32) -> f32 {
if self.settings.extras.zoom_smooth {
fov
} else {
fov / self.zoom_factor()
}
}
/// Mouse turning while zoomed.
pub(super) fn zoom_turn_scale(&self) -> f64 {
turn_scale(self.zoom_factor(), self.settings.extras.zoom_sensitivity)
}
/// The FPS counter and keystrokes, in the HUD layer (hidden with F1 by
/// the caller). The top left corner gives way to the debug screen.
pub(super) fn draw_extras(&mut self, batch: &mut HudBatch) {
let e = &self.settings.extras;
if !e.fps && !e.keystrokes && !e.minimap {
return;
}
let (fps_on, fps_corner, lows) = (e.fps, e.fps_corner, e.fps_lows);
let (keys_on, keys_corner, cps_on) = (e.keystrokes, e.keystrokes_corner, e.keystrokes_cps);
let (map_corner, map_size) = (e.minimap_corner, f32::from(e.minimap_size));
let visible = |corner| !(self.debug && corner == Corner::TopLeft);
let mut corners = Corners::new(batch.width, batch.height, self.effect_rows_height());
let atlas = &self.res.atlas;
if let Some(view) = self.minimap_view()
&& visible(map_corner)
&& !self.extras.minimap.image.is_empty()
&& let Some(image) = atlas.sprites.get(MINIMAP_SPRITE).copied()
{
let (arrow, north) = if view.rotate {
(0.0, Some(view.north()))
} else {
(180.0 + view.yaw, None)
};
let look = extras_hud::MinimapLook {
corner: map_corner,
size: map_size,
image,
arrow,
north,
};
extras_hud::draw_minimap(batch, atlas, &mut corners, &look);
}
if fps_on && visible(fps_corner) {
let reading = self.extras.fps.reading();
extras_hud::draw_fps(batch, atlas, &mut corners, fps_corner, reading, lows);
}
if keys_on && visible(keys_corner) {
let now = self.extras_now();
let cps = cps_on.then(|| {
let [l, r] = &mut self.extras.cps;
(l.per_second(now), r.per_second(now))
});
let held = |k| self.keys.contains(&k);
let label = |name| keybinds::display_name(self.settings.keys.get(name)).plain();
let k = Keystrokes {
moves: [
(held(KeyCode::KeyW), label("key.forward")),
(held(KeyCode::KeyA), label("key.left")),
(held(KeyCode::KeyS), label("key.back")),
(held(KeyCode::KeyD), label("key.right")),
],
jump: held(KeyCode::Space),
attack: self.extras.mouse[0],
use_: self.extras.mouse[1],
cps,
};
extras_hud::draw_keystrokes(batch, &self.res.atlas, &mut corners, keys_corner, &k);
}
}
/// The height the status effect icons take at the top right
/// (`Hud.extractEffects`: beneficial at y 1, harmful at y 26).
fn effect_rows_height(&self) -> f32 {
let effects = &self.potions.effects.list;
if effects.is_empty() || self.screen != Screen::Playing {
return 0.0;
}
let harmful = effects.iter().any(|e| {
horizon_client::brewing::effect(e.id)
.is_some_and(|d| d.category != horizon_client::brewing::Category::Beneficial)
});
if harmful { 50.0 } else { 25.0 }
}
}
+4 -2
View File
@@ -54,6 +54,7 @@ impl Game<'_> {
let target = self
.fov_player()
.map_or(1.0, |p| field_of_view_modifier(&p, first_person, effect));
let target = self.zoomed_fov_target(target);
let eye = self.player.as_ref().map(|p| p.dimensions.eye_height);
self.view.tick(eye, target);
}
@@ -77,14 +78,15 @@ impl Game<'_> {
}
/// `Camera.calculateFov` with `modifyFovBasedOnDeathOrFluid`.
pub(super) fn fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 {
self.view.calculate_fov(
let fov = self.view.calculate_fov(
partial,
self.settings.fov as i32,
self.fov_effect_scale(),
self.death_time(),
self.camera_fluid(camera),
false,
)
);
self.zoomed_fov_degrees(fov)
}
/// `Camera.calculateHudFov`: the first-person hand's field of view.
pub(super) fn hud_fov_degrees(&self, partial: f32, camera: [f64; 3]) -> f32 {
+3 -1
View File
@@ -535,7 +535,9 @@ impl Game<'_> {
let hint = if enabled { "disable" } else { "enable" };
let style = text::Style {
color: Some(if enabled { text::GREEN } else { text::RED }),
suggest: Some(format!("/datapack {hint} \"{id}\"")),
click: Some(text::ClickEvent::SuggestCommand(format!(
"/datapack {hint} \"{id}\""
))),
..text::Style::default()
};
let description = self
+19 -1
View File
@@ -212,8 +212,26 @@ impl Game<'_> {
}
}
}
/// `Minecraft.crosshairPickEntity` when it is a `LivingEntity`: whether
/// it is alive (the nearest entity under the crosshair, before any block).
pub(super) fn crosshair_living(&self) -> Option<bool> {
let nearest = |hits: &[Option<f64>]| hits.iter().flatten().copied().reduce(f64::min);
let living = nearest(&[
self.mob_hit().map(|h| h.1),
self.armor_stand_hit().map(|h| h.1),
self.dragon_hit().map(|h| h.1),
])?;
let other = nearest(&[
self.painting_hit().map(|h| h.1),
self.frame_hit().map(|h| h.1),
self.boat_hit().map(|h| h.1),
self.cart_hit().map(|h| h.1),
]);
// Only alive mobs are hit, so a picked living entity is alive.
(self.before_block(living) && other.is_none_or(|o| living <= o)).then_some(true)
}
/// `Attributes.ATTACK_SPEED` with the main-hand item's modifier.
fn main_hand_attack_speed(&self) -> f64 {
pub(super) fn main_hand_attack_speed(&self) -> f64 {
horizon_client::attack_strength::BASE_ATTACK_SPEED
+ self
.held()
+17 -4
View File
@@ -128,6 +128,9 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
if m.health < m.kind.max_health {
meta.push((9, serializer::FLOAT, Value::Float(m.health.max(0.0))));
}
if kind == "minecraft:rabbit" && m.no_ai {
meta.push((15, serializer::BYTE, Value::Byte(1)));
}
if m.is_baby()
&& let Some(index) = baby_index(kind)
{
@@ -222,9 +225,17 @@ fn mob_meta(m: &Mob, hub: &Hub) -> Vec<(u8, i32, Value)> {
meta.push((18, serializer::INT, Value::Int(e.size)));
}
}
// Creeper.DATA_IS_POWERED.
"minecraft:creeper" if e.charged => {
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
// Creeper.DATA_SWELL_DIR, DATA_IS_POWERED and DATA_IS_IGNITED: the
// guest swells the creeper from them. The direction always goes in,
// as only changed entries are sent and it drops back to -1.
"minecraft:creeper" => {
meta.push((16, serializer::INT, Value::Int(e.counter)));
if e.charged {
meta.push((17, serializer::BOOLEAN, Value::Bool(true)));
}
if e.flag {
meta.push((18, serializer::BOOLEAN, Value::Bool(true)));
}
}
// Enderman.DATA_CARRY_STATE.
"minecraft:enderman" => {
@@ -701,8 +712,10 @@ 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.
let except = if *id == 2015 { None } else { self.lan_acting };
self.lan_events
.push((*id, [pos.x, pos.y, pos.z], *data, self.lan_acting));
.push((*id, [pos.x, pos.y, pos.z], *data, except));
}
}
}
@@ -282,6 +282,9 @@ impl Game<'_> {
o.active(*button) && ui::hovered(self.cursor, *x, *y, *bw, 20.0)
})
.map(|b| b.0);
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(Button::DefaultMode) => o.default_mode = (o.default_mode + 1) % 4,
Some(Button::PersonalMode) => o.personal_mode = (o.personal_mode + 1) % 4,
@@ -1,12 +1,16 @@
//! Level events whose client handler (`LevelEventHandler`) spawns particles
//! on a block: electric sparks (3002), waxing (3003), wax off (3004) and
//! scraping (3005).
//! on a block: dragon egg teleportation (2015), electric sparks (3002),
//! waxing (3003), wax off (3004) and scraping (3005).
use super::Game;
use horizon_client::particles::{self, ParticleOptions, ParticleType};
use horizon_core::position::BlockPos;
use horizon_world::level::LevelEvent;
impl Game<'_> {
pub(super) fn dragon_egg_particles(&mut self, pos: [i32; 3], data: i32) {
self.particles
.block_teleportation(pos, data, self.settings.particles);
}
/// `LevelEventHandler.levelEvent` 3002 to 3005, drawing from the client
/// level's random.
pub(super) fn block_particle_event(&mut self, id: i32, pos: BlockPos, data: i32) {
+330
View File
@@ -0,0 +1,330 @@
//! Maces (`MaceItem`): a hit after falling more than one and a half blocks is
//! a smash attack. It adds damage for the height fallen (more with Density),
//! stops the fall, cancels its damage and knocks the creatures around the
//! target away. The rest of a weapon hit (`Player.itemAttackInteraction`)
//! is here too: `hurtEnemy`, the post-attack enchantments and `postHurtEnemy`.
use super::Game;
use horizon_client::{
enchant::EffectContext,
mobs::{Damage, Mob, Species},
particles::{ParticleOptions, ParticleType},
};
use horizon_core::{geometry::Vec3, position::BlockPos, random::RandomSource};
use horizon_world::registry::BlockStateId;
/// `MaceItem.SMASH_ATTACK_FALL_THRESHOLD`.
const FALL_THRESHOLD: f64 = 1.5;
/// `MaceItem.SMASH_ATTACK_HEAVY_THRESHOLD`.
const HEAVY_THRESHOLD: f64 = 5.0;
/// `MaceItem.SMASH_ATTACK_KNOCKBACK_RADIUS`.
const KNOCKBACK_RADIUS: f64 = 3.5;
/// `MaceItem.SMASH_ATTACK_KNOCKBACK_POWER`.
const KNOCKBACK_POWER: f32 = 0.7;
/// `Entity.isAlliedTo` between the player (`player` its UUID) and a mob
/// without teams: `TamableAnimal.considersEntityAsAlly` (a pet it tamed) and
/// `Allay.considersEntityAsAlly` (an allay that likes it).
fn ally_of_player(m: &Mob, player: Option<[i32; 4]>) -> bool {
let tamable = matches!(
m.species(),
Species::Wolf
| Species::Cat
| Species::Parrot
| Species::Nautilus
| Species::ZombieNautilus
);
tamable && m.extra.tame && m.extra.owner.is_some() && m.extra.owner == player
|| m.species() == Species::Allay && m.extra.tame
}
impl Game<'_> {
fn holds_mace(&self) -> bool {
self.inventory[self.selected]
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:mace")
}
/// `MaceItem.canSmashAttack` for the player: falling and not gliding.
fn can_smash_attack(&self) -> bool {
self.player
.as_ref()
.is_some_and(|p| p.fall_distance > FALL_THRESHOLD && !p.fall_flying)
}
/// A held mace about to smash (`MaceItem.getItemDamageSource`: the attack
/// is `mace_smash` damage).
pub(super) fn smash_attack(&self) -> bool {
self.holds_mace() && self.can_smash_attack()
}
/// The damage source of the player's hit from `from` with the held item.
pub(super) fn attack_source(&self, from: [f64; 3]) -> Damage {
if self.smash_attack() {
Damage::mace(from)
} else {
Damage::player(from)
}
}
/// `MaceItem.getAttackDamageBonus` against `victim`: 4 per block for the
/// first three blocks fallen, 2 for the next five, 1 after that, plus
/// `smash_damage_per_fallen_block` (Density) for every block.
pub(super) fn smash_damage_bonus(&mut self, victim: &str) -> f32 {
if !self.smash_attack() {
return 0.0;
}
let fall = self.player.as_ref().map_or(0.0, |p| p.fall_distance);
let damage = if fall <= 3.0 {
4.0 * fall
} else if fall <= 8.0 {
12.0 + 2.0 * (fall - 3.0)
} else {
22.0 + fall - 8.0
};
let held = self.inventory[self.selected].clone();
let ctx = EffectContext {
this: Some(victim),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some("minecraft:mace_smash"),
items: Some(&self.res.items),
..Default::default()
};
// EnchantmentHelper.modifyFallBasedDamage(..., 0)
let per_block = self.res.stations.enchantments.modify_value(
held.as_ref(),
"minecraft:smash_damage_per_fallen_block",
&ctx,
&mut self.world.random,
0.0,
);
(damage + f64::from(per_block) * fall) as f32
}
/// `LivingEntity.hurtServer` of the mob at `index` by the player's hit:
/// the weapon's `armor_effectiveness` enchantments (Breach) thin its armor.
pub(super) fn hurt_by_player(&mut self, index: usize, amount: f32, source: Damage) -> bool {
let held = self.inventory[self.selected].clone();
let kind = self.mobs[index].kind.id.clone();
let ctx = EffectContext {
this: Some(&kind),
attacker: Some("minecraft:player"),
direct_attacker: Some("minecraft:player"),
is_direct: true,
damage_type: Some(match source.kind {
horizon_client::mobs::DamageKind::MaceSmash => "minecraft:mace_smash",
_ => "minecraft:player_attack",
}),
items: Some(&self.res.items),
..Default::default()
};
let enchantments = &self.res.stations.enchantments;
let random = &mut self.world.random;
// CombatRules.getDamageAfterAbsorb: EnchantmentHelper.modifyArmorEffectiveness.
let mut breach = |fraction: f32| {
enchantments.modify_value(
held.as_ref(),
"minecraft:armor_effectiveness",
&ctx,
random,
fraction,
)
};
let old_health = self.mobs[index].health;
let hurt = self.mobs[index].damage_with(amount, source, Some(&mut breach));
if hurt && self.mobs[index].health != old_health {
self.mob_damage_event(self.mobs[index].id);
}
hurt
}
/// `Player.itemAttackInteraction` after the player's hit landed on the mob
/// at `index`: the item's `hurtEnemy` (the "used" statistic of a weapon),
/// the post-attack enchantments, then `postHurtEnemy` with the weapon's
/// wear.
pub(super) fn weapon_hit(&mut self, index: usize) {
let Some(stack) = self.inventory[self.selected].clone() else {
return;
};
let weapon = self
.res
.items
.get(&stack.item)
.and_then(|i| i.weapon_damage.map(|d| (d, i.max_damage)));
let smash = self.smash_attack();
if smash {
self.mace_hurt_enemy(index);
}
if weapon.is_some() {
self.stats.add("used", &stack.item, 1);
}
self.post_attack(index);
// MaceItem.postHurtEnemy
if smash && let Some(p) = self.player.as_mut() {
p.fall_distance = 0.0;
}
// ItemStack.postHurtEnemy: hurtAndBreak(weapon.itemDamagePerAttack).
if let Some((per_attack, max)) = weapon
&& max > 0
&& !self.creative
{
let loss = self.durability_loss(&stack, per_attack);
if let Some(held) = self.inventory[self.selected].as_mut() {
held.damage += loss;
if held.damage >= max {
self.inventory[self.selected] = None;
}
}
}
}
/// `MaceItem.hurtEnemy` for a smash: the fall stops and its damage is
/// waived from where the hit landed, the ground or air smash sounds, and
/// the knockback around the target.
fn mace_hurt_enemy(&mut self, index: usize) {
let target_on_ground = self.mobs[index].on_ground;
let Some(p) = self.player.as_mut() else {
return;
};
p.velocity = Vec3::new(p.velocity.x, f64::from(0.01f32), p.velocity.z);
// calculateImpactPosition: an earlier impact below the player stays.
let impact = match p.impulse.impact_position {
Some(at) if at.y <= p.position.y => at,
_ => p.position,
};
p.impulse.set_ignore_fall_damage(true, Some(impact));
let fall = p.fall_distance;
let feet = [p.position.x, p.position.y, p.position.z];
let sound = if target_on_ground {
p.spawn_extra_particles_on_fall = true;
if fall > HEAVY_THRESHOLD {
"minecraft:item.mace.smash_ground_heavy"
} else {
"minecraft:item.mace.smash_ground"
}
} else {
"minecraft:item.mace.smash_air"
};
self.audio.play(sound, Some(feet), 1.0, 1.0);
self.smash_knockback(index, fall);
}
/// `MaceItem.knockback`: the dust pillar (level event 2013) under the
/// target, then every living entity within 3.5 blocks of it but the
/// player and the target pushed away and up, harder after a fall of more
/// than five blocks. Spectators, the player's allies (`isAlliedTo`: its
/// pets and the allays that like it), marker armor stands and creative
/// flyers are spared; the predicate's own tamed-animal test asks whether
/// the target owns the animal, which a mob never does.
fn smash_knockback(&mut self, index: usize, fall: f64) {
let target = &self.mobs[index];
let (id, center) = (target.id, target.position);
// Entity.getOnPos without a supporting block.
let on_pos = [
center.x.floor() as i32,
(center.y - f64::from(1.0e-5f32)).floor() as i32,
center.z.floor() as i32,
];
self.level_event_at(2013, on_pos, 750);
let heavy = if fall > HEAVY_THRESHOLD { 2.0 } else { 1.0 };
// getKnockbackPower and the push of one entity at `at`.
let push = |at: Vec3, velocity: &mut Vec3, resistance: f64| {
let d = [at.x - center.x, at.y - center.y, at.z - center.z];
let distance_sqr = d[0] * d[0] + d[1] * d[1] + d[2] * d[2];
if distance_sqr > KNOCKBACK_RADIUS.powi(2) {
return;
}
let length = distance_sqr.sqrt();
let power = (KNOCKBACK_RADIUS - length)
* f64::from(KNOCKBACK_POWER)
* heavy
* (1.0 - resistance);
if power <= 0.0 {
return;
}
// Vec3.normalize: a vector shorter than 1e-5 has no direction.
let (x, z) = if length < f64::from(1.0e-5f32) {
(0.0, 0.0)
} else {
(d[0] / length * power, d[2] / length * power)
};
*velocity = Vec3::new(
velocity.x + x,
velocity.y + f64::from(KNOCKBACK_POWER),
velocity.z + z,
);
};
let player = self.level.player_uuid.or(Some([0, 0, 0, 1]));
for m in self
.mobs
.iter_mut()
.filter(|m| m.id != id && m.alive() && !m.removed && !ally_of_player(m, player))
{
push(m.position, &mut m.velocity, m.attrs.knockback_resistance);
}
for s in self.armor_stands.iter_mut().filter(|s| !s.marker) {
push(s.position, &mut s.velocity, 0.0);
}
}
/// `ServerPlayer.checkFallDamage` after a smash on a grounded target:
/// the landing block's particles, 50 for every block fallen (200 at most).
pub(super) fn smash_landing_particles(
&mut self,
state: BlockStateId,
pos: BlockPos,
fall_distance: f64,
) {
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let count = (50.0 * fall_distance).clamp(0.0, 200.0) as u32;
let spread = f64::from(0.3f32);
self.particles.send_particles(
&ParticleOptions::block(ParticleType::Block, sprite, tint),
[
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
],
[spread; 3],
f64::from(0.15f32),
count,
);
}
/// Level event 2013 (`ParticleUtils.spawnSmashAttackParticles`): dust
/// pillars of the block at `pos`, a cluster over it and a ring 3.5 out.
pub(super) fn smash_dust(&mut self, pos: BlockPos, count: i32) {
let state = self.world.block(pos.x, pos.y, pos.z);
let Some((sprite, tint)) = self.particle_sprite(state) else {
return;
};
let options = ParticleOptions::block(ParticleType::DustPillar, sprite, tint);
let center = [
f64::from(pos.x) + 0.5,
f64::from(pos.y) + 1.0,
f64::from(pos.z) + 0.5,
];
let near = f64::from(0.2f32);
let mut i = 0;
while (i as f32) < count as f32 / 3.0 {
let r = self.particles.random();
let x = center[0] + r.next_gaussian() / 2.0;
let z = center[2] + r.next_gaussian() / 2.0;
let v = [
r.next_gaussian() * near,
r.next_gaussian() * near,
r.next_gaussian() * near,
];
self.particles.add(&options, [x, center[1], z], v);
i += 1;
}
let far = f64::from(0.05f32);
let mut i = 0;
while (i as f32) < count as f32 / 1.5 {
let r = self.particles.random();
let angle = f64::from(i);
let x = center[0] + KNOCKBACK_RADIUS * angle.cos() + r.next_gaussian() / 2.0;
let z = center[2] + KNOCKBACK_RADIUS * angle.sin() + r.next_gaussian() / 2.0;
let v = [
r.next_gaussian() * far,
r.next_gaussian() * far,
r.next_gaussian() * far,
];
self.particles.add(&options, [x, center[1], z], v);
i += 1;
}
}
}
+39 -16
View File
@@ -16,6 +16,7 @@ use horizon_client::{
};
use horizon_core::{
geometry::{Aabb, Vec3},
position::BlockPos,
random::RandomSource,
};
use horizon_world::registry::BlockStateId;
@@ -1042,18 +1043,46 @@ impl Game<'_> {
if !self.before_block(d) || self.mob_hit().is_some_and(|m| m.1 < d) {
return false;
}
let burning = self
.held()
.is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0);
self.hurt_cart(i, damage, self.creative, burning);
self.swing_arm();
true
}
/// An arrow hit cart `i` (`MinecartTNT.hurtServer`, then
/// `VehicleEntity.hurtServer`): a burning arrow sets off a TNT minecart.
pub(super) fn arrow_hits_cart(
&mut self,
i: usize,
damage: f32,
arrow_velocity: Vec3,
burning: bool,
creative: bool,
) {
if i >= self.carts.len() {
return;
}
if burning && self.carts[i].kind == CartKind::Tnt {
let c = self.carts.remove(i);
self.explode_cart(&c, arrow_velocity.length_squared());
return;
}
self.hurt_cart(i, damage, creative, false);
}
/// `VehicleEntity.hurtServer`: shake, add the damage, break past 40 (at
/// once for creative players); TNT minecarts prime instead when moving
/// or hurt by fire.
fn hurt_cart(&mut self, i: usize, damage: f32, creative: bool, fire: bool) {
let c = &mut self.carts[i];
c.hurt_dir = -c.hurt_dir;
c.hurt_time = 10;
c.damage += damage * 10.0;
let destroyed = self.creative || c.damage > 40.0;
let destroyed = creative || c.damage > 40.0;
if destroyed {
let mut c = self.carts.remove(i);
let speed = c.velocity.x * c.velocity.x + c.velocity.z * c.velocity.z;
let burning = self
.held()
.is_some_and(|s| s.enchantment_level("minecraft:fire_aspect") > 0);
if c.kind == CartKind::Tnt && (burning || speed >= 0.01) {
if c.kind == CartKind::Tnt && (fire || speed >= 0.01) {
// MinecartTNT.destroy: prime instead of breaking.
if c.fuse < 0 {
self.prime_cart(&mut c);
@@ -1067,29 +1096,23 @@ impl Game<'_> {
for s in c.items.iter().flatten() {
self.spawn_item(s.clone(), at, [0.0, 0.1, 0.0], 10);
}
if !self.creative {
if !creative {
self.spawn_item(ItemStack::new(c.kind.id(), 1), at, [0.0, 0.1, 0.0], 10);
}
}
}
}
self.swing_arm();
true
}
/// A block model's faces under `m` (block space 0..1), lit flat.
fn block_model_vertices(
pub(super) fn block_model_vertices(
&self,
state: BlockStateId,
seed_pos: BlockPos,
m: glam::Mat4,
light: u32,
out: &mut Vec<Vertex>,
) {
let Ok(models) = self
.res
.assets
.model_catalog
.collect(state, horizon_core::position::BlockPos::new(0, 0, 0))
else {
let Ok(models) = self.res.assets.model_catalog.collect(state, seed_pos) else {
return;
};
for (_, model) in &models {
@@ -1238,7 +1261,7 @@ impl Game<'_> {
* glam::Mat4::from_translation(glam::Vec3::splat(-0.5));
let flash = c.kind == CartKind::Tnt && c.fuse > -1 && (c.fuse / 5) % 2 == 0;
let start = out.len();
self.block_model_vertices(state, m, packed, out);
self.block_model_vertices(state, BlockPos::default(), m, packed, out);
if flash {
// submitWhiteSolidBlock: OverlayTexture.u(1.0) on the cart's own light.
for v in &mut out[start..] {
@@ -28,7 +28,12 @@ impl Game<'_> {
while Instant::now() < deadline {
self.update_world();
if self.remote.is_none() {
error = Some("disconnected".to_owned());
error = Some(match self.title.as_ref().map(|t| &t.mode) {
Some(horizon_client::title::Mode::Multiplayer(
horizon_client::multiplayer::Screen::Disconnected { reason, .. },
)) => format!("disconnected: {reason}"),
_ => "disconnected".to_owned(),
});
break;
}
if Instant::now() >= next {
+17 -3
View File
@@ -44,12 +44,20 @@ impl Game<'_> {
}
pub(super) fn options_mouse(&mut self, pressed: bool, right: bool) -> Result<()> {
if !pressed {
self.ui.options.release();
if right {
return Ok(());
}
let events = self.ui.options.release();
self.dragging = false;
return Ok(());
return self.handle_option_events(events);
}
if !right {
self.dragging = true;
}
self.dragging = true;
let size = self.gui_size();
let framebuffer = self.renderer.as_ref().map_or([1280, 720], |r| {
[r.config.width as i32, r.config.height as i32]
});
let mut ui = std::mem::take(&mut self.ui.options);
let events = ui.click(
&mut self.settings,
@@ -57,6 +65,7 @@ impl Game<'_> {
self.cursor.0,
self.cursor.1,
size,
framebuffer,
false,
right,
);
@@ -65,6 +74,9 @@ impl Game<'_> {
}
pub(super) fn options_drag(&mut self) -> Result<()> {
let size = self.gui_size();
let framebuffer = self.renderer.as_ref().map_or([1280, 720], |r| {
[r.config.width as i32, r.config.height as i32]
});
let mut ui = std::mem::take(&mut self.ui.options);
let events = ui.click(
&mut self.settings,
@@ -72,6 +84,7 @@ impl Game<'_> {
self.cursor.0,
self.cursor.1,
size,
framebuffer,
true,
false,
);
@@ -115,6 +128,7 @@ impl Game<'_> {
pub(super) fn handle_option_events(&mut self, events: Vec<Event>) -> Result<()> {
for e in events {
match e {
Event::ButtonClick => self.audio.play_button_click(),
Event::Changed => {
self.settings.save(&Self::options_path());
self.apply_settings();
+33 -12
View File
@@ -6,6 +6,7 @@ use horizon_client::{
Result,
chunk::Chunk,
entity_nbt,
mobs::Who,
save::{ChunkExtras, random_uuid},
};
use horizon_core::{geometry::Vec3, position::ChunkPos, random::RandomSource, ticks::ChunkTicks};
@@ -186,8 +187,15 @@ impl Game<'_> {
}
"minecraft:experience_orb" => self.orbs.extend(entity_nbt::orbs_from_nbt(&tag)),
"minecraft:arrow" => {
if let Some(a) = entity_nbt::arrow_from_nbt(&tag, player_uuid) {
self.arrows.push(a);
if let Some((mut p, in_block)) = entity_nbt::arrow_from_nbt(
&tag,
player_uuid,
super::dispenser::tipped_effect,
) {
if let Some(a) = p.arrow.as_mut() {
a.last_state = in_block.and_then(|t| self.state_from_nbt(&t));
}
self.creatures.projectiles.push(p);
}
}
"minecraft:falling_block" => {
@@ -198,6 +206,8 @@ impl Game<'_> {
let (no_gravity, drop_item) = entity_nbt::falling_block_flags(&tag);
self.falling.push(FallingBlock {
state,
// DATA_START_POS is not persisted by vanilla.
start_pos: horizon_core::position::BlockPos::default(),
position,
previous: position,
velocity,
@@ -517,7 +527,7 @@ impl Game<'_> {
.id(&state)
.or_else(|| registry.default_state(&state.name))
}
fn state_to_nbt(&self, state: BlockStateId) -> Tag {
pub(in crate::game) fn state_to_nbt(&self, state: BlockStateId) -> Tag {
let registry = self.res.assets.registry;
match registry.state(state) {
Some(s) if registry.default_state(&s.name) == Some(state) => {
@@ -579,14 +589,23 @@ impl Game<'_> {
.push(with_raw(entity_nbt::orb_to_nbt(o, uuid), raw.as_ref()));
}
}
for a in &self.arrows {
if keys.contains(&chunk_of(a.position)) {
let owner = if a.from_player { player_uuid } else { None };
let (uuid, raw) = anon(&self.persist, "minecraft:arrow", a.position);
out.entry(chunk_of(a.position)).or_default().push(with_raw(
entity_nbt::arrow_to_nbt(a, uuid, owner),
raw.as_ref(),
));
for p in &self.creatures.projectiles {
if !keys.contains(&chunk_of(p.position)) {
continue;
}
let owner = if p.owner == Some(Who::Player) {
player_uuid
} else {
None
};
let (uuid, raw) = anon(&self.persist, "minecraft:arrow", p.position);
let in_block = p
.arrow
.as_ref()
.and_then(|a| a.last_state)
.map(|s| self.state_to_nbt(s));
if let Some(tag) = entity_nbt::arrow_to_nbt(p, uuid, owner, in_block, raw.as_ref()) {
out.entry(chunk_of(p.position)).or_default().push(tag);
}
}
for f in &self.falling {
@@ -796,7 +815,9 @@ impl Game<'_> {
keep
});
self.orbs.retain(|o| !gone(o.position));
self.arrows.retain(|a| !gone(a.position));
self.creatures
.projectiles
.retain(|p| p.arrow.is_none() || !gone(p.position));
self.falling.retain(|f| !gone(f.position));
self.persist
.anon
+65 -5
View File
@@ -158,7 +158,11 @@ impl Game<'_> {
let lang = Arc::new(horizon_client::net::load_language(&root));
let view = self.settings.render_distance.clamp(2, 32) as i8;
horizon_client::crash::set_detail("Server", address.to_owned());
let session = Session::connect(address, name, view, lang.clone());
// A signed-in account always plays under its own name.
let auth = horizon_client::auth::current();
let name = auth.as_ref().map_or(name, |a| a.name.as_str());
let session = Session::connect(address, name, auth.clone(), view, lang.clone());
self.extras_connecting(address, name);
let player_type = super::perspective::player_type(&root);
let mut streaming = Streaming::new(
Arc::new(NoTerrain),
@@ -179,7 +183,7 @@ impl Game<'_> {
self.player = None;
self.spawn = None;
self.mobs.clear();
self.arrows.clear();
self.creatures.projectiles.clear();
self.dropped.clear();
self.particles.clear();
self.orbs.clear();
@@ -257,6 +261,10 @@ impl Game<'_> {
/// Disconnect and return to the multiplayer screen (DisconnectedScreen).
pub(super) fn leave_server(&mut self, reason: Option<String>) -> Result<()> {
if reason.is_none() {
// Leaving on purpose: nothing for auto-reconnect to retry.
self.extras_left();
}
if let Some(mut r) = self.remote.take() {
r.session.disconnect();
}
@@ -281,7 +289,10 @@ impl Game<'_> {
let saves = std::env::current_dir()?.join("saves");
let mut title = horizon_client::title::Title::new(saves.clone());
title.mode = horizon_client::title::Mode::Multiplayer(match reason {
Some(reason) => horizon_client::multiplayer::Screen::Disconnected { reason },
Some(reason) => horizon_client::multiplayer::Screen::Disconnected {
reason,
retry: None,
},
None => horizon_client::multiplayer::Screen::list(&saves),
});
self.title = Some(title);
@@ -371,6 +382,7 @@ impl Game<'_> {
uuid,
} => {
self.set_registries(registries);
self.extras_joined();
if let Some(r) = self.remote.as_mut() {
r.joined = true;
r.profile = uuid;
@@ -386,9 +398,15 @@ impl Game<'_> {
}
}
}
Event::Disconnected(reason) => {
Event::Disconnected {
reason,
from_server,
} => {
log::info!("Horizon: disconnected: {reason}");
return self.leave_server(Some(reason));
let retry = self.reconnect_after(&reason, from_server);
self.leave_server(Some(reason))?;
self.offer_reconnect(retry);
return Ok(());
}
Event::Packet(packet) => self.handle_packet(*packet)?,
}
@@ -802,6 +820,9 @@ impl Game<'_> {
}
}
C::BlockChangedAck(_) => {}
C::LevelEvent(p) if p.kind == 2015 => {
self.dragon_egg_particles(p.pos, p.data);
}
C::LevelEvent(p) if p.kind == 2001 => {
// LevelEvent.PARTICLES_DESTROY_BLOCK: someone else broke a block.
let state = BlockStateId(p.data.max(0) as u32);
@@ -915,6 +936,30 @@ impl Game<'_> {
}
}
C::SetEntityData(p) => {
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Rabbit
{
for (index, _, value) in &p.values {
match (index, value) {
(15, Value::Byte(flags)) => m.no_ai = flags & 1 != 0,
(16, Value::Bool(baby)) => m.extra.age = if *baby { -1 } else { 0 },
_ => {}
}
}
}
if let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Creeper
{
for (index, _, value) in &p.values {
match (index, value) {
// Creeper.DATA_SWELL_DIR, DATA_IS_POWERED, DATA_IS_IGNITED.
(16, Value::Int(dir)) => m.extra.counter = *dir,
(17, Value::Bool(powered)) => m.extra.charged = *powered,
(18, Value::Bool(ignited)) => m.extra.flag = *ignited,
_ => {}
}
}
}
for (index, _, value) in &p.values {
if *index == ITEM_ENTITY_ITEM
&& let Value::Item(stack) = value
@@ -945,6 +990,12 @@ impl Game<'_> {
}
}
C::EntityEvent(p) => {
if p.event == 1
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
&& m.species() == horizon_client::mobs::Species::Rabbit
{
horizon_client::mobs::rabbit::hop_event(m);
}
// EntityEvent.DEATH: start the death animation.
if p.event == 3
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == p.id as u32)
@@ -1718,6 +1769,12 @@ impl Game<'_> {
m.previous_body_yaw = m.body_yaw;
m.previous_limb_speed = m.limb_speed;
m.age += 1;
if m.species() == horizon_client::mobs::Species::Rabbit {
horizon_client::mobs::rabbit::base_tick(m);
}
if m.species() == horizon_client::mobs::Species::Creeper {
horizon_client::mobs::hostile::creeper_client_tick(m);
}
if m.hurt_time > 0 {
m.hurt_time -= 1;
}
@@ -1740,6 +1797,9 @@ impl Game<'_> {
let target = (((dx * dx + dz * dz).sqrt() * 4.0) as f32).min(1.0);
m.limb_speed += (target - m.limb_speed) * 0.4;
m.limb_position += m.limb_speed;
if m.species() == horizon_client::mobs::Species::Rabbit {
horizon_client::mobs::rabbit::post_tick(m);
}
}
for d in &mut self.dropped {
d.previous = d.position;
@@ -85,7 +85,8 @@ impl Game<'_> {
render_distance_chunks: self.streaming.radius,
cloud_range_chunks: self.settings.cloud_range,
camera_y: camera.y,
min_y: MIN_Y,
// level.getMinY(): the Nether and the End start at y 0.
min_y: if self.dim == Dim::Overworld { MIN_Y } else { 0 },
flat: false,
forward: forward.map(|c| c as f32),
rain,
@@ -93,6 +94,7 @@ impl Game<'_> {
skybox: self.dim == Dim::Overworld,
blindness: None,
darkness: self.darkness_fog(),
boss_world_fog: self.dragon_bar_shown(),
})
}
/// `SkyRenderer.shouldRenderDarkDisc`: eye below the horizon (y 63) and not under water.
@@ -0,0 +1,595 @@
//! `RespawnAnchorBlock` in the game: glowstone charges it (`useItemOn`), a
//! right click on a charged anchor sets the respawn point in the Nether and
//! blows it up anywhere else (`useWithoutItem`), and respawning goes to it
//! (`ServerPlayer.findRespawnAndUseSpawnBlock`, `PlayerList.respawn`),
//! using a charge.
use super::{Dim, Game};
use horizon_client::{
Result,
blocks::Fluid,
collisions::{SceneCollisions, no_collision_empty},
items::ItemStack,
mobs::Who,
motion::PlayerMotion,
text::Text,
};
use horizon_core::{
geometry::{Aabb, Axis, Vec3, VoxelShape},
position::BlockPos,
random::RandomSource,
};
use horizon_world::{collision_context::CollisionContext, registry::BlockStateId};
/// `ServerPlayer.RespawnConfig`: a respawn point other than the world spawn
/// that the game resolves through its block (a respawn anchor).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct RespawnConfig {
pub dim: Dim,
pub pos: [i32; 3],
pub yaw: f32,
pub forced: bool,
}
/// `RespawnAnchorBlock.RESPAWN_HORIZONTAL_OFFSETS`, then the same a block
/// below, a block above, and straight above.
const HORIZONTAL: [[i32; 3]; 8] = [
[0, 0, -1],
[-1, 0, 0],
[0, 0, 1],
[1, 0, 0],
[-1, 0, -1],
[1, 0, -1],
[-1, 0, 1],
[1, 0, 1],
];
fn respawn_offsets() -> impl Iterator<Item = [i32; 3]> {
HORIZONTAL
.into_iter()
.chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y - 1, z]))
.chain(HORIZONTAL.into_iter().map(|[x, y, z]| [x, y + 1, z]))
.chain(std::iter::once([0, 1, 0]))
}
/// What a right click with an item does to an anchor before `useWithoutItem`.
pub(super) enum AnchorUse {
/// Glowstone charged it.
Charged,
/// `PASS`: the off hand's glowstone charges it instead.
Pass,
/// `TRY_WITH_EMPTY_HAND`, or not an anchor.
Other,
}
impl Game<'_> {
fn is_anchor(&self, state: BlockStateId) -> bool {
&*self.res.facts.get(state).name == "minecraft:respawn_anchor"
}
fn anchor_charges(&self, state: BlockStateId) -> i32 {
self.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("charges"))
.and_then(|c| c.parse().ok())
.unwrap_or(0)
}
fn anchor_with_charges(&self, state: BlockStateId, charges: i32) -> Option<BlockStateId> {
let mut s = self.res.assets.registry.state(state)?.clone();
s.properties.insert("charges".into(), charges.to_string());
self.res.assets.registry.resolve(&s).ok()
}
/// `RespawnAnchorBlock.canSetSpawn`: the `respawn_anchor_works` attribute
/// (only the Nether's dimension type sets it).
pub(super) fn anchor_works(&self) -> bool {
self.dim == Dim::Nether
}
/// `RespawnAnchorBlock.charge`: one more charge, the block change and the sound.
fn charge_anchor(
&mut self,
pos: [i32; 3],
state: BlockStateId,
who: Option<Who>,
) -> Result<()> {
let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) + 1) else {
return Ok(());
};
self.level_set(pos, next)?;
self.post_block_game_event("minecraft:block_change", pos, who, Some(next));
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio
.play("minecraft:block.respawn_anchor.charge", Some(at), 1.0, 1.0);
Ok(())
}
/// `RespawnAnchorBlock.useItemOn` with `held` in the main hand.
pub(super) fn use_respawn_anchor(
&mut self,
pos: [i32; 3],
held: Option<&ItemStack>,
) -> Result<AnchorUse> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !self.is_anchor(state) {
return Ok(AnchorUse::Other);
}
let fuel = |s: Option<&ItemStack>| s.is_some_and(|s| &*s.item == "minecraft:glowstone");
let chargeable = self.anchor_charges(state) < 4;
if fuel(held) && chargeable {
let used = held.cloned();
self.charge_anchor(pos, state, Some(Who::Player))?;
// itemStack.consume(1, player); the criterion sees the stack as used.
self.consume_held();
if let Some(stack) = used {
self.trigger_block("minecraft:item_used_on_block", pos, &stack);
}
return Ok(AnchorUse::Charged);
}
if fuel(self.offhand.as_ref()) && chargeable {
return Ok(AnchorUse::Pass);
}
Ok(AnchorUse::Other)
}
/// The off hand's glowstone on an anchor the main hand passed on.
pub(super) fn charge_anchor_from_offhand(&mut self, pos: [i32; 3]) -> Result<bool> {
let state = self.world.block(pos[0], pos[1], pos[2]);
let fuel = self
.offhand
.as_ref()
.is_some_and(|s| &*s.item == "minecraft:glowstone");
if !self.is_anchor(state) || !fuel || self.anchor_charges(state) >= 4 {
return Ok(false);
}
let used = self.offhand.clone();
self.charge_anchor(pos, state, Some(Who::Player))?;
if !self.creative
&& let Some(s) = self.offhand.as_mut()
{
s.count -= 1;
if s.count == 0 {
self.offhand = None;
}
}
if let Some(stack) = used {
self.trigger_block("minecraft:item_used_on_block", pos, &stack);
}
self.swing_arm();
Ok(true)
}
/// `RespawnAnchorBlock.useWithoutItem` on a charged anchor: outside the
/// Nether it explodes; inside, it becomes the respawn point.
pub(super) fn respawn_anchor_used(&mut self, pos: [i32; 3]) -> Result<()> {
let state = self.world.block(pos[0], pos[1], pos[2]);
if !self.anchor_works() {
return self.explode_anchor(pos, state);
}
let config = RespawnConfig {
dim: self.dim,
pos,
yaw: 0.0,
forced: false,
};
// RespawnConfig.isSamePosition: dimension and block.
let same = self
.respawn_config
.is_some_and(|c| c.dim == config.dim && c.pos == config.pos);
if !same {
// setRespawnPosition(config, true): the message, the point; the
// anchor replaces a bed.
self.system_message(Text::translate("block.minecraft.set_spawn", &[]));
self.respawn_config = Some(config);
if let Some([x, y, z]) = self.level.world_spawn {
self.spawn = Some(Vec3::new(
f64::from(x) + 0.5,
f64::from(y),
f64::from(z) + 0.5,
));
}
let at = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.audio.play(
"minecraft:block.respawn_anchor.set_spawn",
Some(at),
1.0,
1.0,
);
}
Ok(())
}
/// `RespawnAnchorBlock.isWaterThatWouldFlow`.
fn water_would_flow(&self, p: [i32; 3]) -> bool {
let f = self.res.facts.get(self.world.block(p[0], p[1], p[2]));
if f.fluid != Fluid::Water {
return false;
}
if f.fluid_level == 8 && !f.fluid_falling {
return true;
}
if f.fluid_level < 2 {
return false;
}
self.res
.facts
.get(self.world.block(p[0], p[1] - 1, p[2]))
.fluid
!= Fluid::Water
}
/// `RespawnAnchorBlock.explode`: the anchor goes, then a power 5 fiery
/// explosion (`badRespawnPointExplosion`, `ExplosionInteraction.BLOCK`)
/// whose centre resists like water when water would flow into it.
fn explode_anchor(&mut self, pos: [i32; 3], _state: BlockStateId) -> Result<()> {
self.level_set(pos, self.world.air)?;
let horizontal = [[0, 0, -1], [0, 0, 1], [-1, 0, 0], [1, 0, 0]]
.into_iter()
.any(|d| self.water_would_flow([pos[0] + d[0], pos[1], pos[2] + d[2]]));
let above = self
.res
.facts
.get(self.world.block(pos[0], pos[1] + 1, pos[2]))
.fluid
== Fluid::Water;
let in_water = horizontal || above;
let center = [
f64::from(pos[0]) + 0.5,
f64::from(pos[1]) + 0.5,
f64::from(pos[2]) + 0.5,
];
self.block_explosion(center, in_water.then_some(pos))
}
/// `BedRule.destroyOnUse` of the dimension's `bed_rule` and
/// `straw_bed_rule`: true in the Nether and the End.
pub(super) fn beds_destroy_on_use(&self) -> bool {
self.dim != Dim::Overworld
}
/// `AbstractBedBlock.useWithoutItem` where the bed rule destroys on use
/// (the bed's head at `head`): `BedBlock.destroyOnUse` removes both
/// halves and explodes; `StrawBedBlock` just falls apart.
pub(super) fn destroy_bed_on_use(&mut self, head: [i32; 3]) -> Result<()> {
let state = self.world.block(head[0], head[1], head[2]);
let name = self.res.facts.get(state).name.clone();
let center = [
f64::from(head[0]) + 0.5,
f64::from(head[1]) + 0.5,
f64::from(head[2]) + 0.5,
];
if &*name == "minecraft:straw_bed" {
// StrawBedBlock.destroyBed.
self.audio.play(
"minecraft:block.straw_bed.break_leave",
Some(center),
1.0,
1.0,
);
return self.level_set(head, self.world.air);
}
// removeBlock(head), then the foot behind it if it is still this bed.
let facing = self
.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("facing").cloned())
.unwrap_or_default();
let back = match facing.as_str() {
"north" => [0, 0, 1],
"south" => [0, 0, -1],
"west" => [1, 0, 0],
_ => [-1, 0, 0],
};
self.level_set(head, self.world.air)?;
let foot = [head[0] + back[0], head[1], head[2] + back[2]];
if self
.res
.facts
.get(self.world.block(foot[0], foot[1], foot[2]))
.name
== name
{
self.level_set(foot, self.world.air)?;
}
self.block_explosion(center, None)
}
/// `Level.explode(null, badRespawnPointExplosion(center), calculator,
/// center, 5, true, ExplosionInteraction.BLOCK)` (beds and anchors):
/// `water_at` is the block that resists like water.
pub(super) fn block_explosion(
&mut self,
center: [f64; 3],
water_at: Option<[i32; 3]>,
) -> Result<()> {
let interaction = if self.ui.rules.bool("block_explosion_drop_decay") {
super::explosion::BlockInteraction::DestroyWithDecay
} else {
super::explosion::BlockInteraction::Destroy
};
self.server_explode_as(
center,
5.0,
interaction,
true,
"minecraft:bad_respawn_point",
water_at.map(|p| (p, 100.0)),
)
}
// ---- respawning -------------------------------------------------------
/// `DismountHelper.nonClimbableShape`: the collision shape, empty for
/// climbable blocks and open trapdoors.
fn non_climbable_shape(&self, p: [i32; 3]) -> VoxelShape {
let state = self.world.block(p[0], p[1], p[2]);
let name = &self.res.facts.get(state).name;
let open_trapdoor = name.ends_with("_trapdoor")
&& self
.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("open"))
.is_some_and(|v| v == "true");
if self.block_in_tag("minecraft:climbable", name) || open_trapdoor {
return VoxelShape::empty();
}
let binding = self.collision;
let mut scene = SceneCollisions {
world: &self.world,
binding,
subject: None,
};
binding
.collision_shape_with_context(
&mut scene,
state,
BlockPos::new(p[0], p[1], p[2]),
&CollisionContext::empty(false),
)
.unwrap_or_else(|_| VoxelShape::empty())
}
fn block_in_tag(&self, tag: &str, block: &str) -> bool {
self.res
.items
.block_tags
.get(tag)
.is_some_and(|s| s.contains(block))
}
/// `EntityType.isBlockDangerous` for the player.
fn dangerous_for_player(&self, p: [i32; 3]) -> bool {
let state = self.world.block(p[0], p[1], p[2]);
let name = &*self.res.facts.get(state).name;
let lit_campfire = (name == "minecraft:campfire" || name == "minecraft:soul_campfire")
&& self
.res
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("lit"))
.is_some_and(|v| v == "true");
// NodeEvaluator.isBurningBlock, then the hurting plants and snow.
self.block_in_tag("minecraft:fire", name)
|| matches!(
name,
"minecraft:lava"
| "minecraft:magma_block"
| "minecraft:lava_cauldron"
| "minecraft:wither_rose"
| "minecraft:sweet_berry_bush"
| "minecraft:cactus"
| "minecraft:powder_snow"
)
|| lit_campfire
}
/// `DismountHelper.findSafeDismountLocation` for a standing player.
fn safe_dismount_location(&self, p: [i32; 3], check_dangerous: bool) -> Option<Vec3> {
if check_dangerous && self.dangerous_for_player(p) {
return None;
}
let shape = self.non_climbable_shape(p);
let below = self.non_climbable_shape([p[0], p[1] - 1, p[2]]);
let floor = horizon_core::geometry::block_floor_height(&shape, || &below);
// DismountHelper.isBlockFloorValid.
if floor.is_infinite() || floor >= 1.0 {
return None;
}
if check_dangerous && floor <= 0.0 && self.dangerous_for_player([p[0], p[1] - 1, p[2]]) {
return None;
}
let position = Vec3::new(
f64::from(p[0]) + 0.5,
f64::from(p[1]) + floor,
f64::from(p[2]) + 0.5,
);
// EntityDimensions.makeBoundingBox for 0.6 by 1.8 (the half width is a float).
let half = f64::from(0.6f32 / 2.0);
let bounds = Aabb::new(
Vec3::new(position.x - half, position.y, position.z - half),
Vec3::new(
position.x + half,
position.y + f64::from(1.8f32),
position.z + half,
),
);
let mut scene = SceneCollisions {
world: &self.world,
binding: self.collision,
subject: None,
};
if !no_collision_empty(&mut scene, bounds) {
return None;
}
let name = |q: [i32; 3]| {
self.res
.facts
.get(self.world.block(q[0], q[1], q[2]))
.name
.clone()
};
if self.block_in_tag("minecraft:invalid_spawn_inside", &name(p))
|| self.block_in_tag(
"minecraft:invalid_spawn_inside",
&name([p[0], p[1] + 1, p[2]]),
)
{
return None;
}
// WorldBorder.isWithinBounds(box).
let (lo, hi) = (bounds.min(Axis::X), bounds.max(Axis::X) - 1.0e-5);
let (lz, hz) = (bounds.min(Axis::Z), bounds.max(Axis::Z) - 1.0e-5);
(self.border.contains(lo, lz) && self.border.contains(hi, hz)).then_some(position)
}
/// `RespawnAnchorBlock.findStandUpPosition`: a safe spot around the
/// anchor, else any spot.
pub(super) fn anchor_stand_up(&self, pos: [i32; 3]) -> Option<Vec3> {
for check in [true, false] {
for d in respawn_offsets() {
let p = [pos[0] + d[0], pos[1] + d[1], pos[2] + d[2]];
if let Some(at) = self.safe_dismount_location(p, check) {
return Some(at);
}
}
}
None
}
/// `ServerPlayer.findRespawnAndUseSpawnBlock` for an anchor config in the
/// loaded dimension: the position and yaw, using a charge.
pub(super) fn find_respawn_and_use(
&mut self,
c: RespawnConfig,
consume: bool,
) -> Result<Option<(Vec3, f32)>> {
let state = self.world.block(c.pos[0], c.pos[1], c.pos[2]);
if !(self.is_anchor(state)
&& (c.forced || self.anchor_charges(state) > 0)
&& self.anchor_works())
{
return Ok(None);
}
let stand = self.anchor_stand_up(c.pos);
if !c.forced
&& consume
&& stand.is_some()
&& let Some(next) = self.anchor_with_charges(state, self.anchor_charges(state) - 1)
{
self.level_set(c.pos, next)?;
}
Ok(stand.map(|p| (p, look_at_yaw(p, c.pos))))
}
/// The death screen's respawn with an anchor as the respawn point: travel
/// to its dimension and wait for its chunks (`travelling`), then resolve
/// it in [`Game::place_respawned`].
pub(super) fn begin_anchor_respawn(&mut self) -> Result<bool> {
let Some(config) = self.respawn_config else {
return Ok(false);
};
if self.player.is_none() {
return Ok(false);
}
if self.dim != config.dim {
self.end_portal_travel = false;
self.enter_dimension(config.dim)?;
} else {
let player = self.player.take().ok_or("player")?;
self.travelling = Some((player, Vec3::ZERO));
}
let target = Vec3::new(
f64::from(config.pos[0]) + 0.5,
f64::from(config.pos[1]),
f64::from(config.pos[2]) + 0.5,
);
if let Some((_, t)) = self.travelling.as_mut() {
*t = target;
}
self.end_travel = false;
self.respawn_travel = Some(config);
Ok(true)
}
/// `PlayerList.respawn` at an anchor once its dimension is loaded around
/// it: a fresh player at the stand-up position facing the anchor and the
/// deplete sound, or, with no anchor left, the world spawn and
/// `block.minecraft.spawn.not_valid`.
pub(super) fn place_respawned(&mut self, config: RespawnConfig) -> Result<()> {
match self.find_respawn_and_use(config, true)? {
Some((position, yaw)) => {
let mut player = PlayerMotion::new(self.motion, position)?;
player.yaw = yaw;
player.head_yaw = yaw;
self.yaw = yaw;
self.pitch = 0.0;
player.pitch = 0.0;
self.eye = 1.62;
self.previous_eye = 1.62;
self.clock.reset();
self.previous_position = position;
self.player = Some(player);
self.sway = Default::default();
self.apply_equipment();
// ClientboundSoundPacket at the block's corner, seeded from the level random.
let state = self
.world
.block(config.pos[0], config.pos[1], config.pos[2]);
if self.is_anchor(state) {
let _seed = self.world.random.next_long();
let at = [
f64::from(config.pos[0]),
f64::from(config.pos[1]),
f64::from(config.pos[2]),
];
self.audio
.play("minecraft:block.respawn_anchor.deplete", Some(at), 1.0, 1.0);
}
Ok(())
}
None => {
// TeleportTransition.missingRespawnBlock: the world spawn, and
// the point is forgotten.
self.respawn_config = None;
self.system_message(Text::translate("block.minecraft.spawn.not_valid", &[]));
let dead = PlayerMotion::new(self.motion, Vec3::ZERO)?;
if self.dim != Dim::Overworld {
// A dead stand-in travels; the arrival makes a fresh player.
let mut dead = dead;
dead.set_health(0.0, false)?;
self.player = Some(dead);
self.end_portal_travel = true;
let result = self.enter_dimension(Dim::Overworld);
self.end_portal_travel = false;
self.end_travel = true;
return result;
}
self.player = None;
self.spawn_player()
}
}
}
}
/// `RespawnPosAngle.calculateLookAtYaw`: the yaw from the position to the
/// bottom centre of the block.
fn look_at_yaw(position: Vec3, block: [i32; 3]) -> f32 {
let d = Vec3::new(
f64::from(block[0]) + 0.5 - position.x,
f64::from(block[1]) - position.y,
f64::from(block[2]) + 0.5 - position.z,
)
.normalize();
// Mth.atan2(z, x) * 180.0F / (float) Math.PI - 90.0: the compiled code
// multiplies by the folded float constant widened to double.
let degrees = horizon_core::geometry::trig::atan2(d.z, d.x)
* f64::from(horizon_core::geometry::trig::RAD_TO_DEG)
- 90.0;
wrap_degrees(degrees) as f32
}
/// `Mth.wrapDegrees(double)`.
fn wrap_degrees(degrees: f64) -> f64 {
let mut d = degrees % 360.0;
if d >= 180.0 {
d -= 360.0;
}
if d < -180.0 {
d += 360.0;
}
d
}
+110 -4
View File
@@ -10,9 +10,11 @@ use horizon_client::{
},
hud::HudBatch,
hud_layout, hud_overlays,
lan::guest::Guest,
save::{self, uuid_from_text, uuid_text},
scoreboard::{self as sb, Comp, Scoreboard, literal},
scoreboard_cmd::{self, Env, Holder},
tab_list::TabPlayer,
text::Text,
};
use horizon_world::nbt::Tag;
@@ -581,10 +583,10 @@ impl Game<'_> {
impl Game<'_> {
/// `Hud.extractTabList`: the player list while the player-list key is
/// held. A single-player world lists only its player, so it shows only
/// with a `list` objective.
/// held. A local world shows it with a joined LAN guest or a `list`
/// objective.
pub(super) fn draw_tab_list(&mut self, batch: &mut HudBatch) {
use horizon_client::tab_list::{self, TabInputs, TabPlayer};
use horizon_client::tab_list::{self, TabInputs};
let chatting = self.remote.is_some() && self.remote_chat_open();
let key = self.screen == super::Screen::Playing
&& !chatting
@@ -600,7 +602,14 @@ impl Game<'_> {
let mut me = TabPlayer::new(uuid, PLAYER_NAME);
me.game_mode = self.mode_id();
me.skin = "entity/player/wide/steve".into();
(vec![me], true, Vec::new())
let guests = self.lan.as_ref().map_or(&[][..], |h| &h.hub.guests);
let players = local_tab_players(me, guests);
let upside_down = players
.iter()
.filter(|p| p.name == "Dinnerbone" || p.name == "Grumm")
.map(|p| p.uuid)
.collect();
(players, true, upside_down)
}
};
let board = &self.score.board;
@@ -635,6 +644,18 @@ impl Game<'_> {
}
}
/// The host and guests that have entered the world, rebuilt from live state.
fn local_tab_players(me: TabPlayer, guests: &[Guest]) -> Vec<TabPlayer> {
let mut players = vec![me];
players.extend(guests.iter().filter(|g| g.placed).map(|g| {
let mut player = TabPlayer::new(g.uuid, &g.name);
player.game_mode = g.game_mode;
player.latency = g.latency.load(std::sync::atomic::Ordering::Relaxed);
player
}));
players
}
/// The commands' view of the game.
struct GameEnv<'a, 'b> {
g: &'a mut Game<'b>,
@@ -692,3 +713,88 @@ impl Env for GameEnv<'_, '_> {
self.g.feedback(message);
}
}
#[cfg(test)]
mod tab_list_tests {
use super::*;
use horizon_client::{
lan::{Joined, PlayerSender},
tab_list,
};
use horizon_protocol::packets::configuration::ClientInformation;
use std::sync::{
Arc,
atomic::{AtomicI32, Ordering},
mpsc,
};
fn guest(uuid: u128, name: &str) -> Guest {
let (tx, _rx) = mpsc::channel();
Guest::new(
Joined {
conn: uuid as u32,
uuid,
name: name.into(),
info: ClientInformation::new(8),
brand: "test".into(),
sender: PlayerSender {
tx,
pending: Arc::default(),
},
latency: Arc::new(AtomicI32::new(42)),
address: "127.0.0.1:25565".parse().unwrap(),
},
uuid as i32,
[0.0, 64.0, 0.0],
8,
)
}
#[test]
fn lan_tab_list_tracks_join_and_disconnect() {
let me = TabPlayer::new(1, PLAYER_NAME);
let mut guests = vec![guest(2, "Alex")];
let players = local_tab_players(me.clone(), &guests);
assert_eq!(players.as_slice(), std::slice::from_ref(&me));
assert!(!tab_list::visible(true, true, players.len(), false));
guests[0].placed = true;
let players = local_tab_players(me.clone(), &guests);
assert_eq!(players.len(), 2);
assert_eq!(players[0], me);
assert_eq!(players[1].uuid, 2);
assert_eq!(players[1].name, "Alex");
assert!(tab_list::visible(true, true, players.len(), false));
assert!(!tab_list::visible(false, true, players.len(), false));
guests.clear();
let players = local_tab_players(me, &guests);
assert_eq!(players.len(), 1);
assert!(!tab_list::visible(true, true, players.len(), false));
assert!(tab_list::visible(true, true, players.len(), true));
}
#[test]
fn lan_tab_list_reads_current_guest_state() {
let me = TabPlayer::new(1, PLAYER_NAME);
let mut guests = vec![guest(2, "Alex"), guest(3, "Grumm")];
for guest in &mut guests {
guest.placed = true;
}
guests[0].game_mode = tab_list::SPECTATOR;
let players = local_tab_players(me.clone(), &guests);
assert_eq!(players.len(), 3);
assert_eq!(players[1].game_mode, tab_list::SPECTATOR);
assert_eq!(players[1].latency, 42);
assert_eq!(players[1].skin, tab_list::default_skin(2));
assert_eq!(players[2].name, "Grumm");
guests[0].game_mode = 1;
guests[0].latency.store(123, Ordering::Relaxed);
guests.remove(1);
let players = local_tab_players(me, &guests);
assert_eq!(players.len(), 2);
assert_eq!(players[1].game_mode, 1);
assert_eq!(players[1].latency, 123);
}
}
+16
View File
@@ -151,6 +151,9 @@ impl Game<'_> {
.find(|b| b.5 && ui::hovered(self.cursor, b.0, b.1, b.2, 20.0))
.map(|b| b.4)
};
if hit.is_some() && !horizon_client::ui_theme::horizon() {
self.audio.play_button_click();
}
match hit {
Some(0) => {
self.screen = Screen::Playing;
@@ -255,12 +258,25 @@ impl Game<'_> {
.into_iter()
.find(|d| ui::hovered(self.cursor, d.0, d.1, 200.0, 20.0))
.map(|d| d.3);
if hit.is_some() {
self.audio.play_button_click();
}
match hit {
Some(0) if self.remote.is_some() => {
self.ui.death_text = None;
self.toggles.respawn();
self.remote_respawn();
}
Some(0) if self.respawn_config.is_some() => {
// LocalPlayer.respawn: KeyMapping.resetToggleKeys.
self.toggles.respawn();
// PlayerList.respawn at the respawn anchor, once it is loaded.
self.begin_anchor_respawn()?;
self.screen = Screen::Playing;
self.ui.death_text = None;
self.spawn_player()?;
self.capture(true);
}
Some(0) => {
// LocalPlayer.respawn: KeyMapping.resetToggleKeys.
self.toggles.respawn();
+13
View File
@@ -507,6 +507,19 @@ impl Game<'_> {
let ctx = self.who_context(who, state);
self.post_game_event(event, center((pos[0], pos[1], pos[2])), ctx);
}
/// `LivingEntity.actuallyHurt`'s damage vibration, heard as the hit lands;
/// the end-of-tick scan then knows this damage.
pub(super) fn mob_damage_event(&mut self, id: u32) {
if let Some(t) = self
.mobs
.iter()
.find(|m| m.id == id)
.and_then(|m| m.last_damage.map(|(_, t)| t))
{
self.sculk.damaged.insert(id, t);
}
self.post_entity_event("minecraft:entity_damage", Who::Mob(id));
}
/// A game event of an entity at its position.
pub(super) fn post_entity_event(&mut self, event: &'static str, who: Who) {
let at = match who {
@@ -145,6 +145,7 @@ impl Game<'_> {
let (x, y) = (b.width / 2.0 - 100.0, b.height / 4.0 + 144.0);
let (mx, my) = self.cursor;
if mx >= x && mx < x + 200.0 && my >= y && my < y + 20.0 {
self.audio.play_button_click();
self.close_sign_editor();
}
}
+48 -21
View File
@@ -101,13 +101,7 @@ impl Game<'_> {
],
Hit::None => return Ok(()),
};
self.wind_burst(
center,
radius,
knockback,
breeze,
p.owner == Some(Who::Player),
)
self.wind_burst(center, radius, knockback, breeze, !breeze)
}
/// `AbstractWindCharge.onHitEntity`: one point of damage.
fn wind_charge_damage(&mut self, p: &Projectile, who: Who) {
@@ -208,7 +202,8 @@ impl Game<'_> {
center: [f64; 3],
radius: f32,
multiplier: f32,
player_charge: bool,
wind_charge: bool,
blocklike: bool,
) {
let diameter = f64::from(radius * 2.0);
let distance = |p: [f64; 3]| {
@@ -257,11 +252,10 @@ impl Game<'_> {
p.velocity.y + dir[1] * power,
p.velocity.z + dir[2] * power,
);
// ServerPlayer.onExplosionHit: a player's own charge cancels the fall.
if player_charge {
let at = p.position;
p.impulse.set_ignore_fall_damage(true, Some(at));
}
// ServerPlayer.onExplosionHit: a wind charge's burst cancels the
// fall; any other burst ends the grace of the last impulse.
let at = p.position;
p.impulse.set_ignore_fall_damage(wind_charge, Some(at));
}
}
}
@@ -288,6 +282,39 @@ impl Game<'_> {
);
}
self.mobs = mobs;
// ArmorStand.ignoreExplosion: a visible stand feels only a burst that
// affects block-like entities (never a wind charge's).
if blocklike {
let mut stands = std::mem::take(&mut self.armor_stands);
for s in stands.iter_mut().filter(|s| !s.invisible) {
let feet = [s.position.x, s.position.y, s.position.z];
let dist = distance(feet) / diameter;
if dist > 1.0 {
continue;
}
// EntityType.ARMOR_STAND's size, halved when small; a marker has none.
let (w, h, eye) = if s.marker {
(0.0, 0.0, 0.0)
} else if s.small {
(0.125, f64::from(0.9875f32), f64::from(0.9875f32))
} else {
(0.25, f64::from(1.975f32), f64::from(1.7775f32))
};
let exposure = self.seen_percent(
center,
[feet[0] - w, feet[1], feet[2] - w],
[feet[0] + w, feet[1] + h, feet[2] + w],
);
let power = (1.0 - dist) * f64::from(exposure) * multiplier;
let dir = direction([feet[0], feet[1] + eye, feet[2]]);
s.velocity = Vec3::new(
s.velocity.x + dir[0] * power,
s.velocity.y + dir[1] * power,
s.velocity.z + dir[2] * power,
);
}
self.armor_stands = stands;
}
// Arrows and other projectiles (the charges themselves ignore it).
let push = |position: Vec3, velocity: &mut Vec3, game: &Game<'_>| {
let feet = [position.x, position.y, position.z];
@@ -319,11 +346,6 @@ impl Game<'_> {
push(p.position, &mut p.velocity, self);
}
self.creatures.projectiles = projectiles;
let mut arrows = std::mem::take(&mut self.arrows);
for a in arrows.iter_mut().filter(|a| !a.stuck) {
push(a.position, &mut a.velocity, self);
}
self.arrows = arrows;
let mut tnts = std::mem::take(&mut self.tnts);
for t in &mut tnts {
push(t.position, &mut t.velocity, self);
@@ -331,16 +353,21 @@ impl Game<'_> {
self.tnts = tnts;
}
/// The burst: knockback, the blocks that react, the gust and the sound.
fn wind_burst(
pub(super) fn wind_burst(
&mut self,
center: [f64; 3],
radius: f32,
multiplier: f32,
breeze: bool,
player_charge: bool,
wind_charge: bool,
) -> Result<()> {
// ServerExplosion.explode: the blast is heard first.
let ctx = horizon_client::sculk::Context::default();
self.post_game_event("minecraft:explode", center, ctx);
let mut targets = self.wind_positions(center, radius);
self.wind_knockback(center, radius, multiplier, player_charge);
// ServerExplosion.shouldAffectBlocklikeEntities
let blocklike = !breeze && !wind_charge && self.ui.rules.bool("mob_griefing");
self.wind_knockback(center, radius, multiplier, wind_charge, blocklike);
// Explosion.canTriggerBlocks: a breeze's charge needs mob griefing.
if !breeze || self.ui.rules.bool("mob_griefing") {
// Util.shuffle(list, level.random)
+46 -35
View File
@@ -273,6 +273,8 @@ pub struct Renderer {
lightmap_view: wgpu::TextureView,
lightmap_sampler: wgpu::Sampler,
animations: Vec<(SpriteAnimation, usize)>,
/// Each sprite layer's MipmapGenerator settings, for animation frames.
sprite_mips: Vec<crate::mipmap::Settings>,
/// Edge length of the block sprite array's layers.
sprite_size: u32,
indices: wgpu::Buffer,
@@ -320,41 +322,41 @@ pub struct Renderer {
pub animated_textures: bool,
present_modes: Vec<wgpu::PresentMode>,
}
fn mip_chain(pixels: &[u8], size: u32, layers: u32) -> (Vec<u8>, u32) {
/// Every layer's mip levels, layer major (`first` is the first layer's
/// index into `settings`), made by `MipmapGenerator`.
fn mip_chain(
pixels: &[u8],
size: u32,
settings: &[crate::mipmap::Settings],
first: u32,
layers: u32,
) -> (Vec<u8>, u32) {
let levels = size.trailing_zeros() + 1;
let layer_bytes = (size * size * 4) as usize;
let mut out = Vec::new();
for layer in 0..layers as usize {
let base =
&pixels[layer * (size * size * 4) as usize..(layer + 1) * (size * size * 4) as usize];
let mut level = base.to_vec();
let mut s = size as usize;
out.extend_from_slice(&level);
for _ in 1..levels {
let n = s / 2;
let mut next = vec![0u8; n * n * 4];
for y in 0..n {
for x in 0..n {
let mut acc = [0u32; 4];
let mut weight = 0u32;
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
let p = &level[((y * 2 + dy) * s + x * 2 + dx) * 4..][..4];
let a = u32::from(p[3]);
for c in 0..3 {
acc[c] += u32::from(p[c]) * a;
}
acc[3] += a;
weight += a;
}
let o = &mut next[(y * n + x) * 4..][..4];
for c in 0..3 {
o[c] = acc[c].checked_div(weight).unwrap_or(0) as u8;
}
o[3] = (acc[3] / 4) as u8;
}
}
out.extend_from_slice(&next);
level = next;
s = n;
let base = crate::mipmap::Image {
width: size,
height: size,
pixels: pixels[layer * layer_bytes..(layer + 1) * layer_bytes]
.as_chunks::<4>()
.0
.to_vec(),
};
let s = settings
.get(first as usize + layer)
.copied()
.unwrap_or_default();
let has_transparent = s.has_transparent || base.pixels.iter().any(|p| p[3] == 0);
for image in crate::mipmap::generate(
base,
levels - 1,
s.strategy,
s.alpha_cutoff_bias,
has_transparent,
s.item,
) {
out.extend(image.pixels.iter().flatten());
}
}
(out, levels)
@@ -395,6 +397,7 @@ impl Renderer {
sprite_pixels: &[u8],
sprite_size: u32,
layers: u32,
sprite_mips: &[crate::mipmap::Settings],
animations: &[SpriteAnimation],
hud_atlas: (&[u8], u32, u32),
forcefield: (&[u8], u32),
@@ -716,7 +719,7 @@ impl Renderer {
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, layers);
let (mips, mip_levels) = mip_chain(sprite_pixels, sprite_size, sprite_mips, 0, layers);
let sprite_texture = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
@@ -1101,7 +1104,8 @@ impl Renderer {
// WorldBorderRenderer: misc/forcefield.png as a MipmappedTexture
// (repeat, linear minification with mipmaps, nearest magnification).
let (forcefield_pixels, forcefield_size) = forcefield;
let (forcefield_mips, forcefield_levels) = mip_chain(forcefield_pixels, forcefield_size, 1);
let (forcefield_mips, forcefield_levels) =
mip_chain(forcefield_pixels, forcefield_size, &[], 0, 1);
let forcefield_texture = device.create_texture_with_data(
&queue,
&wgpu::TextureDescriptor {
@@ -1408,6 +1412,7 @@ impl Renderer {
lightmap_view,
lightmap_sampler,
animations: animations.iter().map(|a| (a.clone(), usize::MAX)).collect(),
sprite_mips: sprite_mips.to_vec(),
sprite_size,
indices,
index_quads,
@@ -1786,7 +1791,13 @@ impl Renderer {
continue;
}
*previous = frame;
let (mips, levels) = mip_chain(animation.pixels(frame), self.sprite_size, 1);
let (mips, levels) = mip_chain(
animation.pixels(frame),
self.sprite_size,
&self.sprite_mips,
animation.layer,
1,
);
let mut offset = 0;
for level in 0..levels.min(self.mip_levels) {
let size = self.sprite_size >> level;
+68 -18
View File
@@ -401,14 +401,6 @@ impl Item {
}
pub fn label(self, s: &Settings) -> Text {
match self {
// The vanilla button shows the scale alone, under its own caption.
Item::Vanilla(Opt::GuiScale) => Text::translate(
"options.generic_value",
&[
Text::translate("options.guiScale", &[]),
Opt::GuiScale.label(s),
],
),
Item::Vanilla(o) => o.label(s),
Item::Horizon(h) => h.label(s),
}
@@ -420,9 +412,9 @@ impl Item {
}
self.touched(s);
}
pub fn cycle(self, s: &mut Settings, back: bool) {
pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) {
match self {
Item::Vanilla(o) => o.cycle(s, back),
Item::Vanilla(o) => o.cycle(s, back, framebuffer),
Item::Horizon(h) => h.cycle(s, back),
}
self.touched(s);
@@ -456,6 +448,7 @@ impl Item {
/// What the options screens must do after an interaction here.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Action {
ButtonClick,
Changed,
OpenAdvanced,
OpenSimple,
@@ -655,6 +648,7 @@ impl GraphicsUi {
s: &mut Settings,
(x, y): (f32, f32),
(w, h): (f32, f32),
framebuffer: [i32; 2],
drag: bool,
right: bool,
) -> Vec<Action> {
@@ -671,6 +665,9 @@ impl GraphicsUi {
}
return Vec::new();
}
if right {
return Vec::new();
}
for wd in widgets {
if !ui::hovered((x, y), wd.x, wd.y, wd.w, 20.0) {
continue;
@@ -679,13 +676,14 @@ impl GraphicsUi {
continue;
}
return match wd.target {
Target::Button(action) => vec![action],
Target::Button(action) => vec![Action::ButtonClick, action],
Target::Item(item) => {
if item.slider(s).is_some() {
self.dragging = Some(item);
item.set_slider(s, ui::slider_value(wd.x, wd.w, x));
} else {
item.cycle(s, right);
item.cycle(s, right, framebuffer);
return vec![Action::ButtonClick, Action::Changed];
}
vec![Action::Changed]
}
@@ -693,8 +691,8 @@ impl GraphicsUi {
}
Vec::new()
}
pub fn release(&mut self) {
self.dragging = None;
pub fn release(&mut self) -> bool {
self.dragging.take().is_some()
}
pub fn scroll(&mut self, level: Level, h: f32, amount: f32) {
let content = Self::content_height(level);
@@ -708,6 +706,58 @@ impl GraphicsUi {
mod tests {
use super::*;
#[test]
fn graphics_buttons_sound_on_press_and_sliders_on_release() {
let mut s = Settings::default();
let mut ui = GraphicsUi::default();
let size = (480.0, 320.0);
let (widgets, _, _) = ui.layout(Level::Simple, size.0, size.1);
let button = widgets
.iter()
.find(|w| matches!(w.target, Target::Button(_)))
.unwrap();
let point = (button.x + 1.0, button.y + 1.0);
assert!(
ui.click(Level::Simple, &mut s, point, size, [854, 480], false, true)
.is_empty()
);
assert_eq!(
ui.click(Level::Simple, &mut s, point, size, [854, 480], false, false)[0],
Action::ButtonClick
);
assert!(!ui.release());
let slider = widgets
.iter()
.find(|w| matches!(w.target, Target::Item(i) if i.slider(&s).is_some()))
.unwrap();
assert_eq!(
ui.click(
Level::Simple,
&mut s,
(slider.x + 1.0, slider.y + 1.0),
size,
[854, 480],
false,
false
),
vec![Action::Changed]
);
assert_eq!(
ui.click(
Level::Simple,
&mut s,
(-100.0, -100.0),
size,
[854, 480],
true,
false
),
vec![Action::Changed]
);
assert!(ui.release());
assert!(!ui.release());
}
#[test]
fn scrolling_stops_at_both_limits_before_layout() {
for level in [Level::Simple, Level::Advanced] {
@@ -768,16 +818,16 @@ mod tests {
#[test]
fn presets_set_vanilla_and_horizon_options() {
let mut s = Settings::default();
Item::Horizon(H::Preset).cycle(&mut s, false);
Item::Horizon(H::Preset).cycle(&mut s, false, [854, 480]);
assert_eq!(s.horizon.preset, Preset::Performance);
assert_eq!(s.render_distance, 8);
assert_eq!(s.clouds, "false");
// Any quality change leaves the preset.
Item::Vanilla(Opt::Clouds).cycle(&mut s, false);
Item::Vanilla(Opt::Clouds).cycle(&mut s, false, [854, 480]);
assert_eq!(s.horizon.preset, Preset::Custom);
// Display preferences keep it.
Item::Horizon(H::Preset).cycle(&mut s, true);
Item::Vanilla(Opt::Vsync).cycle(&mut s, false);
Item::Horizon(H::Preset).cycle(&mut s, true, [854, 480]);
Item::Vanilla(Opt::Vsync).cycle(&mut s, false, [854, 480]);
assert_eq!(s.horizon.preset, Preset::Ultra);
}
+130 -30
View File
@@ -31,8 +31,12 @@ pub struct HudAtlas {
pub const GLYPH_ROWS: u32 = 512;
/// 128x128 atlas slots for map textures.
pub const MAP_SLOTS: usize = 16;
/// The atlas slot the minimap extra draws into.
pub const MINIMAP_SPRITE: &str = "horizon/minimap";
/// Atlas slots for downloaded player skins (`skins/<sha1>`), 64x64 each.
pub const SKIN_SLOTS: usize = 32;
/// Reused by the visible rows of the classic world selector.
pub const WORLD_ICON_SLOTS: usize = 32;
pub fn decode(path: &Path) -> Result<(u32, u32, Vec<u8>)> {
decode_bytes(&fs::read(path)?)
}
@@ -200,10 +204,25 @@ impl HudAtlas {
for i in 0..MAP_SLOTS {
images.push((format!("horizon/map{i}"), 128, 128, vec![0; 128 * 128 * 4]));
}
// The minimap extra's image (game/extras.rs).
images.push((
MINIMAP_SPRITE.into(),
crate::minimap::SIZE as u32,
crate::minimap::SIZE as u32,
vec![0; crate::minimap::SIZE * crate::minimap::SIZE * 4],
));
// Downloaded skins (game/scoreboard.rs) likewise.
for i in 0..SKIN_SLOTS {
images.push((format!("horizon/skin{i}"), 64, 64, vec![0; 64 * 64 * 4]));
}
for i in 0..WORLD_ICON_SLOTS {
images.push((
format!("horizon/world-icon{i}"),
64,
64,
vec![0; 64 * 64 * 4],
));
}
// Horizon-style menu text and corner masks (ui_theme), rasterized at run time.
images.push((
"horizon/ui-text".into(),
@@ -283,6 +302,9 @@ pub struct HudBatch {
pub height: f32,
/// Glyph pixels to upload into the atlas before drawing.
pub patches: Vec<crate::font::Patch>,
/// Vertex ranges drawn with `RenderPipelines.CROSSHAIR`'s
/// `BlendFunction.INVERT` instead of alpha blending.
pub invert: Vec<std::ops::Range<u32>>,
}
pub fn rgba(r: u8, g: u8, b: u8, a: u8) -> u32 {
u32::from(a) << 24 | u32::from(b) << 16 | u32::from(g) << 8 | u32::from(r)
@@ -305,8 +327,37 @@ impl HudBatch {
width: (window[0] as f32 / scale as f32).ceil(),
height: (window[1] as f32 / scale as f32).ceil(),
patches: Vec::new(),
invert: Vec::new(),
}
}
/// Draw the vertices added since `start` with the inverting blend.
pub fn invert_since(&mut self, start: usize) {
let range = start as u32..self.vertices.len() as u32;
if range.is_empty() {
return;
}
match self.invert.last_mut() {
Some(last) if last.end == range.start => last.end = range.end,
_ => self.invert.push(range),
}
}
/// The vertex ranges in order, each with whether it inverts.
pub fn runs(&self) -> Vec<(std::ops::Range<u32>, bool)> {
let mut out = Vec::new();
let mut at = 0;
for r in &self.invert {
if r.start > at {
out.push((at..r.start, false));
}
out.push((r.clone(), true));
at = r.end;
}
let end = self.vertices.len() as u32;
if end > at {
out.push((at..end, false));
}
out
}
/// `AbstractContainerScreen.init`: center in integer GUI coordinates.
pub fn centered_origin(&self, width: f32, height: f32) -> (f32, f32) {
(
@@ -595,6 +646,8 @@ pub struct HudRenderer {
/// The shared atlas texture, for run-time glyph uploads.
pub atlas_texture: Option<wgpu::Texture>,
pipeline: wgpu::RenderPipeline,
/// `RenderPipelines.CROSSHAIR`.
invert_pipeline: wgpu::RenderPipeline,
group: wgpu::BindGroup,
uniform: wgpu::Buffer,
buffer: wgpu::Buffer,
@@ -675,35 +728,55 @@ impl HudRenderer {
..Default::default()
});
let attributes = wgpu::vertex_attr_array![0=>Float32x2,1=>Float32x2,2=>Unorm8x4];
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("HUD"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<HudVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
let create = |label, blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_main"),
compilation_options: Default::default(),
buffers: &[Some(wgpu::VertexBufferLayout {
array_stride: std::mem::size_of::<HudVertex>() as u64,
step_mode: wgpu::VertexStepMode::Vertex,
attributes: &attributes,
})],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(blend),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let pipeline = create("HUD", wgpu::BlendState::ALPHA_BLENDING);
// BlendFunction.INVERT: ONE_MINUS_DST_COLOR, ONE_MINUS_SRC_COLOR,
// ONE, ZERO.
let invert_pipeline = create(
"HUD crosshair",
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::OneMinusDst,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::Zero,
operation: wgpu::BlendOperation::Add,
},
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_main"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
);
let capacity = 1 << 16;
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("HUD vertices"),
@@ -714,6 +787,7 @@ impl HudRenderer {
Ok(Self {
atlas_texture: None,
pipeline,
invert_pipeline,
group,
uniform,
buffer,
@@ -791,10 +865,16 @@ impl HudRenderer {
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, &self.group, &[]);
pass.set_vertex_buffer(0, self.buffer.slice(..));
pass.draw(0..count as u32, 0..1);
for (range, invert) in batch.runs() {
pass.set_pipeline(if invert {
&self.invert_pipeline
} else {
&self.pipeline
});
pass.draw(range, 0..1);
}
}
}
@@ -871,6 +951,25 @@ mod tests {
fs::remove_dir_all(root).unwrap();
}
#[test]
fn inverted_ranges_split_the_draws_in_order() {
let mut batch = HudBatch::new([854, 480]);
let quad = |b: &mut HudBatch| b.quad([[0.0; 2]; 4], [[0.0; 2]; 4], 0);
quad(&mut batch);
let start = batch.vertices.len();
quad(&mut batch);
batch.invert_since(start);
let start = batch.vertices.len();
quad(&mut batch);
batch.invert_since(start);
batch.invert_since(batch.vertices.len());
quad(&mut batch);
assert_eq!(batch.invert, vec![6..18]);
assert_eq!(
batch.runs(),
vec![(0..6, false), (6..18, true), (18..24, false)]
);
}
#[test]
fn container_origins_use_java_integer_division() {
// Odd scaled dimensions, odd image sizes and an oversized panel.
@@ -881,6 +980,7 @@ mod tests {
width: width as f32,
height: height as f32,
patches: Vec::new(),
invert: Vec::new(),
};
for (image_width, image_height) in [(195, 136), (176, 166), (176, 222)] {
assert_eq!(
+37 -5
View File
@@ -44,6 +44,8 @@ pub enum Blend {
Vignette,
/// `GUI_NAUSEA_OVERLAY`: additive.
Nausea,
/// `CROSSHAIR`: `BlendFunction.INVERT`, the colour under it inverted.
Crosshair,
}
impl Blend {
pub fn pipeline(self) -> &'static str {
@@ -51,6 +53,7 @@ impl Blend {
Blend::Textured => "pipeline/gui_textured",
Blend::Vignette => "pipeline/vignette",
Blend::Nausea => "pipeline/gui_nausea_overlay",
Blend::Crosshair => "pipeline/crosshair",
}
}
}
@@ -58,8 +61,8 @@ impl Blend {
/// One `GuiGraphicsExtractor` call.
#[derive(Clone, Debug, PartialEq)]
pub enum GuiDraw {
/// `blitSprite(sprite, x, y, w, h, color)`; `region` = (spriteW,
/// spriteH, u, v) for the partial overload.
/// `blitSprite(pipeline, sprite, x, y, w, h, color)`; `region` =
/// (spriteW, spriteH, u, v) for the partial overload.
Sprite {
sprite: Cow<'static, str>,
x: i32,
@@ -68,6 +71,7 @@ pub enum GuiDraw {
h: i32,
region: Option<[i32; 4]>,
color: u32,
blend: Blend,
},
/// `blitSprite(pipeline, TextureAtlasSprite, ...)` with a block atlas
/// sprite (the nether portal overlay).
@@ -136,6 +140,7 @@ fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw {
h,
region: None,
color: WHITE,
blend: Blend::Textured,
}
}
fn region(
@@ -154,8 +159,16 @@ fn region(
h,
region: Some([size[0], size[1], uv[0], uv[1]]),
color: WHITE,
blend: Blend::Textured,
}
}
/// A draw through `RenderPipelines.CROSSHAIR`.
fn crosshair_blend(mut d: GuiDraw) -> GuiDraw {
if let GuiDraw::Sprite { blend, .. } = &mut d {
*blend = Blend::Crosshair;
}
d
}
/// `graphics.fill`: the corners are sorted.
pub fn fill(x0: i32, y0: i32, x1: i32, y1: i32, color: u32) -> GuiDraw {
GuiDraw::Fill {
@@ -365,10 +378,25 @@ pub fn hotbar(w: i32, h: i32, i: &HotbarInputs) -> Vec<GuiDraw> {
out
}
/// `Hud.extractCrosshair` (first person, not hidden for spectators):
/// `attack` is `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and
/// `full` whether the full indicator shows for a target in reach.
/// `Hud.extractCrosshair`'s full attack indicator: at full strength on a
/// living, alive `crosshairPickEntity` (`target`) with a weapon slower than
/// `MIN_CROSSHAIR_ATTACK_SPEED` (`delay` is
/// `getCurrentItemAttackStrengthDelay`).
pub fn full_attack_indicator(scale: f32, delay: f32, target: Option<bool>) -> bool {
scale >= 1.0 && delay > 5.0 && target == Some(true)
}
/// `Hud.extractCrosshair` (first person, not hidden for spectators), every
/// sprite through the inverting `CROSSHAIR` pipeline: `attack` is
/// `getAttackStrengthScale(0)` in CROSSHAIR indicator mode and `full`
/// whether the full indicator shows ([`full_attack_indicator`]).
pub fn crosshair(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
crosshair_draws(w, h, attack, full)
.into_iter()
.map(crosshair_blend)
.collect()
}
fn crosshair_draws(w: i32, h: i32, attack: Option<f32>, full: bool) -> Vec<GuiDraw> {
let mut out = vec![sprite("hud/crosshair", (w - 15) / 2, (h - 15) / 2, 15, 15)];
if let Some(scale) = attack {
let (x, y) = (w / 2 - 8, h / 2 - 7 + 16);
@@ -760,6 +788,7 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
h,
region,
color,
blend,
} => {
// Effect sprites belong to the mob_effect atlas directory;
// the other blitSprite ids refer to GUI sprites.
@@ -781,6 +810,9 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra
r.v0 = v0;
}
batch.rect_uv(*x as f32, *y as f32, *w as f32, *h as f32, r, abgr(*color));
if *blend == Blend::Crosshair {
batch.invert_since(start);
}
}
GuiDraw::AtlasSprite {
sprite,
@@ -175,6 +175,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
h: 24,
region: None,
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
});
out.push(GuiDraw::Sprite {
sprite: Cow::Owned(format!("mob_effect/{}", e.id)),
@@ -184,6 +185,7 @@ pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec<GuiDraw> {
h: 18,
region: None,
color: white(alpha),
blend: crate::hud_layout::Blend::Textured,
});
}
out
@@ -492,6 +494,7 @@ pub fn boss_overlay(w: i32, h: i32, bars: &[BossBar], font: &Font) -> Vec<GuiDra
h: 5,
region: Some([182, 5, 0, 0]),
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
};
out.push(sprite(BOSS_COLORS[bar.color].to_owned()));
if bar.overlay != 0 {
@@ -532,6 +535,7 @@ pub fn jump_bar(w: i32, h: i32, cooldown: i32, scale: f32) -> Vec<GuiDraw> {
h: 5,
region,
color: crate::hud_layout::WHITE,
blend: crate::hud_layout::Blend::Textured,
};
let mut out = vec![sprite("hud/jump_bar_background", 182, None)];
if cooldown > 0 {
+116 -28
View File
@@ -10,6 +10,8 @@ use crate::hud::{HudBatch, Rect};
use glam::{EulerRot, Mat4, Vec2, Vec3};
use std::{collections::HashMap, f32::consts::PI};
mod depth;
/// `Lighting.DIFFUSE_LIGHT_0` and `DIFFUSE_LIGHT_1`.
fn diffuse_lights() -> (Vec3, Vec3) {
(
@@ -177,35 +179,19 @@ fn draw_quads(
rect: [f32; 4],
time: f32,
) {
// Back-face culling: front faces wind counter-clockwise on screen with y up.
let mut visible: Vec<(f32, usize)> = quads
.iter()
.enumerate()
.filter(|(_, q)| {
let p = q.pos.map(|v| Vec2::new(v.x, -v.y));
let area: f32 = (0..4)
.map(|i| {
let (a, b) = (p[i], p[(i + 1) % 4]);
a.x * b.y - b.x * a.y
})
.sum();
area > 0.0
})
.map(|(i, q)| (q.pos.iter().map(|v| v.z).sum::<f32>() / 4.0, i))
.collect();
// Far to near; the depth buffer of the item atlas, approximated per quad.
visible.sort_by(|a, b| a.0.total_cmp(&b.0));
for (_, i) in visible {
let q = &quads[i];
let points: [Point; 4] = std::array::from_fn(|k| Point {
p: Vec2::new(q.pos[k].x, q.pos[k].y),
uv: q.uv[k],
});
for face in depth::sort(quads) {
let q = &quads[face.quad];
let points: Vec<_> = face
.corners
.iter()
.map(|v| Point {
p: v.pos.truncate(),
uv: v.uv,
})
.collect();
let color = lit_color(q, lights);
for tri in [
[points[0], points[1], points[2]],
[points[0], points[2], points[3]],
] {
for i in 1..points.len().saturating_sub(1) {
let tri = [points[0], points[i], points[i + 1]];
let fan = clip_triangle(tri, rect);
if fan.len() < 3 {
continue;
@@ -275,6 +261,108 @@ pub fn draw_banner_result(
mod tests {
use super::*;
fn face(y0: f32, y1: f32, z: impl Fn(f32) -> f32, color: u32) -> ItemQuad {
ItemQuad {
pos: [(0.0, y0), (0.0, y1), (8.0, y1), (8.0, y0)].map(|(x, y)| Vec3::new(x, y, z(y))),
uv: [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [1.0, 0.0]],
normal: Vec3::Z,
color,
foil: Foil::None,
light_emission: 0,
}
}
// Sample the emitted triangles in draw order, using opaque test faces.
fn color_at(batch: &HudBatch, p: Vec2) -> Option<u32> {
batch
.vertices
.as_chunks::<3>()
.0
.iter()
.rev()
.find_map(|tri| {
let [a, b, c] = std::array::from_fn(|i| Vec2::from(tri[i].pos));
let area = (b - a).perp_dot(c - a);
if area.abs() < 1e-6 {
return None;
}
let u = (b - p).perp_dot(c - p) / area;
let v = (c - p).perp_dot(a - p) / area;
let w = 1.0 - u - v;
(u >= 0.0 && v >= 0.0 && w >= 0.0).then_some(tri[0].color)
})
}
#[test]
fn banner_cloth_occludes_the_support_at_the_top_edge() {
// The cloth is nearer where it overlaps the bar, although its
// average depth is farther away because it slopes along its height.
let bar = face(0.0, 1.0, |_| 0.0, 0xFF80_4000);
let cloth = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF);
let mut batch = HudBatch::new([320, 240]);
draw_quads(
&[bar, cloth],
(Vec3::Z, Vec3::Z),
&mut batch,
[0.0, 0.0, 16.0, 16.0],
0.0,
);
assert_eq!(color_at(&batch, Vec2::new(4.0, 0.5)), Some(u32::MAX));
}
#[test]
fn intersecting_faces_change_draw_order_at_their_intersection() {
let flat = face(0.0, 8.0, |_| 0.0, 0xFFFF_0000);
let tilted = face(0.0, 8.0, |y| y - 4.0, 0xFF00_00FF);
for quads in [[flat, tilted], [tilted, flat]] {
let mut batch = HudBatch::new([320, 240]);
draw_quads(
&quads,
(Vec3::Z, Vec3::Z),
&mut batch,
[0.0, 0.0, 16.0, 16.0],
0.0,
);
assert_eq!(
color_at(&batch, Vec2::new(4.0, 2.0)),
Some(lit_color(&flat, (Vec3::Z, Vec3::Z)))
);
assert_eq!(
color_at(&batch, Vec2::new(4.0, 6.0)),
Some(lit_color(&tilted, (Vec3::Z, Vec3::Z)))
);
// The cut must interpolate the texture along with the position.
for v in &batch.vertices {
assert!((v.uv[0] - v.pos[0] / 8.0).abs() < 1e-6);
assert!((v.uv[1] - v.pos[1] / 8.0).abs() < 1e-6);
}
}
}
#[test]
fn coplanar_pattern_layers_keep_submission_order() {
let base = face(0.0, 8.0, |y| 2.0 - y, 0xFFFF_FFFF);
let pattern = ItemQuad {
color: 0xFF00_00FF,
..base
};
let quads = [face(0.0, 1.0, |_| 0.0, 0xFF80_4000), base, pattern];
let mut batch = HudBatch::new([320, 240]);
draw_quads(
&quads,
(Vec3::Z, Vec3::Z),
&mut batch,
[0.0, 0.0, 16.0, 16.0],
0.0,
);
for y in [0.5, 6.0] {
assert_eq!(
color_at(&batch, Vec2::new(4.0, y)),
Some(lit_color(&quads[2], (Vec3::Z, Vec3::Z)))
);
}
}
#[test]
fn flat_lights_match_joml() {
// new Matrix4f().rotationY(-PI/8).rotateX(3PI/4).transformDirection(L0).
@@ -0,0 +1,119 @@
//! Back-to-front ordering for the orthographic GUI item view (near is +Z).
//! Whole-face average depths fail when a long, tilted face overlaps a short
//! one, such as a banner's cloth and support. Partition faces by their planes
//! instead, splitting intersecting faces with their UVs. Coplanar faces keep
//! submission order so banner/shield pattern layers still paint bottom first.
use super::super::ItemQuad;
use glam::{Vec3, Vec4};
#[derive(Clone, Copy)]
pub(super) struct Corner {
pub pos: Vec3,
pub uv: [f32; 2],
}
pub(super) struct Face {
pub quad: usize,
pub corners: Vec<Corner>,
}
const EPSILON: f32 = 1e-4;
fn split(face: Face, distances: &[f32]) -> (Face, Face) {
let mut back = Vec::new();
let mut front = Vec::new();
for i in 0..face.corners.len() {
let a = face.corners[i];
let b = face.corners[(i + 1) % face.corners.len()];
let da = distances[i];
let db = distances[(i + 1) % face.corners.len()];
if da <= EPSILON {
back.push(a);
}
if da >= -EPSILON {
front.push(a);
}
if (da < -EPSILON && db > EPSILON) || (da > EPSILON && db < -EPSILON) {
let t = da / (da - db);
let corner = Corner {
pos: a.pos.lerp(b.pos, t),
uv: std::array::from_fn(|k| a.uv[k] + (b.uv[k] - a.uv[k]) * t),
};
back.push(corner);
front.push(corner);
}
}
(
Face {
quad: face.quad,
corners: back,
},
Face {
quad: face.quad,
corners: front,
},
)
}
pub(super) fn sort(quads: &[ItemQuad]) -> Vec<Face> {
let mut planes = vec![Vec4::ZERO; quads.len()];
let faces: Vec<_> = quads
.iter()
.enumerate()
.filter_map(|(i, q)| {
let normal = (q.pos[2] - q.pos[0]).cross(q.pos[3] - q.pos[1]);
// Front faces wind counter-clockwise on screen with Y up.
if normal.z >= 0.0 {
return None;
}
let normal = -normal.normalize();
planes[i] = normal.extend(-normal.dot(q.pos[0]));
Some(Face {
quad: i,
corners: std::array::from_fn::<_, 4, _>(|k| Corner {
pos: q.pos[k],
uv: q.uv[k],
})
.to_vec(),
})
})
.collect();
let mut out = Vec::new();
// An explicit stack avoids recursion for models with many parallel faces.
let mut pending = vec![(faces, false)];
while let Some((faces, emit)) = pending.pop() {
if emit {
out.extend(faces);
continue;
}
let mut faces = faces.into_iter();
let Some(first) = faces.next() else { continue };
let plane = planes[first.quad];
let mut coplanar = vec![first];
let mut back = Vec::new();
let mut front = Vec::new();
for face in faces {
let distances: Vec<_> = face
.corners
.iter()
.map(|c| plane.dot(c.pos.extend(1.0)))
.collect();
let behind = distances.iter().any(|d| *d < -EPSILON);
let ahead = distances.iter().any(|d| *d > EPSILON);
match (behind, ahead) {
(false, false) => coplanar.push(face),
(true, false) => back.push(face),
(false, true) => front.push(face),
(true, true) => {
let (b, f) = split(face, &distances);
back.push(b);
front.push(f);
}
}
}
pending.push((front, false));
pending.push((coplanar, true));
pending.push((back, false));
}
out
}
+47 -2
View File
@@ -70,6 +70,8 @@ pub struct ItemInfo {
pub blocks_attacks: Option<BlocksAttacks>,
/// `weapon.disable_blocking_for_seconds` (axes).
pub disable_blocking_seconds: f32,
/// `weapon.item_damage_per_attack`, when the item is a weapon.
pub weapon_damage: Option<u32>,
/// `use_effects.speed_multiplier` (UseEffects.DEFAULT: 0.2).
pub use_speed: f32,
/// `glider` (elytra).
@@ -439,6 +441,11 @@ impl Items {
disable_blocking_seconds: c["minecraft:weapon"]["disable_blocking_for_seconds"]
.as_f64()
.unwrap_or(0.0) as f32,
weapon_damage: c["minecraft:weapon"].is_object().then(|| {
c["minecraft:weapon"]["item_damage_per_attack"]
.as_u64()
.unwrap_or(1) as u32
}),
equip_asset: c["minecraft:equippable"]["asset_id"]
.as_str()
.map(str::to_owned),
@@ -601,6 +608,7 @@ impl Items {
properties: &empty,
held: None,
killed_by_player: false,
explosion_radius: None,
};
ctx.evaluate(table, random)
}
@@ -662,7 +670,22 @@ impl Items {
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
) -> Vec<ItemStack> {
let drops = self.block_drops_raw(registry, state, held, random, sequences);
self.block_drops_exploded(registry, state, held, dynamic, random, sequences, None)
}
/// `block_drops_full` for a block an explosion destroys: `explosion`
/// is its radius when the explosion decays drops (`DESTROY_WITH_DECAY`).
#[allow(clippy::too_many_arguments)]
pub fn block_drops_exploded(
&self,
registry: &BlockRegistry,
state: BlockStateId,
held: Option<&ItemStack>,
dynamic: &[ItemStack],
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion: Option<f32>,
) -> Vec<ItemStack> {
let drops = self.block_drops_raw(registry, state, held, random, sequences, explosion);
if !drops.iter().any(|d| d.item.starts_with(DYNAMIC)) {
return drops;
}
@@ -684,6 +707,7 @@ impl Items {
held: Option<&ItemStack>,
random: &mut impl RandomSource,
sequences: Option<(&mut crate::random_sequences::RandomSequences, i64)>,
explosion_radius: Option<f32>,
) -> Vec<ItemStack> {
let Some(block) = registry.state(state) else {
return vec![];
@@ -713,6 +737,7 @@ impl Items {
properties: &block.properties,
held,
killed_by_player: false,
explosion_radius,
};
return ctx.evaluate(table, random);
}
@@ -722,6 +747,7 @@ impl Items {
properties: &block.properties,
held,
killed_by_player: false,
explosion_radius,
};
ctx.evaluate(table, random)
}
@@ -744,6 +770,7 @@ impl Items {
properties: &empty,
held,
killed_by_player,
explosion_radius: None,
};
ctx.evaluate(table, random)
}
@@ -775,6 +802,7 @@ impl Items {
properties: &block.properties,
held: None,
killed_by_player: false,
explosion_radius: None,
};
match table.get("random_sequence").and_then(Value::as_str) {
Some(sequence) => ctx.evaluate(table, sequences.get(sequence, seed)),
@@ -799,6 +827,7 @@ impl Items {
properties: &empty,
held,
killed_by_player,
explosion_radius: None,
};
ctx.evaluate(table, random)
}
@@ -820,6 +849,7 @@ impl Items {
properties: &empty,
held,
killed_by_player,
explosion_radius: None,
};
ctx.evaluate(table, random)
}
@@ -859,6 +889,8 @@ struct LootContext<'a> {
properties: &'a BTreeMap<String, String>,
held: Option<&'a ItemStack>,
killed_by_player: bool,
/// `LootContextParams.EXPLOSION_RADIUS`: an explosion that decays drops.
explosion_radius: Option<f32>,
}
impl LootContext<'_> {
/// Level of an enchantment on the tool / killer's weapon.
@@ -920,7 +952,10 @@ impl LootContext<'_> {
_ => return true,
};
match kind {
"minecraft:survives_explosion" => true,
// ExplosionCondition: 1 / radius under a decaying explosion.
"minecraft:survives_explosion" => self
.explosion_radius
.is_none_or(|r| random.next_float() <= 1.0 / r),
"minecraft:tool/can_silk_touch" => self.enchantment_level("minecraft:silk_touch") > 0,
"minecraft:tool/can_shear" => self.held.is_some_and(|h| &*h.item == "minecraft:shears"),
"minecraft:inverted" => !self.condition(&c["term"], random),
@@ -1205,6 +1240,15 @@ impl LootContext<'_> {
}
}
}
// ApplyExplosionDecay: each item survives with 1 / radius.
"minecraft:explosion_decay" => {
if let Some(radius) = self.explosion_radius {
let probability = 1.0 / radius;
stack.count = (0..stack.count)
.filter(|_| random.next_float() <= probability)
.count() as u32;
}
}
"minecraft:limit_count" => {
let limit = &f["limit"];
if let Some(min) = limit["min"].as_i64() {
@@ -1238,6 +1282,7 @@ mod tests {
properties: props,
held,
killed_by_player: block.is_empty(),
explosion_radius: None,
}
}
+16
View File
@@ -263,6 +263,22 @@ impl ChunkEncoder {
}
sections.push(encoded);
}
// A loaded chunk's block entities enter its maps in the save's order
// (ChunkAccess.pendingBlockEntities, then LevelChunk.blockEntities):
// keys that share a bucket keep that order. Others follow in scan order.
if let Some(order) = chunk.saved.as_ref().map(|s| &s.block_entity_order)
&& !order.is_empty()
{
let at = |e: &BlockEntityInfo| {
let pos = (
chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4),
i32::from(e.y),
chunk.z * 16 + i32::from(e.packed_xz as u8 & 15),
);
order.iter().position(|p| *p == pos).unwrap_or(usize::MAX)
};
entity_infos.sort_by_key(at);
}
java_hash_order(&mut entity_infos, |e| {
(
chunk.x * 16 + i32::from(e.packed_xz as u8 >> 4),
+3 -3
View File
@@ -219,7 +219,7 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type State = BlockStateId;
fn is_in_water(&mut self) -> Result<bool> {
Ok(false)
Ok(self.player.fluids.was_touching_water)
}
fn fall_distance(&self) -> f64 {
self.player.fall_distance
@@ -253,8 +253,8 @@ impl FallDamageWorld for MotionWorld<'_, '_, '_> {
}
impl LivingLandingWorld for MotionWorld<'_, '_, '_> {
fn update_fluid_interaction(&mut self) -> Result<bool> {
Ok(false)
} // dry scene
self.update_fluids()
}
fn is_server_level(&self) -> bool {
true
}
+8
View File
@@ -4,11 +4,13 @@
pub mod advancements;
pub mod ambience;
pub mod animate_tick;
pub mod arrows;
pub mod assets;
pub mod atlas_sources;
pub mod attack_strength;
pub mod attribute_updates;
pub mod audio;
pub mod auth;
pub mod auto_jump;
pub mod banner;
pub mod biome;
@@ -43,9 +45,12 @@ pub mod datapack;
pub mod debug_keys;
pub mod effects;
pub mod enchant;
pub mod end_crystal;
pub mod entities;
pub mod entity_nbt;
pub mod environment;
pub mod extras;
pub mod extras_hud;
pub mod fast_hash;
pub mod fastutil_order;
pub mod first_person;
@@ -85,6 +90,8 @@ pub mod logging;
pub mod menu;
pub mod merchant;
pub mod mesher;
pub mod minimap;
pub mod mipmap;
pub mod mobs;
pub mod models;
pub mod motion;
@@ -111,6 +118,7 @@ pub mod raid;
pub mod random_sequences;
pub mod recipe_book;
pub mod recipe_book_screen;
pub mod reconnect;
pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd;
+679
View File
@@ -0,0 +1,679 @@
//! The minimap extra (`docs/extras.md`): a 16x16 tile per loaded chunk with
//! each column's vanilla map colour (`MapColor`, as `MapItem.update` picks
//! it), height and water depth, and a 128x128 image composed from the tiles
//! around the player with the map item's height and water shading.
//!
//! Tiles are filled nearest first within a time budget and rescanned after
//! block changes; the image is recomposed only when the view moved or a tile
//! changed.
use crate::{
blocks::{BlockFacts, Fluid, MAP_COLORS},
chunk::{Chunk, MIN_Y, SECTIONS},
fast_hash::FxHashMap,
world::World,
};
use std::time::{Duration, Instant};
/// The image's side in texels.
pub const SIZE: usize = 128;
/// Marks a column the map cuts through (a wall at the player's height).
const WALL: u8 = 0x80;
/// Water's and lava's map colours (`MapColor.WATER`, `FIRE`).
const WATER: u8 = 12;
const LAVA: u8 = 4;
/// A tile whose chunk changed is rescanned at most this often.
const RESCAN: Duration = Duration::from_secs(1);
/// What the map shows of each column.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Layer {
/// The top block, as map items show it.
Surface,
/// Underground, in the Nether or under a roof: the floor below this
/// height (the player's head), and walls cut at it.
Below(i32),
}
/// What the scan needs of each block state.
pub struct Palette {
/// Map colour id, 0 for none.
color: Vec<u8>,
/// 0 none, 1 water, 2 lava; | 4 for air; | 8 when sturdy on top.
flags: Vec<u8>,
}
const FLUID: u8 = 3;
const AIR: u8 = 4;
const STURDY_TOP: u8 = 8;
impl Palette {
pub fn new(facts: &BlockFacts) -> Self {
let mut color = Vec::with_capacity(facts.states.len());
let mut flags = Vec::with_capacity(facts.states.len());
for (i, f) in facts.states.iter().enumerate() {
color.push(f.map_color);
let mut b = match f.fluid {
Fluid::None => 0,
Fluid::Water => 1,
Fluid::Lava => 2,
};
if facts.is_air(horizon_world::registry::BlockStateId(i as u32)) {
b |= AIR;
}
// isFaceSturdy(UP, FULL): Direction.UP's ordinal is 1.
if f.sturdy_full >> 1 & 1 != 0 {
b |= STURDY_TOP;
}
flags.push(b);
}
Self { color, flags }
}
/// A palette from (colour, flags) per state id (tests).
#[cfg(test)]
fn from_parts(parts: &[(u8, u8)]) -> Self {
Self {
color: parts.iter().map(|p| p.0).collect(),
flags: parts.iter().map(|p| p.1).collect(),
}
}
#[inline]
fn get(&self, id: u16) -> (u8, u8) {
let i = usize::from(id);
(
self.color.get(i).copied().unwrap_or(0),
self.flags.get(i).copied().unwrap_or(AIR),
)
}
}
#[derive(Clone)]
struct Tile {
/// Map colour id per column (`z * 16 + x`), `| WALL` for cut walls.
color: [u8; 256],
height: [i16; 256],
/// Water depth below the surface, for the map's water shading.
depth: [u8; 256],
revision: u64,
layer: Layer,
scanned: Instant,
}
/// `MapItem.update` for one column: the first block with a map colour
/// going down, the fluid's colour over a fluid unless the block is sturdy on
/// top (`getCorrectStateForFluidBlock`), and the fluid's depth.
fn scan_column(
chunk: &Chunk,
palette: &Palette,
x: i32,
z: i32,
top: i32,
layer: Layer,
) -> (u8, i16, u8) {
let mut y = top;
if let Layer::Below(head) = layer {
let (color, flags) = palette.get(chunk.get(x, head, z));
if flags & AIR == 0 && color != 0 && flags & FLUID == 0 {
return (color | WALL, head as i16, 0);
}
}
while y > MIN_Y {
let (mut color, flags) = palette.get(chunk.get(x, y, z));
if color == 0 {
y -= 1;
continue;
}
let mut depth = 0u8;
let fluid = flags & FLUID;
if fluid != 0 {
let mut below = y - 1;
while below > MIN_Y && palette.get(chunk.get(x, below, z)).1 & FLUID != 0 {
depth = depth.saturating_add(1);
below -= 1;
}
depth = depth.saturating_add(1);
if flags & STURDY_TOP == 0 {
color = if fluid == 2 { LAVA } else { WATER };
}
}
return (color, y as i16, depth);
}
(0, MIN_Y as i16, 0)
}
/// The highest block of a chunk worth scanning from.
fn top_of(chunk: &Chunk, air: u16, layer: Layer) -> i32 {
let surface = (0..SECTIONS)
.rev()
.find(|&s| {
chunk
.sections
.get(s)
.is_some_and(|sec| !sec.is_uniform(air))
})
.map_or(MIN_Y, |s| MIN_Y + s as i32 * 16 + 15);
match layer {
Layer::Surface => surface,
Layer::Below(head) => surface.min(head),
}
}
fn scan_tile(chunk: &Chunk, palette: &Palette, air: u16, layer: Layer, revision: u64) -> Tile {
let top = top_of(chunk, air, layer);
let mut tile = Tile {
color: [0; 256],
height: [MIN_Y as i16; 256],
depth: [0; 256],
revision,
layer,
scanned: Instant::now(),
};
for z in 0..16 {
for x in 0..16 {
let (c, h, d) = scan_column(chunk, palette, x, z, top, layer);
let i = (z * 16 + x) as usize;
tile.color[i] = c;
tile.height[i] = h;
tile.depth[i] = d;
}
}
tile
}
/// Where the map looks from and how.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
pub x: f64,
pub z: f64,
/// The player's yaw in degrees (0 faces south).
pub yaw: f32,
/// The map turns with the player (forward is up), or north is up.
pub rotate: bool,
pub blocks_per_pixel: f32,
pub round: bool,
}
impl View {
/// Whether the image for `self` would look different from `other`'s.
fn differs(&self, other: &View) -> bool {
let moved = ((self.x - other.x).abs().max((self.z - other.z).abs()) as f32)
>= self.blocks_per_pixel / 4.0;
let turned = self.rotate && (self.yaw - other.yaw).abs() >= 0.5;
moved
|| turned
|| self.rotate != other.rotate
|| self.round != other.round
|| self.blocks_per_pixel != other.blocks_per_pixel
}
/// The world's right and forward directions as the map's x and up.
fn axes(&self) -> ([f64; 2], [f64; 2]) {
if !self.rotate {
return ([1.0, 0.0], [0.0, -1.0]);
}
let (s, c) = f64::from(self.yaw).to_radians().sin_cos();
([-c, -s], [-s, c])
}
/// Where north is on the map's rim, as a unit direction (x right, y down).
pub fn north(&self) -> (f32, f32) {
let (r, f) = self.axes();
// The direction (0, -1) in the map's (right, -forward) basis.
(-r[1] as f32, f[1] as f32)
}
}
/// `MapColor.getColorFromPackedId` as RGBA.
fn packed_rgba(id: u8, brightness: u8) -> [u8; 4] {
let id = usize::from(id);
if id == 0 || id >= MAP_COLORS.len() {
return [0; 4];
}
let modifier = [180u32, 220, 255, 135][usize::from(brightness & 3)];
let col = MAP_COLORS[id];
let ch = |s: u32| ((col >> s & 255) * modifier / 255) as u8;
[ch(16), ch(8), ch(0), 255]
}
/// The map item's shading at scale 1: brighter facing a lower north
/// neighbour, darker facing a higher one, dithered; water by depth.
fn brightness(color: u8, height: i16, north: Option<i16>, depth: u8, parity: i32) -> u8 {
if color & WALL != 0 {
return 3;
}
let parity = f64::from(parity & 1);
if color == WATER {
let diff = f64::from(depth) * 0.1 + parity * 0.2;
return if diff < 0.5 {
2
} else if diff > 0.9 {
0
} else {
1
};
}
let north = north.unwrap_or(height);
let diff = f64::from(height - north) * 4.0 / 5.0 + (parity - 0.5) * 0.4;
if diff > 0.6 {
2
} else if diff < -0.6 {
0
} else {
1
}
}
const UNKNOWN: [u8; 4] = [20, 20, 20, 200];
const BORDER: [u8; 4] = [10, 10, 10, 230];
#[derive(Default)]
pub struct Minimap {
tiles: FxHashMap<(i32, i32), Tile>,
palette: Option<Palette>,
composed: Option<View>,
/// Tiles changed since the image was composed.
changed: bool,
/// The composed image, `SIZE` x `SIZE` RGBA.
pub image: Vec<u8>,
}
impl Minimap {
/// Forget everything (a new world or dimension, or the minimap turned off).
pub fn clear(&mut self) {
let palette = self.palette.take();
*self = Self {
palette,
..Self::default()
};
}
/// Fill and refresh tiles around chunk `center` within `radius` chunks,
/// nearest first, until `budget` is spent. Returns the tiles scanned.
pub fn update(
&mut self,
world: &World,
facts: &BlockFacts,
center: (i32, i32),
radius: i32,
layer: Layer,
budget: Duration,
) -> usize {
let palette = self.palette.get_or_insert_with(|| Palette::new(facts));
let started = Instant::now();
let air = world.air.0 as u16;
// Tiles of unloaded or distant chunks go.
self.tiles.retain(|k, _| {
(k.0 - center.0).abs() <= radius + 2
&& (k.1 - center.1).abs() <= radius + 2
&& world.chunks.contains_key(k)
});
let mut scanned = 0;
for ring in 0..=radius {
for (dx, dz) in ring_offsets(ring) {
let key = (center.0 + dx, center.1 + dz);
let Some(chunk) = world.chunks.get(&key) else {
continue;
};
let stale = match self.tiles.get(&key) {
None => true,
Some(t) if t.layer != layer => true,
Some(t) => t.revision != world.revision && t.scanned.elapsed() >= RESCAN,
};
if !stale {
continue;
}
let tile = scan_tile(chunk, palette, air, layer, world.revision);
if self.tiles.get(&key).is_none_or(|t| {
t.color != tile.color || t.height != tile.height || t.depth != tile.depth
}) {
self.changed = true;
}
self.tiles.insert(key, tile);
scanned += 1;
if started.elapsed() >= budget {
return scanned;
}
}
}
scanned
}
/// Recompose the image if the view or the tiles changed; true when it did.
pub fn compose(&mut self, view: View) -> bool {
if !self.changed
&& self.composed.is_some_and(|c| !view.differs(&c))
&& !self.image.is_empty()
{
return false;
}
self.changed = false;
self.composed = Some(view);
self.image.resize(SIZE * SIZE * 4, 0);
let (r, f) = view.axes();
let bpp = f64::from(view.blocks_per_pixel);
let half = SIZE as f64 / 2.0;
let mut cached: Option<((i32, i32), &Tile)> = None;
let mut column = |x: i32, z: i32| -> Option<(u8, i16, u8)> {
let key = (x >> 4, z >> 4);
let tile = match cached {
Some((k, t)) if k == key => t,
_ => {
let t = self.tiles.get(&key)?;
cached = Some((key, t));
t
}
};
let i = ((z & 15) * 16 + (x & 15)) as usize;
Some((tile.color[i], tile.height[i], tile.depth[i]))
};
for j in 0..SIZE {
for i in 0..SIZE {
let (u, v) = (i as f64 + 0.5 - half, j as f64 + 0.5 - half);
let o = (j * SIZE + i) * 4;
let edge = if view.round {
let d = (u * u + v * v).sqrt();
if d > half {
self.image[o..o + 4].copy_from_slice(&[0; 4]);
continue;
}
d > half - 1.5
} else {
i == 0 || j == 0 || i == SIZE - 1 || j == SIZE - 1
};
if edge {
self.image[o..o + 4].copy_from_slice(&BORDER);
continue;
}
let wx = view.x + bpp * (u * r[0] - v * f[0]);
let wz = view.z + bpp * (u * r[1] - v * f[1]);
let (x, z) = (wx.floor() as i32, wz.floor() as i32);
let rgba = match column(x, z) {
Some((color, height, depth)) if color & !WALL != 0 => {
let north = column(x, z - 1).filter(|c| c.0 & !WALL != 0).map(|c| c.1);
let b = brightness(color, height, north, depth, x + z);
packed_rgba(color & !WALL, b)
}
_ => UNKNOWN,
};
self.image[o..o + 4].copy_from_slice(&rgba);
}
}
true
}
pub fn tile_count(&self) -> usize {
self.tiles.len()
}
}
/// Chunk offsets at Chebyshev distance `ring`.
fn ring_offsets(ring: i32) -> impl Iterator<Item = (i32, i32)> {
(-ring..=ring).flat_map(move |dz| {
(-ring..=ring)
.filter(move |&dx| dx.abs() == ring || dz.abs() == ring)
.map(move |dx| (dx, dz))
})
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
// States: 0 air, 1 grass (colour 1), 2 stone (11), 3 water, 4 glass (no
// colour), 5 waterlogged slab (sturdy on top? no), 6 lava.
fn palette() -> Palette {
Palette::from_parts(&[
(0, AIR),
(1, STURDY_TOP),
(11, STURDY_TOP),
(WATER, 1),
(0, 0),
(11, 1),
(LAVA, 2),
])
}
fn chunk(columns: &[(i32, i32, &[(i32, u16)])]) -> Chunk {
let mut c = Chunk::empty(0, 0);
for &(x, z, blocks) in columns {
for &(y, id) in blocks {
c.set(x, y, z, id);
}
}
c
}
#[test]
fn columns_take_the_first_coloured_block_and_fluids_over_it() {
let p = palette();
let c = chunk(&[
(0, 0, &[(60, 2), (61, 1)]),
// Glass has no map colour: the grass under it shows.
(1, 0, &[(61, 1), (62, 4)]),
// Three water over stone.
(2, 0, &[(60, 2), (61, 3), (62, 3), (63, 3)]),
(3, 0, &[(70, 6)]),
]);
let top = top_of(&c, 0, Layer::Surface);
assert_eq!(top, 79);
assert_eq!(scan_column(&c, &p, 0, 0, top, Layer::Surface), (1, 61, 0));
assert_eq!(scan_column(&c, &p, 1, 0, top, Layer::Surface), (1, 61, 0));
assert_eq!(
scan_column(&c, &p, 2, 0, top, Layer::Surface),
(WATER, 63, 3)
);
assert_eq!(
scan_column(&c, &p, 3, 0, top, Layer::Surface),
(LAVA, 70, 1)
);
assert_eq!(scan_column(&c, &p, 4, 0, top, Layer::Surface).0, 0);
}
#[test]
fn a_waterlogged_block_not_sturdy_on_top_shows_water() {
let p = palette();
let c = chunk(&[(0, 0, &[(60, 2), (61, 5)])]);
assert_eq!(
scan_column(&c, &p, 0, 0, 70, Layer::Surface),
(WATER, 61, 1)
);
}
#[test]
fn below_a_height_shows_the_floor_and_cuts_walls() {
let p = palette();
// A cave: stone everywhere from 0 to 20, air at 10 and 11 in column 0.
let mut blocks: Vec<(i32, u16)> = (0..=20).map(|y| (y, 2)).collect();
let solid = blocks.clone();
blocks.retain(|&(y, _)| y != 10 && y != 11);
let c = chunk(&[(0, 0, &blocks), (1, 0, &solid)]);
let layer = Layer::Below(11);
let top = top_of(&c, 0, layer);
assert_eq!(top, 11);
assert_eq!(scan_column(&c, &p, 0, 0, top, layer), (11, 9, 0));
assert_eq!(scan_column(&c, &p, 1, 0, top, layer), (11 | WALL, 11, 0));
// The surface view sees the roof.
assert_eq!(scan_column(&c, &p, 0, 0, 31, Layer::Surface), (11, 20, 0));
}
#[test]
fn shading_follows_the_map_item() {
// Higher than the north neighbour: bright; lower: dark; level: normal.
assert_eq!(brightness(1, 65, Some(64), 0, 0), 2);
assert_eq!(brightness(1, 63, Some(64), 0, 1), 0);
assert_eq!(brightness(1, 64, Some(64), 0, 0), 1);
assert_eq!(brightness(1, 64, Some(64), 0, 1), 1);
// Shallow water is bright, deep water dark.
assert_eq!(brightness(WATER, 62, None, 1, 0), 2);
assert_eq!(brightness(WATER, 62, None, 10, 0), 0);
assert_eq!(brightness(1 | WALL, 0, None, 0, 0), 3);
assert_eq!(packed_rgba(1, 2), [127, 178, 56, 255]);
assert_eq!(packed_rgba(0, 2), [0; 4]);
}
fn world_with(chunks: Vec<Chunk>) -> World {
let mut w = World::new(horizon_world::registry::BlockStateId(0), 0);
for c in chunks {
w.chunks.insert((c.x, c.z), Arc::new(c));
}
w
}
fn grass_chunk(x: i32, z: i32) -> Chunk {
let mut c = Chunk::empty(x, z);
for bz in 0..16 {
for bx in 0..16 {
c.set(bx, 64, bz, 1);
}
}
c
}
#[test]
fn tiles_fill_nearest_first_and_follow_changes() {
let mut map = Minimap {
palette: Some(palette()),
..Default::default()
};
let facts = BlockFacts {
states: Vec::new(),
air: horizon_world::registry::BlockStateId(0),
};
let mut world = world_with(
(-2..=2)
.flat_map(|x| (-2..=2).map(move |z| grass_chunk(x, z)))
.collect(),
);
// A zero budget still scans one tile: the player's own chunk.
assert_eq!(
map.update(&world, &facts, (0, 0), 2, Layer::Surface, Duration::ZERO),
1
);
assert!(map.tiles.contains_key(&(0, 0)));
let n = map.update(
&world,
&facts,
(0, 0),
2,
Layer::Surface,
Duration::from_secs(1),
);
assert_eq!(n, 24);
assert_eq!(map.tile_count(), 25);
// Nothing changed: nothing to scan.
assert_eq!(
map.update(
&world,
&facts,
(0, 0),
2,
Layer::Surface,
Duration::from_secs(1)
),
0
);
// A changed world is rescanned once the tiles are old enough.
world
.set(0, 70, 0, horizon_world::registry::BlockStateId(2))
.unwrap();
assert_eq!(
map.update(
&world,
&facts,
(0, 0),
2,
Layer::Surface,
Duration::from_secs(1)
),
0
);
for t in map.tiles.values_mut() {
t.scanned -= RESCAN;
}
assert_eq!(
map.update(
&world,
&facts,
(0, 0),
2,
Layer::Surface,
Duration::from_secs(1)
),
25
);
assert_eq!(map.tiles[&(0, 0)].color[0], 11);
// A new layer rescans everything; unloaded chunks drop out.
world.chunks.remove(&(2, 2));
let n = map.update(
&world,
&facts,
(0, 0),
2,
Layer::Below(70),
Duration::from_secs(1),
);
assert_eq!(n, 24);
assert!(!map.tiles.contains_key(&(2, 2)));
}
#[test]
fn the_image_is_north_up_or_turns_with_the_player() {
let mut map = Minimap {
palette: Some(palette()),
..Default::default()
};
let facts = BlockFacts {
states: Vec::new(),
air: horizon_world::registry::BlockStateId(0),
};
// Grass everywhere, one stone block 10 blocks north of the player.
let mut world = world_with(
(-4..=4)
.flat_map(|x| (-4..=4).map(move |z| grass_chunk(x, z)))
.collect(),
);
world
.set(0, 64, -10, horizon_world::registry::BlockStateId(2))
.unwrap();
map.update(
&world,
&facts,
(0, 0),
4,
Layer::Surface,
Duration::from_secs(1),
);
let pixel = |map: &Minimap, i: usize, j: usize| {
let o = (j * SIZE + i) * 4;
[map.image[o], map.image[o + 1], map.image[o + 2]]
};
let stone = [96, 96, 96];
let mut view = View {
x: 0.0,
z: 0.0,
yaw: 0.0,
rotate: false,
blocks_per_pixel: 1.0,
round: false,
};
assert!(map.compose(view));
assert!(!map.compose(view), "the same view is not recomposed");
// North up: the stone is 10 pixels above the centre.
assert_eq!(pixel(&map, 64, 54), stone);
// Turning with the player facing east (yaw -90): north is to the left.
view.rotate = true;
view.yaw = -90.0;
assert!(map.compose(view));
assert_eq!(pixel(&map, 54, 63), stone);
let (nx, ny) = view.north();
assert!((nx + 1.0).abs() < 1e-5 && ny.abs() < 1e-5, "{nx} {ny}");
// Facing north, north is up.
view.yaw = 180.0;
map.compose(view);
assert_eq!(pixel(&map, 64, 54), stone);
// Round maps are transparent in the corners, framed at the edge.
view.round = true;
map.compose(view);
assert_eq!(map.image[3], 0);
assert_eq!(&map.image[(64 * SIZE) * 4..(64 * SIZE) * 4 + 4], &BORDER);
// A small move recomposes only once it is visible.
view.x += 0.1;
assert!(!map.compose(view));
view.x += 0.2;
assert!(map.compose(view));
}
#[test]
fn rings_cover_each_offset_once() {
let mut seen = std::collections::HashSet::new();
for r in 0..=3 {
for o in ring_offsets(r) {
assert!(seen.insert(o));
}
}
assert_eq!(seen.len(), 49);
}
}
+334
View File
@@ -0,0 +1,334 @@
//! `MipmapGenerator`: the mip levels of a sprite. Cutout textures keep the
//! alpha-test coverage of their base level at every level
//! (`scaleAlphaToCoverage`), so thin cutout edges (cactus sides, leaves,
//! flowers) don't erode into gaps with distance; colours average in linear
//! light (`ARGB.meanLinear`).
/// `MipmapStrategy`, from the texture's `.mcmeta` `texture` section.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Strategy {
#[default]
Auto,
Mean,
Cutout,
StrictCutout,
DarkCutout,
}
impl Strategy {
pub fn parse(name: &str) -> Option<Self> {
Some(match name {
"auto" => Self::Auto,
"mean" => Self::Mean,
"cutout" => Self::Cutout,
"strict_cutout" => Self::StrictCutout,
"dark_cutout" => Self::DarkCutout,
_ => return None,
})
}
}
/// How a sprite's mips are made: its `.mcmeta` `texture` section, whether
/// it has a fully transparent pixel and whether it is an `item/` sprite.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Settings {
pub strategy: Strategy,
pub alpha_cutoff_bias: f32,
pub has_transparent: bool,
pub item: bool,
}
/// A square or rectangular RGBA8 image, rows top to bottom.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub pixels: Vec<[u8; 4]>,
}
impl Image {
fn get(&self, x: u32, y: u32) -> [u8; 4] {
self.pixels[(x + y * self.width) as usize]
}
fn set(&mut self, x: u32, y: u32, p: [u8; 4]) {
self.pixels[(x + y * self.width) as usize] = p;
}
}
/// `ARGB.SRGB_TO_LINEAR`: an sRGB channel in linear light, 0 to 1023.
fn srgb_to_linear() -> &'static [u16; 256] {
static TABLE: std::sync::OnceLock<[u16; 256]> = std::sync::OnceLock::new();
TABLE.get_or_init(|| {
std::array::from_fn(|i| {
let x = i as f32 / 255.0;
let linear = if x >= 0.04045 {
((f64::from(x) + 0.055) / 1.055).powf(2.4) as f32
} else {
x / 12.92
};
java_round(linear * 1023.0) as u16
})
})
}
/// `ARGB.LINEAR_TO_SRGB`: 1024 linear steps back to sRGB.
fn linear_to_srgb() -> &'static [u8; 1024] {
static TABLE: std::sync::OnceLock<[u8; 1024]> = std::sync::OnceLock::new();
TABLE.get_or_init(|| {
std::array::from_fn(|i| {
let x = i as f32 / 1023.0;
let srgb = if x >= 0.003_130_8 {
(1.055 * f64::from(x).powf(0.416_666_666_666_666_7) - 0.055) as f32
} else {
12.92 * x
};
java_round(srgb * 255.0) as u8
})
})
}
/// `Math.round(float)`, bit for bit.
fn java_round(a: f32) -> i32 {
let bits = a.to_bits() as i32;
let biased_exp = (bits & 0x7F80_0000) >> 23;
let shift = (22 + 127) - biased_exp;
if shift & -32 == 0 {
let mut r = bits & 0x007F_FFFF | 0x0080_0000;
if bits < 0 {
r = -r;
}
((r >> shift) + 1) >> 1
} else {
a as i32
}
}
/// `ARGB.alphaFloat`.
fn alpha_float(p: [u8; 4]) -> f32 {
f32::from(p[3]) / 255.0
}
/// `MipmapGenerator.alphaTestCoverage`: the share of the image (bilinearly
/// subsampled 4x4 per texel) whose scaled alpha passes `alpha_ref`.
fn alpha_test_coverage(image: &Image, alpha_ref: f32, alpha_scale: f32) -> f32 {
let (width, height) = (image.width as i32, image.height as i32);
let mut coverage = 0.0f32;
let a =
|x: i32, y: i32| (alpha_float(image.get(x as u32, y as u32)) * alpha_scale).clamp(0.0, 1.0);
for y in 0..height - 1 {
for x in 0..width - 1 {
let (a00, a10, a01, a11) = (a(x, y), a(x + 1, y), a(x, y + 1), a(x + 1, y + 1));
let mut texel = 0.0f32;
for sy in 0..4 {
let fy = (sy as f32 + 0.5) / 4.0;
for sx in 0..4 {
let fx = (sx as f32 + 0.5) / 4.0;
let alpha = a00 * (1.0 - fx) * (1.0 - fy)
+ a10 * fx * (1.0 - fy)
+ a01 * (1.0 - fx) * fy
+ a11 * fx * fy;
if alpha > alpha_ref {
texel += 1.0;
}
}
}
coverage += texel / 16.0;
}
}
coverage / ((width - 1) * (height - 1)) as f32
}
/// `MipmapGenerator.scaleAlphaToCoverage`: five bisection steps for the
/// alpha scale whose coverage is nearest `desired`, then every alpha scaled
/// and biased.
fn scale_alpha_to_coverage(image: &mut Image, desired: f32, alpha_ref: f32, bias: f32) {
let (mut min_scale, mut max_scale) = (0.0f32, 4.0f32);
let mut scale = 1.0f32;
let mut best_scale = 1.0f32;
let mut best_error = f32::MAX;
for _ in 0..5 {
let current = alpha_test_coverage(image, alpha_ref, scale);
let error = (current - desired).abs();
if error < best_error {
best_error = error;
best_scale = scale;
}
if current < desired {
min_scale = scale;
} else if current > desired {
max_scale = scale;
} else {
break;
}
scale = (min_scale + max_scale) * 0.5;
}
for p in &mut image.pixels {
let alpha = (alpha_float(*p) * best_scale + bias + 0.025).clamp(0.0, 1.0);
p[3] = (alpha * 255.0).floor() as u8;
}
}
/// `TextureUtil.solidify`: every transparent pixel takes the colour of the
/// nearest opaque one (breadth first, keeping its zero alpha).
fn solidify(image: &mut Image) {
let (width, height) = (image.width as i32, image.height as i32);
let n = image.pixels.len();
let mut nearest = vec![[0u8; 4]; n];
let mut distance = vec![i32::MAX; n];
let mut queue = std::collections::VecDeque::new();
for x in 0..width {
for y in 0..height {
let i = (x + y * width) as usize;
let p = image.pixels[i];
if p[3] != 0 {
distance[i] = 0;
nearest[i] = p;
queue.push_back(i);
}
}
}
while let Some(i) = queue.pop_front() {
let (x, y) = (i as i32 % width, i as i32 / width);
for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
let (nx, ny) = (x + dx, y + dy);
if nx >= 0 && ny >= 0 && nx < width && ny < height {
let j = (nx + ny * width) as usize;
if distance[j] > distance[i] + 1 {
distance[j] = distance[i] + 1;
nearest[j] = nearest[i];
queue.push_back(j);
}
}
}
}
for (i, p) in image.pixels.iter_mut().enumerate() {
if p[3] == 0 {
let c = nearest[i];
*p = [c[0], c[1], c[2], 0];
}
}
}
/// `TextureUtil.fillEmptyAreasWithDarkColor`: transparent pixels take three
/// quarters of the darkest visible colour.
fn fill_empty_dark(image: &mut Image) {
let mut darkest = [255u8; 4];
let mut min = i32::MAX;
for x in 0..image.width {
for y in 0..image.height {
let p = image.get(x, y);
if p[3] != 0 {
let brightness = i32::from(p[0]) + i32::from(p[1]) + i32::from(p[2]);
if brightness < min {
min = brightness;
darkest = p;
}
}
}
}
let dark = |c: u8| (3 * i32::from(c) / 4) as u8;
let fill = [dark(darkest[0]), dark(darkest[1]), dark(darkest[2]), 0];
for p in &mut image.pixels {
if p[3] == 0 {
*p = fill;
}
}
}
/// `ARGB.meanLinear`.
fn mean_linear(c: [[u8; 4]; 4]) -> [u8; 4] {
let (to_linear, to_srgb) = (srgb_to_linear(), linear_to_srgb());
let channel = |k: usize| {
let sum: u32 = c.iter().map(|p| u32::from(to_linear[p[k] as usize])).sum();
to_srgb[(sum / 4) as usize]
};
let alpha = c.iter().map(|p| u32::from(p[3])).sum::<u32>() / 4;
[channel(0), channel(1), channel(2), alpha as u8]
}
/// `MipmapGenerator.darkenedAlphaBlend`: the visible pixels' mean in linear
/// light, transparent ones counting as black.
fn darkened_alpha_blend(c: [[u8; 4]; 4]) -> [u8; 4] {
let to_linear = srgb_to_linear();
let linear = |v: u8| f32::from(to_linear[v as usize]) / 1023.0;
let mut total = [0.0f32; 4];
for p in c.iter().filter(|p| p[3] != 0) {
total[3] += linear(p[3]);
for k in 0..3 {
total[k] += linear(p[k]);
}
}
let to_srgb = |v: f32| linear_to_srgb()[(v / 4.0 * 1023.0).floor() as usize];
[
to_srgb(total[0]),
to_srgb(total[1]),
to_srgb(total[2]),
to_srgb(total[3]),
]
}
/// `MipmapGenerator.generateMipLevels` from the base image (`levels` mips
/// below it): `has_transparent` is `Transparency.hasTransparent` (a pixel
/// with zero alpha), `item` whether the sprite is under `item/` (its base
/// is left as is).
pub fn generate(
mut base: Image,
levels: u32,
strategy: Strategy,
alpha_cutoff_bias: f32,
has_transparent: bool,
item: bool,
) -> Vec<Image> {
let strategy = match strategy {
Strategy::Auto if has_transparent => Strategy::Cutout,
Strategy::Auto => Strategy::Mean,
s => s,
};
if !item {
match strategy {
Strategy::Cutout | Strategy::StrictCutout => solidify(&mut base),
Strategy::DarkCutout => fill_empty_dark(&mut base),
_ => {}
}
}
let cutout = matches!(
strategy,
Strategy::Cutout | Strategy::StrictCutout | Strategy::DarkCutout
);
let alpha_ref = if strategy == Strategy::StrictCutout {
0.3
} else {
0.5
};
let coverage = if cutout {
alpha_test_coverage(&base, alpha_ref, 1.0)
} else {
0.0
};
let mut out = vec![base];
for _ in 1..=levels {
let last = out.last().expect("the base level");
let (width, height) = (last.width >> 1, last.height >> 1);
let mut data = Image {
width,
height,
pixels: vec![[0; 4]; (width * height) as usize],
};
for x in 0..width {
for y in 0..height {
let c = [
last.get(x * 2, y * 2),
last.get(x * 2 + 1, y * 2),
last.get(x * 2, y * 2 + 1),
last.get(x * 2 + 1, y * 2 + 1),
];
let p = if strategy == Strategy::DarkCutout {
darkened_alpha_blend(c)
} else {
mean_linear(c)
};
data.set(x, y, p);
}
}
if cutout {
scale_alpha_to_coverage(&mut data, coverage, alpha_ref, alpha_cutoff_bias);
}
out.push(data);
}
out
}
+34 -3
View File
@@ -45,6 +45,7 @@ pub mod nether;
pub mod path;
pub mod phantom;
pub mod piglin;
pub mod rabbit;
pub mod raider;
pub mod ravager;
pub mod render;
@@ -492,6 +493,8 @@ pub enum Who {
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DamageKind {
PlayerAttack,
/// `mace_smash`: a mace hit after a fall (the player attack tags too).
MaceSmash,
MobAttack,
Arrow,
Thrown,
@@ -541,6 +544,14 @@ impl Damage {
from: Some(from),
}
}
/// `DamageSources.mace`: a player's smash attack.
pub fn mace(from: [f64; 3]) -> Self {
Self {
kind: DamageKind::MaceSmash,
attacker: Some(Who::Player),
from: Some(from),
}
}
pub fn mob(id: u32, from: [f64; 3]) -> Self {
Self {
kind: DamageKind::MobAttack,
@@ -808,6 +819,11 @@ pub struct Mob {
/// Events a mob tick asks the game to act on.
#[derive(Clone, Debug)]
pub enum MobEvent {
/// Rabbit entity event 1, sent only when a ground jump actually happens.
RabbitHop {
mob: u32,
at: [f64; 3],
},
Sound(&'static str, [f64; 3], f32, f32),
/// `ChestBlockEntity.startOpen` / `stopOpen` by a copper golem: the
/// chest's opener count goes up or down (interaction range 3).
@@ -1328,6 +1344,7 @@ pub struct MobWorld<'a> {
pub world: &'a World,
pub registry: &'a horizon_world::registry::BlockRegistry,
pub facts: &'a BlockFacts,
pub movement: &'a horizon_world::movement_properties::BoundMovementProperties,
pub collision: &'a BlockCollisionRegistry<'a>,
pub data: &'a MobData,
pub player: Option<PlayerView>,
@@ -1518,6 +1535,16 @@ impl Mob {
.fold((0.0, 0.0), |(a, t), (x, y)| (a + x, t + y))
}
pub fn damage(&mut self, amount: f32, source: Damage) -> bool {
self.damage_with(amount, source, None)
}
/// `damage` by a source with a weapon: `armor_effectiveness` runs the
/// weapon's armor-effectiveness enchantments (breach) over the armor fraction.
pub fn damage_with(
&mut self,
amount: f32,
source: Damage,
armor_effectiveness: Option<&mut dyn FnMut(f32) -> f32>,
) -> bool {
raider::note_hurt(self);
if !self.alive() || self.removed || self.invulnerable_flag {
return false;
@@ -1535,7 +1562,11 @@ impl Mob {
let armor = self.kind.armor + worn;
let toughness = 2.0 + (self.kind.armor_toughness + worn_toughness) / 4.0;
let effective = (armor - amount / toughness).clamp(armor * 0.2, 20.0);
amount *= 1.0 - effective / 25.0;
let mut fraction = effective / 25.0;
if let Some(modify) = armor_effectiveness {
fraction = modify(fraction).clamp(0.0, 1.0);
}
amount *= 1.0 - fraction;
}
// CombatRules.getDamageAfterMagicAbsorb: enchantment protection.
let epf = gear::protection(self, source.kind);
@@ -1570,7 +1601,7 @@ impl Mob {
let (dx, dz) = source.from.map_or((0.0, 0.0), |f| {
(f[0] - self.position.x, f[2] - self.position.z)
});
self.knockback(0.4, dx, dz);
self.knockback(f64::from(0.4f32), dx, dz);
}
ai::after_hurt(self, &source);
if self.health <= 0.0 {
@@ -1597,7 +1628,7 @@ impl Mob {
}
/// LivingEntity.knockback(power, xd, zd) towards the negative direction.
pub fn knockback(&mut self, power: f64, mut xd: f64, mut zd: f64) {
let power = power * (1.0 - self.kind.knockback_resistance);
let power = power * (1.0 - self.attrs.knockback_resistance);
if power <= 0.0 {
return;
}
+17 -4
View File
@@ -171,7 +171,12 @@ pub fn register(m: &mut Mob) {
Family::Undead => undead::register(m),
Family::Hostile => hostile::register(m),
Family::Aquatic => aquatic::register(m),
Family::Generic => generic(m),
Family::Generic => {
generic(m);
if m.species() == Species::Rabbit {
super::rabbit::register(m);
}
}
Family::Inert => {}
Family::Witch => super::witch::register(m),
Family::Tame if m.species() == Species::Cat => super::tame::register_cat(m),
@@ -271,8 +276,9 @@ fn generic(m: &mut Mob) {
m.ai.targets.add(2, NearestTarget::player(true));
} else {
g.add(0, Float);
g.add(1, Panic::new(1.25));
g.add(5, Stroll::avoiding_water(1.0));
let rabbit = m.kind.species == Species::Rabbit;
g.add(1, Panic::new(if rabbit { 2.2 } else { 1.25 }));
g.add(5, Stroll::avoiding_water(if rabbit { 0.6 } else { 1.0 }));
g.add(6, LookAtPlayer::new(6.0));
g.add(7, RandomLookAround::default());
}
@@ -352,6 +358,9 @@ pub fn tick(
}
super::warden::pre_tick(m, w, events);
base_tick(m, w, events);
if m.species() == Species::Rabbit {
super::rabbit::base_tick(m);
}
if m.death_time >= super::creaking::death_limit(m) {
// Creaking.tickDeath: a heart's creaking crumbles away.
if super::creaking::is_creaking(m) && super::creaking::tearing_down(m) {
@@ -362,6 +371,9 @@ pub fn tick(
if !m.no_ai {
ai_step(m, w, level_random, events);
}
if m.species() == Species::Rabbit {
super::rabbit::post_tick(m);
}
// Mob.tickHeadTurn -> BodyRotationControl.clientTick (a frozen
// creaking's waits).
if m.alive() && !(super::creaking::is_creaking(m) && !super::creaking::can_move(m)) {
@@ -605,7 +617,7 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
m.ai.xxa = 0.0;
m.ai.zza = 0.0;
}
m.handle_jumping();
m.handle_jumping(w);
let input = Vec3::new(
f64::from(m.ai.xxa),
f64::from(m.ai.yya),
@@ -849,6 +861,7 @@ fn server_ai_step(
}
fn custom_server_ai_step(m: &mut Mob, cx: &mut Cx) {
match m.species() {
Species::Rabbit => super::rabbit::server_ai_step(m),
Species::Sheep => {}
Species::Zombie
| Species::Husk
@@ -132,6 +132,9 @@ impl Mob {
}
/// MoveControl.tick (and the flying / smooth-swimming variants).
pub fn move_control_tick(&mut self, w: &MobWorld, events: &mut Vec<super::MobEvent>) {
if self.species() == super::Species::Rabbit {
return super::rabbit::move_control(self, w);
}
let attr_speed = self.movement_speed();
match self.ai.mov.kind {
MoveKind::Custom => super::ai::custom_move_control(self, w, events),
@@ -376,6 +379,9 @@ impl Mob {
}
/// JumpControl.tick.
pub fn jump_control_tick(&mut self) {
if self.species() == super::Species::Rabbit {
return super::rabbit::jump_control(self);
}
self.ai.jumping = self.ai.jump;
self.ai.jump = false;
}
@@ -117,6 +117,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage) -> bool {
let direct = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MaceSmash
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
+4 -1
View File
@@ -291,7 +291,10 @@ pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.hurt_time == 10
&& !moving
&& let Some((d, _)) = m.last_damage
&& matches!(d.kind, DamageKind::PlayerAttack | DamageKind::MobAttack)
&& matches!(
d.kind,
DamageKind::PlayerAttack | DamageKind::MaceSmash | DamageKind::MobAttack
)
{
let from = [m.position.x, m.position.y, m.position.z];
match d.attacker {
+13
View File
@@ -142,6 +142,19 @@ impl Goal for Swell {
m.extra.counter = dir;
}
}
/// Creeper.tick on a client of a server: the synced fuse direction
/// (DATA_SWELL_DIR, DATA_IS_IGNITED) swells the creeper the renderer draws;
/// the server explodes it.
pub fn creeper_client_tick(m: &mut Mob) {
if !m.alive() {
return;
}
m.previous_swell = m.swell;
if m.extra.flag {
m.extra.counter = 1;
}
m.swell = (m.swell + m.extra.counter).clamp(0, 30);
}
/// Creeper.tick: advance the fuse and explode at 30.
pub fn creeper_tick(m: &mut Mob, events: &mut Vec<MobEvent>) {
if !m.alive() {
+1 -1
View File
@@ -541,7 +541,7 @@ fn shoot_crossbow(m: &mut Mob, who: Who, cx: &mut Cx) {
start,
Some(Who::Mob(m.id)),
);
p.bonus = super::gear::arrow_bonus(m);
p.set_bonus(super::gear::arrow_bonus(m));
// rangedAttackUncertainty at normal difficulty: 14 - 2 * 4.
p.shoot(
&mut crate::projectiles::own_random(m),
+7 -3
View File
@@ -723,7 +723,7 @@ impl Mob {
}
}
/// The jump part of LivingEntity.aiStep.
pub fn handle_jumping(&mut self) {
pub fn handle_jumping(&mut self, w: &MobWorld) {
if self.ai.jumping && self.affected_by_fluids() {
let (fluid_height, in_water_with_height) = if self.fluids.in_lava {
(self.fluids.lava, false)
@@ -739,7 +739,7 @@ impl Mob {
if (self.on_ground || in_water_with_height && fluid_height <= threshold)
&& self.ai.no_jump_delay == 0
{
self.jump_from_ground();
self.jump_from_ground(w);
self.ai.no_jump_delay = 10;
}
} else {
@@ -756,7 +756,11 @@ impl Mob {
fn jump_in_liquid(&mut self) {
self.velocity.y += if self.ai.nav.can_float { 0.04 } else { 0.3 };
}
pub fn jump_from_ground(&mut self) {
pub fn jump_from_ground(&mut self, w: &MobWorld) {
if self.species() == super::Species::Rabbit {
super::rabbit::jump(self, w);
return;
}
if matches!(
self.species(),
super::Species::Slime | super::Species::MagmaCube | super::Species::SulfurCube
+486
View File
@@ -0,0 +1,486 @@
//! Rabbit hopping controls and the clocks consumed by `RabbitModel`.
use super::{Mob, MobEvent, MobWorld, control::Operation};
use horizon_core::{
geometry::{Vec3, trig},
random::RandomSource,
};
// Rabbit's transient state in Extra (none of these clocks are saved).
const JUMP_TICKS: usize = 0;
const JUMP_DURATION: usize = 1;
const MOVE_DELAY: usize = 2;
const IDLE_TIMEOUT: usize = 3;
// Client counters start only when the actual ground jump emits entity event 1.
const CLIENT_JUMP_TICKS: usize = 4;
const CLIENT_JUMP_DURATION: usize = 5;
pub fn register(m: &mut Mob) {
m.ai.mov.kind = super::control::MoveKind::Custom;
m.ai.nav.can_float = true;
m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180;
}
/// Rabbit.baseTick: the idle timeout branch precedes the hop clock branch.
pub fn base_tick(m: &mut Mob) {
let age = m.age as f32;
let leashed = m.extra.leash.is_some();
if m.extra.ints[IDLE_TIMEOUT] <= 0 && !leashed && !m.no_ai {
m.extra.ints[IDLE_TIMEOUT] = m.random.next_int_bound(40).unwrap_or(0) + 180;
m.anim.states[1].start(age);
} else if m.extra.ints[CLIENT_JUMP_TICKS] > 0 {
m.anim.states[0].start_if_stopped(age);
m.anim.states[1].stop();
} else {
m.extra.ints[IDLE_TIMEOUT] -= 1;
m.anim.states[0].stop();
}
if leashed {
m.anim.states[1].stop();
}
}
fn start_jumping(m: &mut Mob) {
m.ai.jumping = true;
m.extra.ints[JUMP_DURATION] = 15;
m.extra.ints[JUMP_TICKS] = 0;
let pitch = ((m.random.next_float() - m.random.next_float()) * 0.2 + 1.0) * 0.8;
if !m.silent {
m.outbox.push(MobEvent::Sound(
"entity.rabbit.jump",
[m.position.x, m.position.y, m.position.z],
1.0,
pitch,
));
}
}
/// Rabbit.customServerAiStep: start a hop toward the current path waypoint.
pub fn server_ai_step(m: &mut Mob) {
// RabbitMoveControl.setWantedPosition applies the water override before landing checks.
if m.fluids.in_water && m.ai.mov.speed_modifier > 0.0 {
m.ai.mov.speed_modifier = 1.5;
}
if m.extra.ints[MOVE_DELAY] > 0 {
m.extra.ints[MOVE_DELAY] -= 1;
}
if m.on_ground {
if !m.extra.flag {
m.ai.jumping = false;
m.extra.ints[MOVE_DELAY] = if m.ai.mov.speed_modifier < 2.2 { 10 } else { 3 };
}
if !m.ai.jump && m.ai.mov.has_wanted() && m.extra.ints[MOVE_DELAY] == 0 {
let mut at = m.ai.mov.wanted;
if let Some(path) = m.ai.nav.path.as_ref().filter(|p| !p.is_done()) {
let p = path.entity_pos_at(path.next, m.width());
at = [p.x, p.y, p.z];
}
m.yaw = trig::atan2_degrees(at[2] - m.position.z, at[0] - m.position.x) - 90.0;
start_jumping(m);
}
}
m.extra.flag = m.on_ground;
}
/// RabbitMoveControl.tick: wait on the ground and restore the last wanted speed in flight.
pub fn move_control(m: &mut Mob, w: &MobWorld) {
prepare_move(m);
m.ground_move_tick(w, m.movement_speed());
}
fn prepare_move(m: &mut Mob) {
if m.ai.mov.speed_modifier > 0.0 {
m.extra.vector[0] = if m.fluids.in_water {
1.5
} else {
m.ai.mov.speed_modifier
};
}
if m.on_ground && !m.ai.jumping && !m.ai.jump {
m.ai.mov.speed_modifier = 0.0;
m.set_speed(0.0);
} else if m.ai.mov.has_wanted() || m.ai.mov.operation == Operation::Jumping {
m.ai.mov.speed_modifier = if m.fluids.in_water {
1.5
} else {
m.extra.vector[0]
};
}
}
/// RabbitJumpControl.tick: explicit jump requests do not wait for the landing cooldown.
pub fn jump_control(m: &mut Mob) {
if m.ai.jump {
start_jumping(m);
m.ai.jump = false;
}
}
/// Rabbit.aiStep runs after the living physics; the fifteenth tick still renders the hop.
pub fn post_tick(m: &mut Mob) {
for (ticks, duration) in [
(JUMP_TICKS, JUMP_DURATION),
(CLIENT_JUMP_TICKS, CLIENT_JUMP_DURATION),
] {
if m.extra.ints[ticks] != m.extra.ints[duration] {
m.extra.ints[ticks] += 1;
} else if m.extra.ints[duration] != 0 {
m.extra.ints[ticks] = 0;
m.extra.ints[duration] = 0;
if ticks == JUMP_TICKS {
m.ai.jumping = false;
}
}
}
}
fn jump_scale(m: &Mob) -> f32 {
let step =
m.ai.nav
.path
.as_ref()
.filter(|p| !p.is_done())
.is_some_and(|p| f64::from(p.next_node().y) > m.position.y + 0.5);
let high =
m.horizontal_collision || step || m.ai.jumping && m.ai.mov.wanted[1] > m.position.y + 0.5;
let base = if high {
0.5
} else if m.ai.mov.speed_modifier <= 0.6 {
0.2
} else {
0.3
};
base / 0.42
}
/// Rabbit.jumpFromGround: ordinary small hops, larger hops toward raised terrain.
pub fn jump(m: &mut Mob, w: &MobWorld) {
let power = jump_power(m, block_jump_factor(m, w));
apply_jump(m, power);
}
fn jump_power(m: &Mob, block_factor: f32) -> f32 {
let boost = m
.extra
.effects
.iter()
.find(|e| e.0 == "minecraft:jump_boost")
.map_or(0.0, |e| 0.1 * (e.2 + 1) as f32);
m.attrs.jump_strength as f32 * jump_scale(m) * block_factor + boost
}
fn apply_jump(m: &mut Mob, power: f32) {
if power > 1.0e-5 {
m.velocity.y = f64::from(power).max(m.velocity.y);
}
if m.ai.mov.speed_modifier > 0.0
&& m.velocity.x * m.velocity.x + m.velocity.z * m.velocity.z < 0.01
{
m.move_relative(
0.1,
Vec3::new(0.0, if m.is_baby() { 0.5 } else { 1.5 }, 1.0),
);
}
hop_event(m);
m.outbox.push(MobEvent::RabbitHop {
mob: m.id,
at: [m.position.x, m.position.y, m.position.z],
});
}
/// Rabbit.handleEntityEvent(1): reset the counter without starting the clock early.
pub fn hop_event(m: &mut Mob) {
m.extra.ints[CLIENT_JUMP_DURATION] = 15;
m.extra.ints[CLIENT_JUMP_TICKS] = 0;
}
fn block_jump_factor(m: &Mob, w: &MobWorld) -> f32 {
let properties = w.movement;
let current = w.world.block(
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let below = m.on_pos(0.500_001);
// shortcut: use mobs' existing on_pos until they track supporting blocks like the player.
let lower = w.world.block(below[0], below[1], below[2]);
let current = properties
.get(current)
.expect("validated movement registry")
.coefficients
.jump_factor;
let lower = properties
.get(lower)
.expect("validated movement registry")
.coefficients
.jump_factor;
if current == 1.0 { lower } else { current }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mobs::{
Anim, Brain, Flags, MobType, Part, Species,
anim::{self, Poses},
body_anim,
keyframes::Animation,
};
use serde_json::json;
use std::{collections::HashMap, sync::Arc};
fn rabbit() -> Mob {
let model = Arc::new(Part::parse(
"root",
&json!({"children": {"head": {}, "left_hind_foot": {}}}),
));
let kind = Arc::new(MobType {
id: "minecraft:rabbit".into(),
species: Species::Rabbit,
width: 0.4,
height: 0.5,
eye_height: 0.4,
category: "creature".into(),
max_health: 3.0,
speed: 0.3,
flying_speed: 0.4,
attack_damage: 0.0,
attack_knockback: 0.0,
follow_range: 16.0,
step_height: 0.6,
armor: 0.0,
armor_toughness: 0.0,
knockback_resistance: 0.0,
jump_strength: 0.42,
attributes: Arc::default(),
gravity: 0.08,
safe_fall_distance: 3.0,
fall_damage_multiplier: 1.0,
water_efficiency: 0.0,
water_slowdown: 0.8,
air_speed: 0.02,
baby_scale: 0.5,
head_rot_speed: 10.0,
max_head_x_rot: 40.0,
max_head_y_rot: 75.0,
ambient_interval: 120,
flags: Flags {
animal: true,
..Default::default()
},
model,
layers: HashMap::new(),
texture: String::new(),
brain: Brain::Passive,
anim: Anim::Rabbit,
sounds: [""; 3],
step_sound: None,
food: Arc::default(),
tempt: Arc::default(),
});
Mob::new(1, kind, Vec3::ZERO, 0.0)
}
fn near(a: f64, b: f64) {
assert!((a - b).abs() < 1.0e-6, "{a} != {b}");
}
#[test]
fn summoned_age_selects_the_baby_model_and_texture() {
let mut template = rabbit();
let kind = Arc::make_mut(&mut template.kind);
kind.texture = "entity/rabbit/rabbit_brown".into();
kind.layers
.insert("rabbit_baby#main".into(), kind.model.clone());
let types = HashMap::from([(kind.id.clone(), template.kind.clone())]);
for (age, baby) in [(-24000, true), (-1, true), (0, false), (6000, false)] {
let (tag, _) = horizon_world::nbt::parse_snbt(&format!(
"{{id:\"minecraft:rabbit\",Pos:[0.0d,0.0d,0.0d],Age:{age}}}"
))
.unwrap();
let m = crate::entity_nbt::mob_from_nbt(&tag, &types, 2).unwrap();
assert_eq!(m.extra.age, age);
assert_eq!(m.is_baby(), baby);
assert_eq!(
crate::mobs::render::body(&m),
if baby {
(
"rabbit_baby#main".into(),
"entity/rabbit/rabbit_brown_baby".into(),
)
} else {
("rabbit#main".into(), "entity/rabbit/rabbit_brown".into())
}
);
}
}
#[test]
fn landing_waits_then_real_hop_clock_moves_the_model() {
let mut m = rabbit();
m.on_ground = true;
m.ai.mov.set_wanted(0.0, 0.0, 5.0, 0.6);
server_ai_step(&mut m);
assert_eq!(m.extra.ints[MOVE_DELAY], 10);
assert!(!m.ai.jumping);
for _ in 0..9 {
server_ai_step(&mut m);
}
assert!(!m.ai.jumping);
server_ai_step(&mut m);
assert!(m.ai.jumping);
assert_eq!(m.extra.ints[JUMP_DURATION], 15);
assert_eq!(m.anim.states[0].started, None);
apply_jump(&mut m, 0.2);
post_tick(&mut m);
m.age = 1;
base_tick(&mut m);
assert_eq!(m.anim.states[0].started, Some(1.0));
let curve = Animation::parse(&json!({"length": 0.75, "looping": true,
"bones": {"left_hind_foot": [{"target": "rotation", "keyframes": [[0,[0,0,0],[0,0,0],"linear"],[0.75,[1,0,0],[1,0,0],"linear"]]}]}}));
let animations = HashMap::from([("RabbitAnimation.HOP".into(), curve)]);
let mut poses = Poses::new(&m.kind.model);
let state = anim::state(&m, 0.5);
body_anim::rabbit(
&mut poses,
&state,
&m.anim.states[0],
&m.anim.states[1],
&animations,
);
assert!(poses.get("left_hind_foot")[3] > 0.0);
for _ in 1..15 {
post_tick(&mut m);
}
assert_eq!(m.extra.ints[JUMP_TICKS], 15);
assert!(m.ai.jumping);
post_tick(&mut m);
base_tick(&mut m);
assert!(!m.ai.jumping);
assert_eq!(m.anim.states[0].started, None);
}
#[test]
fn panic_and_explicit_requests_use_their_own_hop_timing() {
let mut m = rabbit();
m.on_ground = true;
m.ai.mov.set_wanted(0.0, 0.0, 5.0, 2.2);
server_ai_step(&mut m);
assert_eq!(m.extra.ints[MOVE_DELAY], 3);
m.ai.jump = true;
m.jump_control_tick();
assert!(m.ai.jumping);
assert!(!m.ai.jump);
assert_eq!(m.extra.ints[MOVE_DELAY], 3);
m.jump_control_tick();
assert!(m.ai.jumping);
}
#[test]
fn a_new_hop_preserves_a_running_clock_until_the_counter_finishes() {
let mut m = rabbit();
m.anim.states[0].start(4.0);
m.extra.ints[CLIENT_JUMP_TICKS] = 8;
hop_event(&mut m);
assert_eq!(m.anim.states[0].started, Some(4.0));
assert_eq!(m.extra.ints[CLIENT_JUMP_TICKS], 0);
assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 15);
post_tick(&mut m);
m.age = 12;
base_tick(&mut m);
assert_eq!(m.anim.states[0].started, Some(4.0));
assert!(m.outbox.is_empty());
}
#[test]
fn deep_water_jump_requests_do_not_start_a_client_hop() {
let mut m = rabbit();
m.fluids.in_water = true;
m.fluids.water = 1.0;
m.ai.jump = true;
jump_control(&mut m);
assert!(m.ai.jumping);
assert_eq!(m.extra.ints[JUMP_DURATION], 15);
post_tick(&mut m);
base_tick(&mut m);
assert_eq!(m.extra.ints[JUMP_TICKS], 1);
assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 0);
assert!(m.anim.states[0].started.is_none());
assert!(
!m.outbox
.iter()
.any(|e| matches!(e, MobEvent::RabbitHop { .. }))
);
hop_event(&mut m);
post_tick(&mut m);
base_tick(&mut m);
assert!(m.anim.states[0].started.is_some());
}
#[test]
fn grounded_movement_waits_and_water_uses_its_hop_speed() {
let mut m = rabbit();
m.on_ground = true;
m.ai.mov.set_wanted(0.0, 0.0, 5.0, 0.6);
prepare_move(&mut m);
assert_eq!(m.ai.mov.speed_modifier, 0.0);
assert_eq!(m.ai.zza, 0.0);
m.ai.jumping = true;
prepare_move(&mut m);
assert_eq!(m.ai.mov.speed_modifier, 0.6);
m.fluids.in_water = true;
prepare_move(&mut m);
assert_eq!(m.ai.mov.speed_modifier, 1.5);
assert_eq!(m.extra.vector[0], 1.5);
assert!(m.ai.nav.can_float);
m.extra.flag = false;
m.ai.mov.set_wanted(0.0, 0.0, 5.0, 2.2);
server_ai_step(&mut m);
assert_eq!(m.ai.mov.speed_modifier, 1.5);
assert_eq!(m.extra.ints[MOVE_DELAY], 10);
}
#[test]
fn jump_impulse_scales_strength_terrain_boost_and_baby_kick() {
let mut m = rabbit();
m.ai.mov.speed_modifier = 0.6;
near(f64::from(jump_power(&m, 1.0)), 0.2);
m.ai.mov.speed_modifier = 2.2;
near(f64::from(jump_power(&m, 1.0)), 0.3);
m.horizontal_collision = true;
near(f64::from(jump_power(&m, 1.0)), 0.5);
m.attrs.jump_strength = 0.84;
m.extra.effects.push(("minecraft:jump_boost", 100, 1));
near(f64::from(jump_power(&m, 0.5)), 0.7);
apply_jump(&mut m, 0.2);
near(m.velocity.z, 0.1 / 3.25_f64.sqrt());
near(m.velocity.y, 0.2 + 0.15 / 3.25_f64.sqrt());
m.extra.age = -100;
m.velocity = Vec3::ZERO;
apply_jump(&mut m, 0.2);
near(m.velocity.z, 0.1 / 1.25_f64.sqrt());
near(m.velocity.y, 0.2 + 0.05 / 1.25_f64.sqrt());
assert_eq!(m.extra.ints[CLIENT_JUMP_DURATION], 15);
}
#[test]
fn idle_timeout_hop_priority_no_ai_and_leash_follow_tick_order() {
let mut m = rabbit();
m.age = 7;
m.extra.ints[IDLE_TIMEOUT] = 0;
m.extra.ints[CLIENT_JUMP_TICKS] = 2;
base_tick(&mut m);
assert_eq!(m.anim.states[1].started, Some(7.0));
assert!(m.anim.states[0].started.is_none());
base_tick(&mut m);
assert_eq!(m.anim.states[0].started, Some(7.0));
assert!(m.anim.states[1].started.is_none());
m.extra.ints[CLIENT_JUMP_TICKS] = 0;
m.extra.ints[IDLE_TIMEOUT] = 0;
m.no_ai = true;
base_tick(&mut m);
assert_eq!(m.extra.ints[IDLE_TIMEOUT], -1);
assert!(m.anim.states[1].started.is_none());
m.no_ai = false;
base_tick(&mut m);
assert!(m.anim.states[1].started.is_some());
m.extra.leash = Some(super::super::leash::Holder::Knot([0, 0, 0]));
base_tick(&mut m);
assert!(m.anim.states[1].started.is_none());
}
}
+4
View File
@@ -169,6 +169,10 @@ pub fn body(m: &Mob) -> (String, String) {
"frog#main".into(),
format!("entity/frog/frog_{}", climate(m)),
),
S::Rabbit => (
baby_or(m, "rabbit#main", "rabbit_baby#main"),
b(&m.kind.texture),
),
S::Pig => {
let model = if baby {
"pig_baby#main".into()
@@ -289,6 +289,7 @@ pub fn accepts_damage(m: &mut Mob, source: &Damage, amount: f32) -> bool {
let immune = matches!(
source.kind,
DamageKind::PlayerAttack
| DamageKind::MaceSmash
| DamageKind::MobAttack
| DamageKind::Arrow
| DamageKind::Thrown
+1 -1
View File
@@ -755,7 +755,7 @@ pub fn perform_ranged_attack(m: &mut Mob, who: Who, cx: &mut Cx, power: f32) {
start,
Some(Who::Mob(m.id)),
);
p.bonus = super::gear::arrow_bonus(m);
p.set_bonus(super::gear::arrow_bonus(m));
p.shoot(
&mut arrow_random,
[xd, yd + dist * 0.2, zd],
+56 -6
View File
@@ -43,6 +43,9 @@ use std::{
sync::Arc,
};
mod fluids;
pub use fluids::{FluidResources, LAVA, PlayerFluids, WATER};
pub struct MotionResources {
pub attributes: Arc<Catalog>,
pub blocks: BoundMovementProperties,
@@ -50,6 +53,7 @@ pub struct MotionResources {
pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources,
pub fluids: FluidResources,
}
impl MotionResources {
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
@@ -86,6 +90,7 @@ impl MotionResources {
Ok(Self {
landing: crate::landing::load(root, &properties)?,
health: crate::health::HealthResources::load(root)?,
fluids: FluidResources::load(root, assets)?,
attributes,
blocks: properties.bind(&MovementTags {
fences: tag("minecraft:fences")?,
@@ -143,6 +148,28 @@ pub enum MotionEvent {
InsidePortal {
pos: BlockPos,
},
/// `ServerPlayer.checkFallDamage` after a mace smash: block particles
/// from the landing block, more the further the fall.
SmashLanding {
state: BlockStateId,
position: BlockPos,
fall_distance: f64,
},
/// `Entity.doWaterSplashEffect`: the player's splash (or high-speed
/// splash) sound at its position...
Splash {
high_speed: bool,
volume: f32,
pitch: f32,
},
/// ...its BUBBLE (else SPLASH) particles...
SplashParticle {
bubble: bool,
position: Vec3,
velocity: Vec3,
},
/// ...and the SPLASH game event.
SplashEvent,
}
pub struct PlayerMotion {
pub position: Vec3,
@@ -200,9 +227,14 @@ pub struct PlayerMotion {
pub events: Vec<MotionEvent>,
pub attributes: LiveAttributes<Box<dyn FnMut() -> i32>>,
pub impulse: ImpulseContext,
/// `ServerPlayer.spawnExtraParticlesOnFall`: a mace smash on a grounded
/// target makes the next landing throw up the block below.
pub spawn_extra_particles_on_fall: bool,
pub health: crate::health::PlayerHealth,
/// Status effects and armor protection seen by movement and damage.
pub status: crate::effects::StatusFlags,
/// Water and lava around the player (`Entity.fluidInteraction`).
pub fluids: PlayerFluids,
/// `Entity.isInPowderSnow` / `wasInPowderSnow`.
pub in_powder_snow: bool,
pub was_in_powder_snow: bool,
@@ -259,6 +291,7 @@ impl PlayerMotion {
health: crate::health::PlayerHealth::new(&resources.health, &mut attributes)?,
status: crate::effects::StatusFlags::default(),
impulse: ImpulseContext::default(),
spawn_extra_particles_on_fall: false,
position,
velocity: Vec3::ZERO,
ground: GroundState::default(),
@@ -302,6 +335,7 @@ impl PlayerMotion {
sync_position: false,
events: Vec::new(),
attributes,
fluids: PlayerFluids::default(),
in_powder_snow: false,
was_in_powder_snow: false,
ticks_frozen: 0,
@@ -580,6 +614,7 @@ impl MotionWorld<'_, '_, '_> {
// Entity.baseTick
self.player.was_in_powder_snow = self.player.in_powder_snow;
self.player.in_powder_snow = false;
self.fluid_base_tick()?;
self.player.old_position = self.player.position;
if self.player.jump_trigger_time > 0 {
self.player.jump_trigger_time -= 1;
@@ -1323,15 +1358,21 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
self.player.fall_distance
}
fn fall_reset_clip(&mut self, from: Vec3, to: Vec3) -> Result<bool> {
// Every fluid in this controlled scene is empty. Tagged reset blocks use
// a full block in ClipContext.FALLDAMAGE_RESETTING, not their collider.
// ClipContext.Block.FALLDAMAGE_RESETTING: tagged reset blocks are a full
// block, not their collider; ClipContext.Fluid.WATER: the water's shape.
// Both shapes are queried for every visited block (the water's first
// query fixes its cached shape), either one hitting ends the ray.
let hit = traverse_blocks(from, to, 1_000_000, |p| {
let water = match self.water_clip(from, to, p) {
Ok(hit) => hit,
Err(e) => return Some(Err(e)),
};
let name = &self.assets.registry.state(self.block(p)).unwrap().name;
(self.resources.fall_reset.contains(name)
&& VoxelShape::block().clip(from, to, p).is_some())
.then_some(())
let reset = self.resources.fall_reset.contains(name)
&& VoxelShape::block().clip(from, to, p).is_some();
(water || reset).then_some(Ok(()))
})?;
Ok(hit.is_some())
hit.transpose().map(|h| h.is_some())
}
fn reset_fall_distance(&mut self) -> Result<()> {
self.player.fall_distance = 0.0;
@@ -1385,6 +1426,15 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
state: BlockStateId,
position: BlockPos,
) -> Result<()> {
if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
{
self.player.events.push(MotionEvent::SmashLanding {
state,
position,
fall_distance: self.player.fall_distance,
});
self.player.spawn_extra_particles_on_fall = false;
}
self.player.events.push(MotionEvent::Landing {
dy,
grounded,
+336
View File
@@ -0,0 +1,336 @@
//! The player's fluid immersion over the resident scene: `Entity.updateFluidInteraction`
//! (water, waterlogged blocks, bubble columns and lava, with their currents), the
//! water-entry splash and the fall resets that hinge on touching water.
use super::*;
use horizon_world::{
entity_fluid::{
CurrentTarget, EntityFluidInteraction, FluidInteractionWorld, FluidMembership,
FluidSections, FluidTagId,
},
entity_fluid_tick::{self, EntityFluidTickWorld},
fluid::{FluidHeightWorld, FluidKind, FluidState, FluidStateTable},
fluid_flow::{FluidFlowWorld, flow_at},
fluid_shape::FluidShapeCache,
water_splash::{self, SplashParticle, WaterSplashWorld},
};
use std::sync::Mutex;
/// `FluidTags.WATER` and `FluidTags.LAVA`, the fluids with a current.
pub const WATER: FluidTagId = FluidTagId(0);
pub const LAVA: FluidTagId = FluidTagId(1);
/// Per-state fluid facts the player's immersion and fall-reset rays read.
pub struct FluidResources {
states: FluidStateTable,
/// `isFaceSturdy(FULL)` per `Direction` (bit = ordinal).
sturdy: Vec<u8>,
/// `#minecraft:blocks_fluid_flow` membership.
blocks_flow: Vec<bool>,
/// `IceBlock` and its subclasses.
ice: Vec<bool>,
/// `FlowingFluid.shapes`: the shape of the first query of each fluid
/// state, kept for the whole process like the registered fluid's map.
pub shapes: Mutex<FluidShapeCache>,
}
impl FluidResources {
pub fn load(root: &Path, assets: &Assets) -> Result<Self> {
let facts = crate::blocks::BlockFacts::load(root, assets.registry)?;
Ok(Self {
states: FluidStateTable::new(assets.registry)?,
sturdy: facts.states.iter().map(|s| s.sturdy_full).collect(),
blocks_flow: facts
.states
.iter()
.map(|s| assets.blocks_fluid_flow.contains(&*s.name))
.collect(),
ice: facts
.states
.iter()
.map(|s| s.has_class("IceBlock"))
.collect(),
shapes: Mutex::new(FluidShapeCache::default()),
})
}
pub fn fluid(&self, state: BlockStateId) -> FluidState {
self.states.get(state).unwrap_or(FluidState::EMPTY)
}
/// `BlockState.isFaceSturdy(FULL)` on that face.
pub fn sturdy(&self, state: BlockStateId, d: Direction) -> bool {
self.sturdy
.get(state.0 as usize)
.is_some_and(|s| s & 1 << d as u8 != 0)
}
/// `#minecraft:blocks_fluid_flow` membership.
pub fn blocks_flow(&self, state: BlockStateId) -> bool {
self.blocks_flow
.get(state.0 as usize)
.copied()
.unwrap_or(false)
}
/// `IceBlock` or one of its subclasses.
pub fn ice(&self, state: BlockStateId) -> bool {
self.ice.get(state.0 as usize).copied().unwrap_or(false)
}
}
/// The player's `EntityFluidInteraction` and the water flags around it.
pub struct PlayerFluids {
pub interaction: EntityFluidInteraction,
/// `Entity.wasTouchingWater` (`isInWater`).
pub was_touching_water: bool,
/// `Entity.wasEyeInWater`.
pub was_eye_in_water: bool,
/// `Entity.firstTick`: no splash, and no lava, until the first base tick ends.
pub first_tick: bool,
/// The dimension's `FAST_LAVA` (the Nether), set by the game.
pub fast_lava: bool,
}
impl Default for PlayerFluids {
fn default() -> Self {
Self {
interaction: EntityFluidInteraction::new([WATER, LAVA]),
was_touching_water: false,
was_eye_in_water: false,
first_tick: true,
fast_lava: false,
}
}
}
fn is_tagged(kind: FluidKind, tag: FluidTagId) -> bool {
if tag == WATER {
matches!(kind, FluidKind::Water | FluidKind::FlowingWater)
} else {
matches!(kind, FluidKind::Lava | FluidKind::FlowingLava)
}
}
impl PlayerMotion {
pub fn fluid_height(&self, tag: FluidTagId) -> f64 {
self.fluids.interaction.fluid_height(&Membership, tag)
}
pub fn is_eye_in_fluid(&self, tag: FluidTagId) -> bool {
self.fluids.interaction.is_eye_in_fluid(&Membership, tag)
}
/// `Entity.isInLava`.
pub fn is_in_lava(&self) -> bool {
!self.fluids.first_tick && self.fluids.interaction.is_in_fluid(&Membership, LAVA)
}
}
struct Membership;
impl FluidMembership for Membership {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
is_tagged(kind, tag)
}
}
impl MotionWorld<'_, '_, '_> {
fn fluid_at(&self, p: BlockPos) -> FluidState {
self.resources.fluids.fluid(self.block(p))
}
/// `Entity.baseTick`'s fluid phase: `wasEyeInWater`, `updateFluidInteraction`,
/// the lava's fall halving, and the end of the first tick.
pub fn fluid_base_tick(&mut self) -> Result<()> {
self.player.fluids.was_eye_in_water = self.player.is_eye_in_fluid(WATER);
self.update_fluids()?;
if self.player.is_in_lava() {
self.player.fall_distance *= 0.5;
}
self.player.fluids.first_tick = false;
Ok(())
}
/// `Entity.updateFluidInteraction`: immersion heights, then touching water
/// resets the fall and splashes on entry, then the currents push.
pub fn update_fluids(&mut self) -> Result<bool> {
let mut interaction = std::mem::take(&mut self.player.fluids.interaction);
let result = entity_fluid_tick::update(&mut interaction, self, WATER, LAVA, 1_000_000);
self.player.fluids.interaction = interaction;
result.map_err(|e| e.to_string().into())
}
/// `ClipContext.Fluid.WATER` in a fall-reset ray: the water's shape.
pub(super) fn water_clip(&mut self, from: Vec3, to: Vec3, p: BlockPos) -> Result<bool> {
let fluid = self.fluid_at(p);
if !is_tagged(fluid.kind(), WATER) {
return Ok(false);
}
let resources = self.resources;
let shape = resources
.fluids
.shapes
.lock()
.map_err(|_| "fluid shape cache poisoned")?
.shape(self, fluid, p)?;
Ok(shape.clip(from, to, p).is_some())
}
}
impl FluidMembership for MotionWorld<'_, '_, '_> {
fn fluid_in_tag(&self, kind: FluidKind, tag: FluidTagId) -> bool {
is_tagged(kind, tag)
}
}
impl CurrentTarget for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn is_player_class(&self) -> bool {
true
}
fn velocity(&mut self) -> Result<Vec3> {
Ok(self.player.velocity)
}
fn add_delta_movement(&mut self, delta: Vec3) -> Result<()> {
// Entity.addDeltaMovement and setDeltaMovement keep only finite values.
let v = self.player.velocity;
let sum = Vec3::new(v.x + delta.x, v.y + delta.y, v.z + delta.z);
if delta.is_finite() && sum.is_finite() {
self.player.velocity = sum;
}
Ok(())
}
}
impl FluidInteractionWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Chunk = ();
fn interaction_box(&mut self) -> Result<Option<Aabb>> {
// Entity.getFluidInteractionBox (not riding).
Ok(Some(
self.player.bounds().deflate(Vec3::new(0.001, 0.001, 0.001)),
))
}
fn loaded_chunk(&mut self, x: i32, z: i32) -> Result<Option<()>> {
Ok(self.scene.chunks.contains_key(&(x, z)).then_some(()))
}
fn chunk_sections(&mut self, _: ()) -> Result<FluidSections<'_>> {
// Resident sections keep no fluid count: scanning the box finds no
// fluid where a section without fluid would have skipped it.
static SECTIONS: [bool; crate::chunk::SECTIONS] = [true; crate::chunk::SECTIONS];
Ok(FluidSections {
minimum_section_y: crate::chunk::MIN_Y >> 4,
has_fluid: &SECTIONS,
})
}
fn bounding_box_min_y(&self) -> f64 {
self.player.bounds().min_position().y
}
fn block_x(&self) -> i32 {
self.player.position.x.floor() as i32
}
fn eye_y(&mut self) -> Result<f64> {
Ok(self.player.position.y + f64::from(self.player.dimensions.eye_height))
}
fn block_z(&self) -> i32 {
self.player.position.z.floor() as i32
}
fn fluid_state(&mut self, p: BlockPos) -> Result<FluidState> {
Ok(self.fluid_at(p))
}
fn fluid_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.height_at(self, [p.x, p.y, p.z])
}
fn camera_height(&mut self, f: FluidState, p: BlockPos) -> Result<f32> {
f.camera_height_at(self, [p.x, p.y, p.z])
}
fn flow(&mut self, f: FluidState, p: BlockPos) -> Result<Vec3> {
flow_at(self, f, p)
}
}
impl EntityFluidTickWorld for MotionWorld<'_, '_, '_> {
/// `Player.isPushedByFluid`: not while flying.
fn is_pushed_by_fluid(&mut self) -> Result<bool> {
Ok(!self.player.flying)
}
fn reset_fall_distance(&mut self) -> Result<()> {
self.player.fall_distance = 0.0;
Ok(())
}
fn was_touching_water(&self) -> bool {
self.player.fluids.was_touching_water
}
fn first_tick(&self) -> bool {
self.player.fluids.first_tick
}
fn water_splash(&mut self) -> Result<()> {
water_splash::water_splash(self, 1_000_000).map_err(|e| e.to_string())?;
Ok(())
}
fn set_was_touching_water(&mut self, value: bool) {
self.player.fluids.was_touching_water = value;
}
fn fast_lava(&mut self) -> Result<bool> {
Ok(self.player.fluids.fast_lava)
}
}
impl FluidHeightWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
fn fluid(&mut self, p: [i32; 3]) -> Result<FluidState> {
Ok(self.fluid_at(BlockPos::new(p[0], p[1], p[2])))
}
fn sturdy_down(&mut self, p: [i32; 3]) -> Result<bool> {
let state = MotionWorld::block(self, BlockPos::new(p[0], p[1], p[2]));
Ok(self.resources.fluids.sturdy(state, Direction::Down))
}
}
impl FluidFlowWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Block = BlockStateId;
fn fluid(&mut self, p: BlockPos) -> Result<FluidState> {
Ok(self.fluid_at(p))
}
fn block(&mut self, p: BlockPos) -> Result<BlockStateId> {
Ok(MotionWorld::block(self, p))
}
fn blocks_fluid_flow(&self, s: BlockStateId) -> bool {
self.resources.fluids.blocks_flow(s)
}
fn is_ice_class(&self, s: BlockStateId) -> bool {
self.resources.fluids.ice(s)
}
fn is_face_sturdy(&mut self, s: BlockStateId, _: BlockPos, d: Direction) -> Result<bool> {
Ok(self.resources.fluids.sturdy(s, d))
}
}
/// `Entity.doWaterSplashEffect` for the player: the world random draws the
/// pitch and particle offsets.
impl WaterSplashWorld for MotionWorld<'_, '_, '_> {
type Error = Box<dyn std::error::Error>;
type Entity = ();
/// `Player.getSwimHighSpeedSplashSound` when true, else `getSwimSplashSound`.
type Sound = bool;
fn this_entity(&self) {}
fn controlling_passenger(&mut self) -> Result<Option<()>> {
Ok(None)
}
fn velocity(&mut self, _: ()) -> Result<Vec3> {
Ok(self.player.velocity)
}
fn splash_sound(&mut self, high_speed: bool) -> Result<bool> {
Ok(high_speed)
}
fn random_float(&mut self) -> Result<f32> {
Ok(self.scene.random.next_float())
}
fn random_double(&mut self) -> Result<f64> {
Ok(self.scene.random.next_double())
}
fn play_sound(&mut self, high_speed: bool, volume: f32, pitch: f32) -> Result<()> {
self.player.events.push(MotionEvent::Splash {
high_speed,
volume,
pitch,
});
Ok(())
}
fn position(&self) -> Vec3 {
self.player.position
}
fn width(&self) -> f32 {
self.player.dimensions.width
}
fn particle(&mut self, kind: SplashParticle, position: Vec3, velocity: Vec3) -> Result<()> {
self.player.events.push(MotionEvent::SplashParticle {
bubble: matches!(kind, SplashParticle::Bubble),
position,
velocity,
});
Ok(())
}
fn splash_event(&mut self) -> Result<()> {
// The SPLASH game event: sculk listens to the player's moves itself.
self.player.events.push(MotionEvent::SplashEvent);
Ok(())
}
}
+39 -9
View File
@@ -47,6 +47,8 @@ pub enum Screen {
},
Disconnected {
reason: String,
/// Auto-reconnect's next attempt, until it is cancelled.
retry: Option<crate::reconnect::Retry>,
},
}
/// What a click asks the title screen to do.
@@ -205,14 +207,27 @@ impl Screen {
53,
),
],
Self::Disconnected { .. } => vec![b(
w / 2.0 - 100.0,
h / 2.0 + 30.0,
200.0,
"Back to Server List",
true,
54,
)],
Self::Disconnected { retry, .. } => {
let mut v = vec![b(
w / 2.0 - 100.0,
h / 2.0 + 30.0,
200.0,
"Back to Server List",
true,
54,
)];
if retry.is_some() {
v.push(b(
w / 2.0 - 100.0,
h / 2.0 + 54.0,
200.0,
"Cancel Reconnecting",
true,
55,
));
}
v
}
}
}
fn field(
@@ -427,7 +442,7 @@ impl Screen {
blink,
);
}
Self::Disconnected { reason } => {
Self::Disconnected { reason, retry } => {
centered(
batch,
"Connection Lost",
@@ -437,6 +452,10 @@ impl Screen {
for (i, line) in wrap(reason, 300.0, atlas).iter().enumerate() {
centered(batch, line, h / 2.0 - 16.0 + i as f32 * 9.0, u32::MAX);
}
if let Some(r) = retry {
let text = r.text(std::time::Instant::now());
centered(batch, &text, h / 2.0 + 16.0, rgba(170, 170, 170, 255));
}
}
}
}
@@ -552,6 +571,7 @@ impl Screen {
Self::Edit { .. } | Self::Direct { .. } | Self::Disconnected { .. },
Some(51 | 53 | 54),
) => *self = Self::list(saves),
(Self::Disconnected { retry, .. }, Some(55)) => *retry = None,
(Self::Direct { address }, Some(52)) => {
return Outcome::Connect(address.trim().to_owned());
}
@@ -578,6 +598,16 @@ impl Screen {
_ => None,
}
}
/// Auto-reconnect's attempt, once its countdown is over.
pub fn due_retry(&mut self) -> Option<crate::reconnect::Retry> {
let Self::Disconnected { retry, .. } = self else {
return None;
};
if !retry.as_ref()?.due(std::time::Instant::now()) {
return None;
}
retry.take()
}
/// The focused text field, its id and maximum length (copy and paste).
pub fn focused_text(&mut self) -> Option<(crate::clipboard::FieldId, &mut String, usize)> {
let id = match self {
+81 -25
View File
@@ -1,17 +1,20 @@
//! Multiplayer session: a network thread that connects to a server, logs in
//! (offline mode only), runs the configuration phase and then forwards decoded
//! play packets to the game thread. Keep-alives and pings are answered on the
//! network thread like vanilla's connection handlers so a busy frame never
//! times the client out. Online-mode (authenticated) servers are refused:
//! Horizon never handles Microsoft credentials.
//! Multiplayer session: a network thread that connects to a server, logs in,
//! runs the configuration phase and then forwards decoded play packets to the
//! game thread. Keep-alives and pings are answered on the network thread like
//! vanilla's connection handlers so a busy frame never times the client out.
//! Online-mode servers need the Microsoft account the launcher signed in
//! (crate::auth): the login joins the server through the session service and
//! encrypts the connection (ClientHandshakePacketListenerImpl.handleHello).
use crate::auth::AuthSession;
use horizon_protocol::{
PROTOCOL_VERSION,
connection::{ConnReader, ConnWriter, Connection, Counters},
crypto::offline_uuid,
crypto::{generate_secret, offline_uuid, server_hash},
packets::{Empty, configuration as cfg, handshake, login, play},
registry::Dynamic,
rsa::RsaPublicKey,
servers::parse_address,
text::{Language, plain},
text::{Language, plain, translatable},
};
use std::{
sync::{
@@ -37,7 +40,13 @@ pub enum Event {
DecodeError(String),
/// The server sent us back to configuration and finished it again.
Reconfigured(Arc<Dynamic>),
Disconnected(String),
/// The connection ended. `from_server`: the server gave the reason (or
/// the connection was refused for good), rather than the connection
/// failing (auto-reconnect retries only failures and shutdowns).
Disconnected {
reason: String,
from_server: bool,
},
}
pub struct Session {
@@ -51,8 +60,14 @@ pub struct Session {
debug: bool,
}
impl Session {
/// Start connecting in the background.
pub fn connect(address: &str, name: &str, view_distance: i8, lang: Arc<Language>) -> Self {
/// Start connecting in the background, as `auth`'s account when there is one.
pub fn connect(
address: &str,
name: &str,
auth: Option<Arc<AuthSession>>,
view_distance: i8,
lang: Arc<Language>,
) -> Self {
let (send, events) = channel();
let writer = Arc::new(Mutex::new(None));
let counters = Arc::new(Mutex::new(None));
@@ -61,22 +76,25 @@ impl Session {
let thread = std::thread::Builder::new()
.name("horizon-net".into())
.spawn(move || {
let reason = match run(
let result = run(
&address_owned,
&name_owned,
auth.as_deref(),
view_distance,
&lang,
&send,
&thread_writer,
&thread_counters,
) {
Ok(reason) => reason,
Err(e) => e,
};
);
let from_server = result.is_ok();
let reason = result.unwrap_or_else(|e| e);
if let Some(w) = thread_writer.lock().unwrap().take() {
w.shutdown();
}
let _ = send.send(Event::Disconnected(reason));
let _ = send.send(Event::Disconnected {
reason,
from_server,
});
})
.ok();
let debug = std::env::var_os("HORIZON_NET_DEBUG").is_some();
@@ -131,18 +149,29 @@ fn status(send: &Sender<Event>, text: &str) {
let _ = send.send(Event::Status(text.to_owned()));
}
/// The whole connection; returns the disconnect reason.
/// Shown when an online-mode server asks a client without an account to authenticate.
pub const NOT_SIGNED_IN: &str = "This server is in online mode. Sign in with your Microsoft account in the Horizon launcher to join it.";
/// A translation, or the key itself (Language.getOrDefault).
fn tr(lang: &Language, key: &str) -> String {
lang.get(key).cloned().unwrap_or_else(|| key.to_owned())
}
/// The whole connection. Ok: why it ended for good (the server's reason, or
/// a refusal no retry fixes); Err: the connection failed.
fn run(
address: &str,
name: &str,
auth: Option<&AuthSession>,
view_distance: i8,
lang: &Language,
send: &Sender<Event>,
shared_writer: &Mutex<Option<ConnWriter>>,
shared_counters: &Mutex<Option<Arc<Counters>>>,
) -> Result<String, String> {
let (host, port) =
parse_address(address).ok_or_else(|| format!("Invalid server address: {address}"))?;
let Some((host, port)) = parse_address(address) else {
return Ok(format!("Invalid server address: {address}"));
};
status(send, "Connecting to the server...");
let mut c =
Connection::connect(&host, port, Duration::from_secs(10)).map_err(|e| e.to_string())?;
@@ -158,8 +187,8 @@ fn run(
.encode(),
)
.map_err(e)?;
status(send, "Logging in...");
let uuid = offline_uuid(name);
// Vanilla's login sends the account's profile id, or the offline one.
let uuid = auth.map_or_else(|| offline_uuid(name), |a| a.uuid);
c.send(
&login::Serverbound::Hello(login::ServerHello {
name: name.to_owned(),
@@ -181,10 +210,37 @@ fn run(
let reason = serde_json::from_str::<serde_json::Value>(&p.reason_json)
.map(|v| json_text(&v, lang))
.unwrap_or(p.reason_json);
return Err(reason);
return Ok(reason);
}
login::Clientbound::Hello(_) => {
return Err("This server is in online mode. Horizon only joins offline-mode servers (online-mode=false).".into());
login::Clientbound::Hello(hello) => {
status(send, &tr(lang, "connect.authorizing"));
let key = RsaPublicKey::from_der(&hello.public_key)
.map_err(|err| format!("Protocol error: {err}"))?;
let secret = generate_secret().map_err(e)?;
if hello.should_authenticate {
let account = auth.ok_or_else(|| NOT_SIGNED_IN.to_owned())?;
let hash = server_hash(&hello.server_id, &secret, &hello.public_key);
if let Err(err) = crate::auth::join_server(account, &hash) {
let reason = match err.reason() {
Ok(key) => tr(lang, key),
Err(message) => message.to_owned(),
};
return Err(plain(
&translatable("disconnect.loginFailedInfo", &[&reason]),
lang,
));
}
}
status(send, &tr(lang, "connect.encrypting"));
c.send(
&login::Serverbound::Key(login::Key {
key: key.encrypt(&secret).map_err(e)?,
challenge: key.encrypt(&hello.challenge).map_err(e)?,
})
.encode(),
)
.map_err(e)?;
c.enable_encryption(&secret);
}
login::Clientbound::CustomQuery(q) => {
c.send(
+70 -21
View File
@@ -10,15 +10,13 @@
//! of control belong in `ui_theme` so the launcher-matching look stays in one
//! place. Everything else (sliders dragging, scrolling, Done) is handled here.
use crate::{
extras,
graphics_style::Cost,
graphics_ui::{self, Item, Level},
hud::{HudAtlas, HudBatch},
options_ui::{Event, Kind, Opt, OptionsUi, Page, apply_preset},
settings::{SOUND_SOURCES, Settings},
ui_theme::{
self as t, CONTROL, Face, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, SMALL, Ui, color,
id,
},
ui_theme::{self as t, CONTROL, Kind as Button, MenuStyle, ROW_LABEL, SIDEBAR, Ui, color, id},
};
/// One row of a section.
@@ -34,6 +32,8 @@ pub enum HRow {
Level,
/// A graphics setting with its frame-time cost and description.
Graphics(Item, Cost, &'static str),
/// One of Horizon's extras (`extras`), off by default.
Extra(extras::Item),
}
/// A sidebar section: name, description, rows.
pub struct Section {
@@ -172,6 +172,16 @@ pub const SECTIONS: &[Section] = &[
]
},
},
Section {
name: "Extras",
blurb: "Optional additions, all off by default: the game stays vanilla until you turn one on.",
rows: |_| {
extras::rows()
.into_iter()
.map(|r| r.map_or_else(HRow::Header, HRow::Extra))
.collect()
},
},
];
const NAV: u64 = id("options.nav", 0);
@@ -245,28 +255,18 @@ impl OptionsUi {
) -> Vec<(Item, f32, f32)> {
let (w, h) = (ui.w, ui.h);
if self.in_world {
ui.atmosphere(0.45, 1.0);
ui.atmosphere(horizon_theme::VEIL, 1.0);
} else {
if backdrop < 1.0 {
ui.cold_background(1.0 - backdrop);
}
ui.atmosphere(0.66, 1.0);
ui.atmosphere(horizon_theme::VEIL, 1.0);
}
let section = self.section.min(SECTIONS.len() - 1);
// The sidebar.
ui.fill(0.0, 0.0, SIDEBAR, h, color::with_alpha(color::SIDEBAR, 0.8));
ui.vline(SIDEBAR - 1.0, 0.0, h, color::BORDER);
ui.text_line(
Face::Display,
22.0,
30.0,
22.0,
16.0,
color::TEXT,
"Options",
);
ui.sidebar_frame("Options");
let names: Vec<&str> = SECTIONS.iter().map(|s| s.name).collect();
ui.sidebar_list(NAV, 12.0, 66.0, SIDEBAR - 24.0, &names, section);
ui.sidebar_list(NAV, 12.0, 72.0, SIDEBAR - 24.0, &names, section);
let dy = h - 12.0 - CONTROL;
ui.button(
DONE,
@@ -312,7 +312,7 @@ impl OptionsUi {
for (i, row) in rows.iter().enumerate() {
match *row {
HRow::Header(label) => {
ui.text(Face::Medium, SMALL, x, y + 18.0, color::FAINT, label);
ui.caps(x, y + 20.0, color::FAINT, label);
y += HEADER_H;
ui.divider(x, y, cw);
continue;
@@ -402,6 +402,43 @@ impl OptionsUi {
);
}
}
HRow::Extra(item) => {
let cy = y + ROW_H / 2.0;
let id = ROW + i as u64;
let mut cost = item.cost().map_or((0, ""), |c| (c as u8, c.label()));
let (caption, mut text) = (item.caption(), item.description().to_owned());
// A vanilla mapping on the same key: both act on it, like
// the binds list's duplicates; say which.
let conflicts = extras::zoom_key_conflicts(&s.extras, &s.keys);
if item == extras::Item::ZoomKey && !conflicts.is_empty() {
let names: Vec<String> =
conflicts.iter().map(|c| crate::lang::get(c)).collect();
cost = (3, "Also bound");
text = format!("{} uses this key too; both act on it.", names.join(", "));
}
let text = text.as_str();
if let Some(on) = item.switch(&s.extras) {
ui.described_row(x, y, caption, "", 0.0, cost, text, cw - 60.0);
ui.switch(id, control_x, cy, on);
} else {
let value = if item == extras::Item::ZoomKey
&& self.selected_key == Some(extras::ZOOM_KEY)
{
"Press a key".to_owned()
} else {
item.value(&s.extras)
};
let bw = ui.button_width(&value, false).max(96.0);
ui.described_row(x, y, caption, "", 0.0, cost, text, cw - bw - 24.0);
ui.button(
id,
[control_x - bw, y + 12.0, bw, CONTROL],
&value,
Button::Secondary,
true,
);
}
}
HRow::Style => {
ui.row(x, y, "Menu style", "", 0.0);
let labels = ["Horizon", "Classic"];
@@ -497,6 +534,7 @@ impl OptionsUi {
atlas: &HudAtlas,
x: f32,
y: f32,
framebuffer: [i32; 2],
drag: bool,
right: bool,
) -> Vec<Event> {
@@ -513,6 +551,10 @@ impl OptionsUi {
}
return events;
}
// A click anywhere stops waiting for the zoom key.
if self.selected_key == Some(extras::ZOOM_KEY) {
self.selected_key = None;
}
match self.horizon_target(s, atlas, x, y) {
Some(Target::Nav(i)) => {
self.section = i;
@@ -543,17 +585,24 @@ impl OptionsUi {
let section = self.section.min(SECTIONS.len() - 1);
match (SECTIONS[section].rows)(s).get(i) {
Some(HRow::Opt(opt)) => {
opt.cycle(s, right);
opt.cycle(s, right, framebuffer);
if *opt == Opt::Preset {
apply_preset(s);
}
events.push(Event::Changed);
}
Some(HRow::Graphics(item, ..)) => {
item.cycle(s, right);
item.cycle(s, right, framebuffer);
events.push(Event::Changed);
}
Some(HRow::Page(_, _, page)) => self.open_page(*page),
Some(HRow::Extra(extras::Item::ZoomKey)) => {
self.selected_key = Some(extras::ZOOM_KEY);
}
Some(HRow::Extra(item)) => {
item.cycle(&mut s.extras, right);
events.push(Event::Changed);
}
_ => {}
}
}
+319 -45
View File
@@ -189,7 +189,6 @@ impl Opt {
} else {
s.volumes[i]
}),
Opt::GuiScale => unit(s.gui_scale as f32, 0.0, 6.0),
Opt::Gamma => Kind::Slider(s.gamma),
Opt::MaxFps => unit(s.max_fps as f32, 10.0, 260.0),
Opt::CloudRange => unit(s.cloud_range as f32, 2.0, 128.0),
@@ -261,11 +260,12 @@ impl Opt {
}
}
Opt::GuiScale => {
if s.gui_scale == 0 {
let value = if s.gui_scale == 0 {
tr("options.guiScale.auto")
} else {
Text::literal(s.gui_scale.to_string())
}
};
generic(c, value)
}
Opt::Gamma => match (f64::from(s.gamma) * 100.0) as i32 {
0 => generic(c, tr("options.gamma.min")),
@@ -446,7 +446,6 @@ impl Opt {
Opt::WheelSensitivity => s.mouse_wheel_sensitivity = 0.01 + v * 9.99,
Opt::Volume(0) => s.master_volume = v,
Opt::Volume(i) => s.volumes[i] = v,
Opt::GuiScale => s.gui_scale = step(0.0, 6.0) as u32,
Opt::Gamma => s.gamma = v,
Opt::MaxFps => s.max_fps = (step(1.0, 26.0) as u32) * 10,
Opt::CloudRange => s.cloud_range = step(2.0, 128.0) as i32,
@@ -494,7 +493,7 @@ impl Opt {
)
}
/// Advance a cycle button (CycleButton.cycleValue).
pub fn cycle(self, s: &mut Settings, back: bool) {
pub fn cycle(self, s: &mut Settings, back: bool, framebuffer: [i32; 2]) {
let next = |n: u8, count: u8| {
if back {
(n + count - 1) % count
@@ -503,6 +502,17 @@ impl Opt {
}
};
match self {
Opt::GuiScale => {
let max = crate::window::calculate_scale(framebuffer, 0, s.force_unicode) as u32;
let value = s.gui_scale.min(max);
s.gui_scale = if back {
if value == 0 { max } else { value - 1 }
} else if value == max {
0
} else {
value + 1
};
}
Opt::InvertY => s.invert_y = !s.invert_y,
Opt::DiscreteScroll => s.discrete_scroll = !s.discrete_scroll,
Opt::ViewBobbing => s.view_bobbing = !s.view_bobbing,
@@ -665,6 +675,8 @@ struct Widget {
/// What the game must do after an interaction.
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
/// An accepted button press or the release of a slider.
ButtonClick,
/// Close the options screens (back to the pause menu or title).
Close,
/// Settings changed: apply them.
@@ -1607,17 +1619,22 @@ impl OptionsUi {
x: f32,
y: f32,
size: (f32, f32),
framebuffer: [i32; 2],
drag: bool,
right: bool,
) -> Vec<Event> {
if crate::ui_theme::horizon() && self.page() == Page::Main {
return self.click_horizon(s, atlas, x, y, drag, right);
return self.click_horizon(s, atlas, x, y, framebuffer, drag, right);
}
if let Some(level) = Self::graphics_level(self.page()) {
use crate::graphics_ui::Action;
let mut events = Vec::new();
for action in self.graphics.click(level, s, (x, y), size, drag, right) {
for action in self
.graphics
.click(level, s, (x, y), size, framebuffer, drag, right)
{
match action {
Action::ButtonClick => events.push(Event::ButtonClick),
Action::Changed => events.push(Event::Changed),
Action::OpenAdvanced => self.push(Page::GraphicsAdvanced),
Action::OpenSimple => {
@@ -1642,6 +1659,9 @@ impl OptionsUi {
}
let m = crate::screen_draw::Measure(&atlas.font);
let p = self.packs(atlas, size);
if p.button_at(&m, x as f64, y as f64) {
events.push(Event::ButtonClick);
}
let before = p.search_focused();
let action = p.click(&m, x as f64, y as f64);
if !before && p.search_focused() {
@@ -1682,6 +1702,11 @@ impl OptionsUi {
events.push(Event::Changed);
return events;
}
// AbstractWidget accepts only the primary button. Rebinding above
// accepts other mouse buttons, but is not a widget activation.
if right {
return events;
}
for wd in widgets {
if !ui::hovered((x, y), wd.x, wd.y, wd.w, wd.h) {
continue;
@@ -1692,43 +1717,46 @@ impl OptionsUi {
match wd.kind {
WKind::Button {
active: true, act, ..
} => match act {
Act::Push(p) => self.push(p),
Act::Done => events.extend(self.back(s)),
Act::Cycle(opt) => {
opt.cycle(s, right);
if opt == Opt::Preset {
apply_preset(s);
} => {
events.push(Event::ButtonClick);
match act {
Act::Push(p) => self.push(p),
Act::Done => events.extend(self.back(s)),
Act::Cycle(opt) => {
opt.cycle(s, right, framebuffer);
if opt == Opt::Preset {
apply_preset(s);
}
events.push(Event::Changed);
}
events.push(Event::Changed);
}
Act::Key(name) => self.selected_key = Some(name),
Act::ResetKey(name) => {
s.keys.set(name, KeyBinds::default_of(name));
events.push(Event::Changed);
}
Act::ResetKeys => {
s.keys.reset_all();
events.push(Event::Changed);
}
Act::PadKey(action) => self.selected_pad_action = Some(action),
Act::ResetPadKey(action) => {
s.controller
.bind(action, gamepad::PadSettings::default_of(action));
events.push(Event::Changed);
}
Act::ResetPadKeys => {
s.controller.reset_bindings();
events.push(Event::Changed);
}
Act::HorizonMenus => {
self.horizon_menus();
if let Ok(dir) = std::env::current_dir() {
crate::ui_theme::save_preferences(&dir);
Act::Key(name) => self.selected_key = Some(name),
Act::ResetKey(name) => {
s.keys.set(name, KeyBinds::default_of(name));
events.push(Event::Changed);
}
Act::ResetKeys => {
s.keys.reset_all();
events.push(Event::Changed);
}
Act::PadKey(action) => self.selected_pad_action = Some(action),
Act::ResetPadKey(action) => {
s.controller
.bind(action, gamepad::PadSettings::default_of(action));
events.push(Event::Changed);
}
Act::ResetPadKeys => {
s.controller.reset_bindings();
events.push(Event::Changed);
}
Act::HorizonMenus => {
self.horizon_menus();
if let Ok(dir) = std::env::current_dir() {
crate::ui_theme::save_preferences(&dir);
}
}
Act::None => {}
}
Act::None => {}
},
}
WKind::Slider { opt, .. } => {
self.dragging = Some(opt);
opt.set_slider(s, ui::slider_value(wd.x, wd.w, x));
@@ -1763,10 +1791,17 @@ impl OptionsUi {
self.section_shown = None;
self.hscroll = 0.0;
}
pub fn release(&mut self) {
self.dragging = None;
pub fn release(&mut self) -> Vec<Event> {
// AbstractSliderButton suppresses the press sound and plays once on
// release, even if the pointer has left the widget or its value stayed.
let slider = self.dragging.take().is_some();
self.hdragging = None;
self.graphics.release();
let graphics_slider = self.graphics.release();
if slider || graphics_slider {
vec![Event::ButtonClick]
} else {
Vec::new()
}
}
pub fn scroll(&mut self, s: &Settings, size: (f32, f32), amount: f32) {
let (_, top, bottom, content) = self.layout(s, size.0, size.1);
@@ -1930,7 +1965,11 @@ impl OptionsUi {
.unwrap_or("key.keyboard.unknown")
.to_owned()
};
s.keys.set(name, &value);
if name == crate::extras::ZOOM_KEY {
s.extras.zoom_key = value;
} else {
s.keys.set(name, &value);
}
return vec![Event::Changed];
}
if key == K::Escape {
@@ -1956,6 +1995,241 @@ mod tests {
use super::*;
use crate::ui_theme::{MenuStyle, set_style, style};
fn atlas() -> HudAtlas {
HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets")).unwrap()
}
#[test]
fn classic_video_gui_scale_cycles_on_press_without_dragging() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Video);
let size = (480.0, 480.0);
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
let button = widgets
.iter()
.find(|wd| {
matches!(
wd.kind,
WKind::Button {
active: true,
act: Act::Cycle(Opt::GuiScale),
..
}
)
})
.expect("GUI Scale must be a cycle button in classic Video Settings");
let (x, y) = (button.x + 1.0, button.y + 1.0);
assert!(Opt::GuiScale.slider_position(&s).is_none());
assert!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, true)
.is_empty()
);
assert_eq!(s.gui_scale, 0);
for expected in [1, 2, 0] {
assert_eq!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
vec![Event::ButtonClick, Event::Changed]
);
assert_eq!(s.gui_scale, expected);
assert!(
ui.click(&mut s, &atlas, x + 100.0, y, size, [854, 480], true, false)
.is_empty()
);
assert_eq!(s.gui_scale, expected);
assert!(ui.release().is_empty());
}
}
#[test]
fn gui_scale_cycle_handles_reverse_and_out_of_range_saved_values() {
for (framebuffer, force_unicode, max) in [
([854, 480], false, 2),
([1920, 1080], false, 4),
([1280, 720], true, 4),
([3840, 2160], false, 9),
([320, 240], false, 1),
] {
let mut s = Settings {
force_unicode,
..Settings::default()
};
for expected in (0..=max).rev() {
Opt::GuiScale.cycle(&mut s, true, framebuffer);
assert_eq!(s.gui_scale, expected);
}
for expected in (1..=max).chain([0]) {
Opt::GuiScale.cycle(&mut s, false, framebuffer);
assert_eq!(s.gui_scale, expected);
}
s.gui_scale = u32::MAX;
s.clamp_gui_scale(framebuffer);
assert_eq!(s.gui_scale, max);
s.gui_scale = u32::MAX;
Opt::GuiScale.cycle(&mut s, false, framebuffer);
assert_eq!(s.gui_scale, 0);
s.gui_scale = u32::MAX;
Opt::GuiScale.cycle(&mut s, true, framebuffer);
assert_eq!(s.gui_scale, max - 1);
}
let mut s = Settings {
gui_scale: 4,
..Settings::default()
};
// A resized window supplies a new maximum on the next interaction.
Opt::GuiScale.cycle(&mut s, true, [854, 480]);
assert_eq!(s.gui_scale, 1);
}
#[test]
fn classic_buttons_sound_but_disabled_and_nonprimary_clicks_are_silent() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Mouse);
let size = (480.0, 320.0);
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
let button = widgets
.iter()
.find(|wd| {
matches!(
wd.kind,
WKind::Button {
active: true,
act: Act::Cycle(_),
..
}
)
})
.unwrap();
let (x, y) = (button.x + 1.0, button.y + 1.0);
assert!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, true)
.is_empty()
);
assert_eq!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
vec![Event::ButtonClick, Event::Changed]
);
assert!(ui.release().is_empty());
assert!(
ui.click(&mut s, &atlas, 0.0, 0.0, size, [854, 480], false, false)
.is_empty()
);
ui.show(Page::KeyBinds);
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
let disabled = widgets
.iter()
.find(|wd| matches!(wd.kind, WKind::Button { active: false, .. }))
.unwrap();
assert!(
ui.click(
&mut s,
&atlas,
disabled.x + 1.0,
disabled.y + 1.0,
size,
[854, 480],
false,
false
)
.is_empty()
);
}
#[test]
fn classic_sliders_sound_once_on_release_including_unchanged_values() {
let atlas = atlas();
let size = (480.0, 320.0);
let mut s = Settings::default();
let mut ui = OptionsUi::default();
ui.show(Page::Sound);
let (widgets, _, _, _) = ui.layout(&s, size.0, size.1);
let slider = widgets
.iter()
.find(|wd| {
matches!(
wd.kind,
WKind::Slider {
opt: Opt::Volume(0),
..
}
)
})
.unwrap();
let (x, y) = (slider.x + slider.w - 1.0, slider.y + 1.0);
assert_eq!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
vec![Event::Changed]
);
assert_eq!(s.master_volume, 1.0);
assert_eq!(ui.release(), vec![Event::ButtonClick]);
assert!(ui.release().is_empty());
assert_eq!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], false, false),
vec![Event::Changed]
);
for cx in [-100.0, 250.0, 1000.0] {
assert_eq!(
ui.click(&mut s, &atlas, cx, -100.0, size, [854, 480], true, false),
vec![Event::Changed]
);
}
assert_eq!(ui.release(), vec![Event::ButtonClick]);
assert!(
ui.click(&mut s, &atlas, x, y, size, [854, 480], true, false)
.is_empty()
);
}
#[test]
fn classic_language_rows_and_text_fields_are_silent() {
let atlas = atlas();
let mut s = Settings::default();
let mut ui = OptionsUi {
languages: languages(),
..Default::default()
};
ui.show(Page::Language);
let size = (480.0, 320.0);
let (widgets, top, bottom, _) = ui.layout(&s, size.0, size.1);
let row = widgets
.iter()
.find(|wd| {
matches!(wd.kind, WKind::LanguageRow { .. }) && wd.y >= top && wd.y + wd.h <= bottom
})
.unwrap();
assert!(
ui.click(
&mut s,
&atlas,
row.x + 1.0,
row.y + 1.0,
size,
[854, 480],
false,
false
)
.is_empty()
);
assert!(ui.release().is_empty());
let search = ui.language_search.clone();
assert!(
ui.click(
&mut s,
&atlas,
search.x + 1.0,
search.y + 1.0,
size,
[854, 480],
false,
false
)
.is_empty()
);
}
fn languages() -> Vec<LanguageInfo> {
(0..30)
.map(|i| LanguageInfo {
+68
View File
@@ -19,6 +19,7 @@ pub enum Compat {
TooNew,
Unknown,
}
impl Compat {
fn key(self) -> &'static str {
match self {
@@ -457,6 +458,18 @@ impl PackScreen {
self.info(id).is_none_or(|p| !p.fixed || !p.required)
}
/// Whether a left click activates a footer or confirmation button.
/// Pack entries and the search field do not play widget click sounds.
pub fn button_at(&self, m: &Measure, x: f64, y: f64) -> bool {
let buttons = if let Some(c) = &self.confirm {
self.confirm_layout(m, c).2
} else {
self.footer()
};
buttons.into_iter().any(|(bx, by)| {
x >= bx as f64 && y >= by as f64 && x < (bx + 150) as f64 && y < (by + 20) as f64
})
}
/// A left click (`Screen.mouseClicked`).
pub fn click(&mut self, m: &Measure, x: f64, y: f64) -> Action {
if self.confirm.is_some() {
@@ -928,3 +941,58 @@ impl PackScreen {
}
}
}
#[cfg(test)]
mod click_sound_tests {
use super::*;
#[test]
fn only_footer_and_confirmation_buttons_request_a_click_sound() {
let atlas =
crate::hud::HudAtlas::build(std::path::Path::new("/nonexistent/horizon-test-assets"))
.unwrap();
let m = Measure(&atlas.font);
let mut screen = PackScreen::new(&m, 480, 320, false, Vec::new(), &[]);
assert!(!screen.button_at(&m, 0.0, 0.0));
assert!(!screen.button_at(
&m,
screen.search.x as f64 + 1.0,
screen.search.y as f64 + 1.0
));
let buttons = screen.footer();
for (i, (x, y)) in buttons.into_iter().enumerate() {
assert!(screen.button_at(&m, x as f64 + 1.0, y as f64 + 1.0));
assert!(!screen.button_at(&m, (x + 150) as f64, (y + 20) as f64));
assert_eq!(
screen.click(&m, x as f64 + 1.0, y as f64 + 1.0),
if i == 0 {
Action::OpenFolder
} else {
Action::Done
}
);
}
screen.confirm = Some(Confirm {
id: "incompatible".into(),
title: Text::literal("Confirm"),
message: Text::literal("Use this pack?"),
});
let buttons = screen
.confirm_layout(&m, screen.confirm.as_ref().unwrap())
.2;
for (x, y) in buttons {
assert!(screen.button_at(&m, x as f64 + 1.0, y as f64 + 1.0));
}
assert!(!screen.button_at(
&m,
screen.footer()[0].0 as f64 + 1.0,
screen.footer()[0].1 as f64 + 1.0
));
let (x, y) = buttons[1];
assert_eq!(
screen.click(&m, x as f64 + 1.0, y as f64 + 1.0),
Action::None
);
assert!(!screen.confirming());
}
}

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