Compare commits

..
Author SHA1 Message Date
Ludovic MarieandClaude Opus 5.5 266c4576a5 Launcher: java_launch's Windows paths, one part at a time
The log config and old versions' asset folder were joined from
"a/b" strings; on Windows their tests compared those mixed
separators with paths joined part by part. Join them part by part.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 01:21:50 +01:00
1257 changed files with 29988 additions and 155110 deletions

No files matched your search

-76
View File
@@ -1,76 +0,0 @@
---
name: vanilla-parity
description: Fix a Horizon bug or gap so it behaves 1:1 like vanilla 26.3, starting from the port ledger (tools/port_ledger.py) instead of grepping. Use for any issue, Discord report or PR that makes Horizon match vanilla: "X doesn't work like in Java", a missing sound, particle, animation, mob behaviour, block rule, screen or packet.
---
# Vanilla parity with the port ledger
The port ledger pairs every vanilla method with the Rust fn that ports it (or says it is missing, or needs
no port) and lists where a port isn't wired like vanilla. Ask it first; grep only for what it can't answer.
Full reference: `docs/port-ledger.md`.
## 0. Have a fresh ledger
```sh
python3 tools/port_ledger.py build # ~20 s; again after pulling main
```
It needs the vanilla jar (the launcher's `versions/26.3/26.3.jar`, or `--jar`) and/or the lab's decompiled
sources (`python3 tools/lab.py decompile`, or `--sources DIR`). If `build` says it has no vanilla code, run
the lab first; don't guess vanilla from memory.
## 1. From the report to the code
```sh
python3 tools/port_ledger.py issue 3236 # a GitHub issue number
python3 tools/port_ledger.py issue "mooshroom stays red after lightning" # or the report's text
```
It ranks the vanilla classes the report names and lists, per class, its Rust home files, where each method is
ported, and the known gaps (`missing` rows from the verdict map, seam/client/drift gaps). Often the cause is
already written there ("Type is not saved"). Then drill in:
```sh
python3 tools/port_ledger.py where MushroomCow.readAdditionalSaveData # ports, callers, callees, gaps
python3 tools/port_ledger.py class MushroomCow # every method: where, or missing
python3 tools/port_ledger.py what crates/horizon-client/src/mobs/farm.rs:120 # which vanilla method a fn ports
```
A ledger answer is a lead, not a verdict: about 1 in 12 map rows is wrong. Read the vanilla method (path and
line are in the output) and the Rust fn before changing anything.
## 2. Port it the vanilla way
- Translate the vanilla method, don't reinvent it: same order of operations, same constants, the same random
draws in the same order (`horizon_core::random`), Java `Math` through `horizon_core::jmath`.
- Open the fn's doc with the vanilla method it ports: `` /// `MushroomCow.readAdditionalSaveData`: ... ``.
That one line is what makes the next agent find it.
- Fix the path players run: single player is a client of the integrated server, so server logic lives in
`game/lan*.rs` and `src/lan/`, and what only the client's copy shows (particles, local sounds, hand
animation) must be reached from `game/remote*.rs`. A fix on the old in-frame path alone fixes nothing.
- Look at the neighbours the ledger lists for the same class: a `client` or `seam` gap next to your fix is
usually the same bug on the other path.
## 3. Before the PR
```sh
python3 tools/port_ledger.py check --base origin/main
```
It lists the ports your branch touches with their open gaps, citations to add, stale citations, and (against
the base) the gaps the branch closes and opens. Close what belongs to your fix, cite what you ported, leave
no new stale citation. If you ported a method the verdict map called `missing`, change its row in
`tools/port_map/*.tsv` to `port` with the fn (`file.rs::Owner::fn`) and run
`python3 tools/port_ledger.py map-check tools/port_map/<file>.tsv`.
Then the usual: the harness for the area (`docs/architecture.md`), `cargo check`/tests per `AGENTS.md`, and
a small PR that says which vanilla method it now matches.
## Finding work
```sh
python3 tools/port_ledger.py gaps --kind seam # ported on two paths, wired on one: the best leads
python3 tools/port_ledger.py gaps --kind client # client-only effects the server path never reaches
python3 tools/port_ledger.py gaps --kind drift # a port missing a sound, particle, item or constant
rg -n "player:" tools/port_map/*.tsv # missing behaviour a player would see
```
-14
View File
@@ -1,21 +1,7 @@
<!-- Opened by an AI agent? First line: "> 🤖 Opened by <your GitHub login>'s AI agent (<tool, model>), not by <your GitHub login> personally." Use your own login, not someone else's. -->
## What and why
<!-- What this changes, and why. Link the issue it fixes ("Fixes #123"). -->
## Kind
<!-- Tick one: it sets the pull request's label (CONTRIBUTING.md "Pull requests"). -->
- [ ] parity: Horizon now does what vanilla 26.3 does
- [ ] bug: a crash or a breakage
- [ ] perf: faster, or less memory
- [ ] feature: something new for players (listed under New in the release notes)
- [ ] extra: Horizon-only, off by default
- [ ] tooling: tools, CI, tests, harnesses
- [ ] docs
## Vanilla reference
<!-- The vanilla classes and methods this follows (tools/rea_vanilla.py), and the harness that checks it.
+4 -6
View File
@@ -16,14 +16,12 @@ jobs:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
BRANCH: ${{ github.event.pull_request.head.ref }}
HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
SHA: ${{ github.event.pull_request.head.sha }}
run: |
# Every head the pull request had, not only its last: a run-parity label added on an older head left that
# run queued after the merge (#3104, 2026-10-29). Its branch in its own repository names its runs (another
# fork can have a branch of the same name).
for status in queued in_progress waiting pending requested; do
gh api -X GET "repos/$REPO/actions/runs" -f branch="$BRANCH" -f event=pull_request -f status="$status" \
-f per_page=100 --jq ".workflow_runs[] | select(.head_repository.full_name == \"$HEAD_REPO\") | .id"
gh run list -R "$REPO" --branch "$BRANCH" --status "$status" --limit 100 \
--json databaseId,event,headSha \
-q ".[] | select(.event == \"pull_request\" and .headSha == \"$SHA\") | .databaseId"
done | sort -u | while read -r id; do
gh run cancel -R "$REPO" "$id" || true
done
+6 -5
View File
@@ -51,7 +51,7 @@ jobs:
if: steps.rust.outputs.required != 'false'
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
rustup toolchain install stable --profile minimal --component rustfmt --component clippy --target wasm32-unknown-unknown
# Dependencies and the workspace's own build, saved from main's runs (pull requests read main's cache).
- uses: Swatinem/rust-cache@v2
if: steps.rust.outputs.required != 'false'
@@ -62,7 +62,8 @@ jobs:
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable fmt --all -- --check
cargo +stable clippy --workspace --all-targets -- -D warnings
# With the game's code mods (on in every release build, off by default).
cargo +stable clippy --workspace --all-targets --features horizon-client/mods -- -D warnings
# The server build (released as horizon-engine): the game without sound or controllers.
cargo +stable clippy -p horizon-client --all-targets --no-default-features -- -D warnings
# Libraries, binaries and integration tests, then doc tests: not the ~275 examples, which clippy above already
@@ -70,11 +71,11 @@ jobs:
- name: Test Rust core and voxel kernel correctness
if: steps.rust.outputs.required != 'false'
run: |
cargo +stable test --workspace --lib --bins --tests
cargo +stable test --workspace --lib --bins --tests --features horizon-client/mods,horizon-mods/pack
# The full content-root tests (#[ignore]d: minutes each on a laptop). The same build as above; they need the
# prepared vanilla data, so without it they pass at once.
cargo +stable test --workspace --lib mod_content::tests:: -- --ignored
cargo +stable test --workspace --doc
cargo +stable test --workspace --lib --features horizon-client/mods,horizon-mods/pack mod_content::tests:: -- --ignored
cargo +stable test --workspace --doc --features horizon-client/mods,horizon-mods/pack
# The launcher is its own workspace (launcher/Cargo.toml), so verify's cargo runs never build it. A pull request that
# changes it or a crate it builds is checked here, and so is every push to main: two pull requests can each pass
# alone and break it together (#2059 and the registry ratings did, 2026-10-26).
-76
View File
@@ -1,76 +0,0 @@
name: claim command
# `/claim` and `/unclaim` comments: anyone takes an issue before working on it, and a daily run releases the claims
# older than 5 days that no open pull request links (CONTRIBUTING.md "Claim before you start",
# tools/ci/claim_command.py).
#
# Why no pull request's code runs here, though the token can write:
# - `issue_comment` and `schedule` always run this file from main, whoever comments and wherever.
# - It checks out main's script and list only, never a pull request; it reads threads through the API.
# - The comment's text and author reach the script as env vars, never in a shell line. The token stays in the step
# and can only write issues (assignees, comments, reactions).
on:
issue_comment:
types: [created]
schedule:
- cron: "23 5 * * *"
workflow_dispatch:
permissions:
contents: read
jobs:
command:
# Every other comment skips here, before a runner starts. Pull requests are answered by the script.
if: >-
github.event_name == 'issue_comment' && github.event.comment.user.type != 'Bot' && (
startsWith(github.event.comment.body, '/claim') ||
startsWith(github.event.comment.body, '/unclaim') ||
startsWith(github.event.comment.body, '🤖 Agent: /claim') ||
startsWith(github.event.comment.body, '🤖 Agent: /unclaim'))
# One command per issue at a time, so two `/claim`s can't both find it free. On the job, not the workflow:
# the skipped runs of ordinary comments must not cancel a waiting one.
concurrency:
group: claim-${{ github.event.issue.number }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
sparse-checkout: |
.github/trusted-reviewers.txt
tools/ci/nightly_set.py
tools/ci/claim_command.py
sparse-checkout-cone-mode: false
- name: Run the command
env:
GH_TOKEN: ${{ github.token }}
BODY: ${{ github.event.comment.body }}
AUTHOR: ${{ github.event.comment.user.login }}
ISSUE: ${{ github.event.issue.number }}
COMMENT_ID: ${{ github.event.comment.id }}
REPO: ${{ github.repository }}
run: python3 tools/ci/claim_command.py command
release:
if: github.event_name != 'issue_comment' && github.repository == 'horizon-rust/horizon'
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
issues: write
steps:
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
sparse-checkout: |
tools/ci/nightly_set.py
tools/ci/claim_command.py
sparse-checkout-cone-mode: false
- name: Release stale claims
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: python3 tools/ci/claim_command.py release
+9 -8
View File
@@ -37,10 +37,9 @@ permissions:
jobs:
exporters:
# This runner holds the maintainer's own pinned Minecraft jars. Only our classes leave it. An untrusted build
# goes to the Mac mini's nightly runner (macOS + horizon-nightly: ludovics-mac-mini-nightly, beside the one that
# runs pull requests' parity jobs, so a nightly never waits behind their queue), never the release runner
# (MAC_RUNNER: ludovics-mac-mini-release) nor parity-main's.
runs-on: ${{ inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-nightly"]') }}
# goes to the Mac mini runner that already runs pull requests' parity jobs (macOS + horizon-game:
# ludovics-mac-mini), never the release runner (MAC_RUNNER: ludovics-mac-mini-release) nor parity-main's.
runs-on: ${{ inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]') }}
# Three full preparations (two isolated, one batched) besides the compile.
timeout-minutes: 60
steps:
@@ -104,7 +103,7 @@ jobs:
mac: true
dir: horizon-macos-arm64
asset: horizon-macos-arm64.zip
runs-on: ${{ matrix.mac && (inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-nightly"]')) || matrix.os }}
runs-on: ${{ matrix.mac && (inputs.trusted && vars.MAC_RUNNER || fromJSON('["self-hosted", "macOS", "horizon-game"]')) || matrix.os }}
# Notarizing the zip can take a few minutes.
timeout-minutes: ${{ matrix.mac && 60 || 40 }}
env:
@@ -138,7 +137,8 @@ jobs:
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, horizon-ctl, horizon-prepare and horizon-server
run: cargo build --release --locked -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server
# `horizon-client/mods`: every released game runs code mods (the feature is off in dev builds).
run: cargo build --release --locked --features horizon-client/mods -p horizon-client --bin horizon-client --bin horizon-ctl -p horizon-prepare --bin horizon-prepare -p horizon-server --bin horizon-server
- name: Every program the release folder takes was built
run: |
for binary in horizon-client horizon-ctl horizon-prepare horizon-server; do
@@ -266,8 +266,9 @@ jobs:
run: |
set -euo pipefail
# After the client is packaged: target/release/horizon-client is rebuilt without the audio and
# controllers features, so it needs neither libasound nor libudev (minimal server images lack them).
cargo build --release --locked -p horizon-client --no-default-features --bin horizon-client
# controllers features, so it needs neither libasound nor libudev (minimal server images lack them),
# and with code mods like the client.
cargo build --release --locked -p horizon-client --no-default-features --features mods --bin horizon-client
cargo run --locked -p xtask -- package-server target/release/horizon-client "dist/${{ matrix.server_dir }}"
folder="dist/${{ matrix.server_dir }}"
python3 tools/check_imports.py --server "$folder/horizon-engine" "$folder/horizon-server" "$folder/horizon-prepare"
+3 -3
View File
@@ -233,9 +233,9 @@ jobs:
# before the Nightly-only switch keep (they don't read Nightlies).
gh release create nightly --prerelease --latest=false --target "$SHA" \
--title "Nightly $DATE · ${SHA:0:7}" --notes-file dist/nightly-notes.md \
"dist/horizon-linux-x86_64.tar.gz#Game files the launcher installs (Nightly): Linux (horizon-linux-x86_64.tar.gz)" \
"dist/horizon-windows-x64.zip#Game files the launcher installs (Nightly): Windows (horizon-windows-x64.zip)" \
"dist/horizon-macos-arm64.zip#Game files the launcher installs (Nightly): macOS (horizon-macos-arm64.zip)" \
"dist/horizon-linux-x86_64.tar.gz#Nightly game files: Linux (horizon-linux-x86_64.tar.gz)" \
"dist/horizon-windows-x64.zip#Nightly game files: Windows (horizon-windows-x64.zip)" \
"dist/horizon-macos-arm64.zip#Nightly game files: macOS (horizon-macos-arm64.zip)" \
"dist/horizon-server-linux-x86_64.tar.gz#Nightly dedicated server for Linux (horizon-server-linux-x86_64.tar.gz)" \
"dist/horizon-source.tar.gz#Source of this Nightly, commit ${SHA:0:7} (horizon-source.tar.gz; kept for good as the tag $SOURCE_TAG)" \
dist/SHA256SUMS "${signature[@]}" dist/smoke-test.json
-41
View File
@@ -1,41 +0,0 @@
name: overlap note
# One comment on a pull request naming the other open pull requests that close the same issue or change the same
# functions, edited on every push (tools/ci/overlap_note.py, issue #3859).
#
# Why no pull request's code runs here, though `pull_request_target` gives a token that can write:
# - `pull_request_target` runs this file and the script from main, never the pull request's copy.
# - The checkout is main's (`ref: main`), blobless, with the script alone on disk. The pull requests' heads are fetched
# as git objects and only diffed, never checked out; git runs with hooks, fsmonitor, external diff and textconv off.
# - The rest comes from the API. The token writes the comment only.
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review]
permissions:
contents: read
jobs:
note:
if: github.event.pull_request.base.ref == 'main'
# A newer push replaces the note being computed.
concurrency:
group: overlap-note-${{ github.event.pull_request.number }}
cancel-in-progress: true
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
filter: blob:none
persist-credentials: false
sparse-checkout: |
tools/ci/overlap_note.py
sparse-checkout-cone-mode: false
- name: Note
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: python3 tools/ci/overlap_note.py event
-36
View File
@@ -1,36 +0,0 @@
name: pr labels
# A pull request's kind label (the box ticked in the template) and area labels (the paths it changes):
# tools/ci/pr_labels.py, CONTRIBUTING.md "Pull requests".
#
# Why no pull request's code runs here, though `pull_request_target` gives a token that can write to fork PRs:
# - `pull_request_target` runs this file and the script from main, never the pull request's copy.
# - It checks out main's script only (`ref: main`), never the pull request's head or merge commit.
# - The script reads the event file (the description is data in JSON, never in a shell line) and the API's list of
# changed file names; it runs, builds and imports nothing of theirs. The token writes labels only.
on:
pull_request_target:
types: [opened, reopened, synchronize, edited, ready_for_review]
permissions:
contents: read
jobs:
label:
# Title-only edits change nothing: skip them before a runner starts.
if: github.event.action != 'edited' || github.event.changes.body != null
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
pull-requests: write
steps:
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
sparse-checkout: |
tools/ci/pr_labels.py
sparse-checkout-cone-mode: false
- name: Label
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
run: python3 tools/ci/pr_labels.py event
+2 -6
View File
@@ -5,15 +5,11 @@ name: run-parity
# skipped `verify`, and GitHub counts a skipped required check as passed.
on:
pull_request:
# A push starts a run only to cancel the old head's (see concurrency): the job runs on the label alone.
types: [labeled, synchronize]
types: [labeled]
permissions:
contents: read
concurrency:
# The run-parity label and pushes share one group per pull request, so the newest run cancels the one before: a
# pushed pull request's run tested a head the merge would no longer land. Any other label gets a group of its own:
# in the shared one, adding needs-proof cancelled the parity run queued seconds before (run 40766180150).
group: run-parity-${{ github.event.pull_request.number }}${{ github.event.action == 'labeled' && github.event.label.name != 'run-parity' && format('-{0}', github.run_id) || '' }}
group: run-parity-${{ github.event.pull_request.number }}
cancel-in-progress: true
env:
# Test runs never reach the telemetry server: no live-count ping, no uploads (docs/telemetry.md).
+21 -29
View File
@@ -13,15 +13,13 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
`XDG_CONFIG_HOME`, plus `HORIZON_LAUNCHER_NO_SELF_UPDATE=1` and `HORIZON_NO_AUDIO=1`, and, for the
launcher, `HORIZON_LAUNCHER_TRASH`, `HORIZON_LAUNCHER_CLIPBOARD` and `HORIZON_LAUNCHER_DESKTOP` pointing into the scratch home. Never write to
`~/.local/share/{applications,horizon,horizon-launcher}` or `~/.local/bin`.
- **Mark what an agent posts.** A PR body starts with a line naming the person whose agent opened it and
the tool: `> 🤖 Opened by <login>'s AI agent (<tool, model>), not by <login> personally.`, where `<login>`
is the GitHub account the PR is opened from (`gh api user --jq .login`). Issues say "Filed by", reviews
"Review by". Every comment starts with `🤖 Agent:`. Write only as the person you work for: the lines on
this page that name Ludovic are for his own agents (account `ludovic111`), never for anyone else's.
- **Mark what an agent posts.** A PR body starts with a line naming whose agent opened it and with what.
Ludovic's agents write `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, and a
contributor's agent names its own person and tool (issues: "Filed by", reviews: "Review by"). Every
comment starts with `🤖 Agent:`. Never write as Ludovic or as anyone else.
- **Attribution.** Commits end with a `Co-Authored-By:` line for the agent that wrote them, and PR bodies
with that agent's own "Generated with" line. Example, Ludovic's agents (Claude Code on `ludovic111`):
first line `> 🤖 Opened by Ludovic's AI agent (Claude), not by Ludovic himself.`, commits
`Co-Authored-By: Claude <model> <[email protected]>`, last line
with that agent's own "Generated with" line. Ludovic's agents use
`Co-Authored-By: Claude <model> <[email protected]>` and
`🤖 Generated with [Claude Code](https://claude.com/claude-code)`.
- Everything players run is Rust. Python/Java only for dev tools and harness drivers in `tools/`.
- Horizon-only features follow [docs/design-system.md](docs/design-system.md) and are off by default where
@@ -30,8 +28,6 @@ Feature → files → harness for the most-changed areas: [docs/architecture.md]
change), none for a fix. Agents never add `release-now`: the maintainer decides it. Merges ship in batches of 5, or after
6 hours ([docs/release-flow.md](docs/release-flow.md)).
- Contributors first: `gh pr list --state open --search <area>` before you start; never duplicate theirs.
- **Claim before you start**: comment `/claim` on the issue (no issue yet: open one, then claim it). An assigned
issue is taken: pick another. `/unclaim` when you stop; a claim with no open PR linking it is released after 5 days.
## Crates
@@ -39,12 +35,11 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
| Crate | Owns |
|---|---|
| `horizon-client` | The game: a lib (`src/lib.rs`, ~100 flat modules: gameplay, networking, title screens) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
| `horizon-client` | The game: a lib (`src/lib.rs`, ~170 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
| `horizon-items` | Blocks and items below gameplay: `blocks.rs` (block facts), `items.rs`, `item_data.rs` (components), `enchant.rs`, `cooldowns.rs`, `bundle.rs`, `item_nbt.rs`. Re-exported as `horizon_client::items`... |
| `horizon-command` | Command parsing (Brigadier): the vanilla tree, argument types, selectors, suggestions, the tree's network form. Re-exported as `horizon_client::command` |
| `horizon-client-core` | The client lib's bottom layer: `text.rs`, `lang.rs`, `snbt.rs`, `nbt_path.rs`, `component.rs`, `scoreboard.rs`, `bossbar.rs`, `gamerules.rs`, `block_entity_nbt.rs`, registry/particle/sound tables. Re-exported under the old paths (`horizon_client::text`...) |
| `horizon-client-input` | Key bindings and key names, toggle keys, mouse options, controller settings and glyphs, the clipboard, window options (`keybinds.rs`, `gamepad.rs`, `mouse.rs`, `window.rs`...). Re-exported under the old paths |
| `horizon-client-render` | The client's world data, rendering and screens (chunks, meshing, light, streaming, `gfx`, HUD, menus, settings): ~80 modules that horizon-client re-exports under the same paths. Nothing in it reaches gameplay |
| `horizon-world` | Vanilla world data with no gameplay loop: NBT, regions, chunks, `datafix/`, `worldgen/`, `level/` (server-side block behaviour, ticks, redstone), entity physics, items, effects, food, damage |
| `horizon-core` | Simulation primitives: Java `Random`s, `jmath` (HotSpot-exact `Math`), positions, noise, density, paletted storage, `version.rs` (the pinned version) |
| `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` |
@@ -52,9 +47,8 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
| `horizon-prepare` | Builds `.local/horizon-client/26.3` from the player's own Minecraft install (runs the Java exporters) |
| `horizon-server` | `horizon-server`: `server.toml`, CLI, supervisor of the headless game ([docs/hosting.md](docs/hosting.md)) |
| `horizon-server-files` | `server.properties`, eula, ops/whitelist/bans, usercache |
| `horizon-anticheat` | The dedicated server's anticheat, off by default: `[anticheat]` settings, violation levels, the checks' rules; the hub runs them (`lan/anticheat.rs`) ([docs/anticheat.md](docs/anticheat.md)) |
| `horizon-friends`, `horizon-relay` | Play with Friends: invite codes, encrypted tunnel, the relay ([docs/play-with-friends.md](docs/play-with-friends.md)) |
| `horizon-mods`, `cargo-horizon-mod` | Content mods (`.hmod`: manifest, content fence, no code), the registry index and `.hpack`, and `cargo horizon-mod` (`new`, `build`, `run`, `check`, `registry`) ([docs/mods.md](docs/mods.md)). Code mods are native, built by the launcher ([docs/native-mods.md](docs/native-mods.md)) |
| `horizon-mods`, `horizon-mod-sdk`, `cargo-horizon-mod` | Sandboxed WebAssembly mods: runtime, SDK + WIT, `cargo horizon-mod` ([docs/mods.md](docs/mods.md)) |
| `horizon-port-pack` | Porting Java modpacks ([docs/modpacks.md](docs/modpacks.md)) |
| `horizon-shader-api` | Horizon's own WGSL shader packs ([docs/api/shaders.md](docs/api/shaders.md)): `horizon-shaders.toml`, the `.hshader` package; shared by the game, the launcher and the registry |
| `horizon-shaders` | Shader packs (the `shaders/` folder format), rebuilt clean-room from a written spec of the format; no wgpu |
@@ -74,12 +68,12 @@ reads `README.md`, `launcher/links.json`, `docs/api/`, `roadmap/roadmap.json` an
python3 tools/pr_ready.py # the self-check: fmt, clippy -D warnings, touched crates' tests, harnesses; paste its block in the PR
python3 tools/pr_ready.py --quick # same without harnesses
cargo test -p horizon-client --lib --bins --tests # skips the 104 examples (pr_ready does this); `--doc` separately
cargo test -p horizon-client --lib mod_content::tests:: -- --ignored # the 5 slow content-root tests, #[ignore]d; pr_ready runs them when mod content, assets, blocks or items change
cargo test -p horizon-client --features horizon-client/mods --lib mod_content::tests:: -- --ignored # the 5 slow content-root tests, #[ignore]d; pr_ready runs them when mod content, assets, blocks or items change
cargo build --profile fast -p horizon-client # optimized, quick to link: use it to play or run lan_e2e
python3 tools/parity.py --changed origin/main # the harnesses your branch can affect (CI's parity job)
python3 tools/parity.py --changed-files paths.txt --list # which harnesses cover these files, without running them
python3 tools/parity.py mob_ai sculk # named harnesses
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host)
python3 tools/lan_e2e.py --check chest # two real games over LAN (server-thread host); --in-frame compares the fallback
python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
```
@@ -94,6 +88,9 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
- What a change reruns (of 329 harnesses, measured 2026-10-23): a file of the game binary (`game.rs`, `game/`)
~25, a file of the client lib ~103, of `horizon-world` ~103–109, of `horizon-core` ~119. Plan for it.
- Rust integration tests: `crates/horizon-client/tests/` (`lan_bot.rs`, `generation_saves.rs`, `streaming_meshes.rs`).
- **macOS:** `cargo build/test --workspace` may fail to link the two wasm guest cdylibs (undefined
`horizon:mods/events` symbols) until #1446 lands: add `--exclude coords-hud --exclude predator-missile --exclude horizon-mods-test-guest --exclude horizon-mods-test-ui-guest`.
Their real check is `cargo test -p horizon-mods` (builds them for `wasm32-unknown-unknown`).
- Linux needs `libasound2-dev libudev-dev`; `--no-default-features` drops audio and controllers (the server build).
- Run and drive the game (starts the `horizon-client` beside `horizon-ctl`; other arguments go to the game):
`target/fast/horizon-ctl --socket $PWD/ctl.sock launch --world W --creative --offscreen --wait --resources $PWD/.local/horizon-client/26.3`,
@@ -102,9 +99,6 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
## Vanilla reference
- Start parity work from the port ledger, not grep: `python3 tools/port_ledger.py issue N` (or `where
Class.method`, `what file:line`), and `check --base origin/main` before the PR. How:
[.claude/skills/vanilla-parity/SKILL.md](.claude/skills/vanilla-parity/SKILL.md), [docs/port-ledger.md](docs/port-ledger.md).
- Decompiled sources: `.local/minecraft/26.3/sources/{client,server}/` (`python3 tools/lab.py decompile`).
- Bytecode queries (callers through lambdas, every overload):
`python3 tools/rea_vanilla.py method net.minecraft.world.level.block.DispenserBlock dispenseFrom`
@@ -116,8 +110,7 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
## horizon-client: where things live
`L:` = lib (`crates/horizon-client/src/`, or `crates/horizon-client-render/src/` for the modules that crate holds, under
the same `horizon_client::<module>` paths), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see
`L:` = lib (`crates/horizon-client/src/`), `G:` = bin (`crates/horizon-client/src/game/`). The lib can't see
`Game`; bin code reaches the lib as `horizon_client::<module>`.
| Subsystem | Files |
@@ -136,7 +129,7 @@ the same `horizon_client::<module>` paths), `G:` = bin (`crates/horizon-client/s
| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) |
| LAN host / server side | L: `lan/` (`conn.rs` handshake + login threads, `hub.rs` + `hub/` play state, `chunks.rs`, `entity.rs`, `tracking.rs`, `guest.rs`, `playerdata.rs`); G: `lan.rs` (`LanHost`), `lan_actions.rs` (`fn as_guest`, `fn tick_guests`), `lan_*.rs` per feature, `lan_entities.rs` (tracked entities) |
| Integrated server | G: `integrated.rs` (the server thread), `levels.rs` (one level per dimension, `fn tick_server`), `server_travel.rs` |
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server`, `horizon-anticheat` (L: `lan/anticheat.rs`) |
| Dedicated server | G: `dedicated.rs`, `dedicated/status.rs`; crates `horizon-server-files`, `horizon-server` |
| Save and load | L: `save.rs` (level.dat, regions, playerdata), `entity_nbt.rs`, `options_file.rs`; `horizon-client-core/src/block_entity_nbt.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` |
| Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; crate `horizon-client-input` (`keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `clipboard.rs`); L: `osk.rs`; G: `pad.rs`, `pad_menu.rs` |
| Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
@@ -169,18 +162,17 @@ the same `horizon_client::<module>` paths), `G:` = bin (`crates/horizon-client/s
"Server thread" with one level per dimension; the window joins it as a client through memory (`remote`),
exactly as a LAN guest or a dedicated server's player does. This is what players run. Open
`[server-thread]` issues list the gaps left.
2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`): DEPRECATED, never use it, it
will be removed soon.** The window's `Game` ticks the world itself, one level that follows the player
(`fn enter_dimension`). Compatibility does not matter: don't add features or fixes for it, don't write new
tests against it, and move code off it when you touch it. The deterministic rule fixtures still run on it
until they are ported.
2. **In-frame (`--in-frame`, `--no-server-thread` or `HORIZON_SERVER_THREAD=0`):** the window's `Game` ticks
the world itself, one level that follows the player (`fn enter_dimension`). Deterministic rule fixtures still use this path; player-facing integration uses the default server thread.
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test the server
thread when you touch player-facing gameplay:
LAN guests and dedicated servers always use the server code, so a fix there serves both. Test both paths
when you touch player-facing gameplay:
```sh
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T # server thread
cargo run --profile fast -p horizon-client -- --resources .local/horizon-client/26.3 --world T --in-frame # in-frame
python3 tools/lan_e2e.py --check <name> # host on its server thread, guest is a server client
python3 tools/lan_e2e.py --in-frame --check <name> # comparison (portals, levels, distance, lava need server-thread mode)
python3 tools/parity.py dedicated_server server_entities server_player_damage
```
+3 -20
View File
@@ -74,19 +74,6 @@ including examples. The dependency scope includes optional, platform, build and
Tests run library, binary, integration and doc tests without building unrelated example executables. Shared Cargo
configuration and toolchain changes select the whole workspace; CI also keeps its workspace-wide checks.
## Claim before you start
Work is tracked in GitHub issues, and an issue that is assigned is taken (so is one with the `in progress` label:
claimed on Discord with Kira's `/claim`): pick another, or ask its holder in the thread. Before you start, comment
**`/claim`** on the issue; you are assigned at once, no role needed. No issue for your work yet? Open one (a line is
enough), then claim it. `/unclaim` gives it back.
A claim with no open pull request linking the issue (`Fixes #123` in the description, or a draft) is released after
5 days, with a comment: open a draft early. You can hold 5 open issues at a time. Agents claim the same way.
When your pull request changes the same functions as another open one, or closes the same issue, a bot comment names
it (edited on every push, never repeated): talk to its author in the thread before you both finish the same work.
## Pull requests
- **Small.** One change per pull request, under about 500 lines of code where you can; split bigger work into
@@ -95,12 +82,8 @@ it (edited on every push, never repeated): talk to its author in the thread befo
can see.
- **Tick "Allow edits by maintainers".** When something small is left (a lint, a rebase, a nit) we push the fixup
ourselves instead of sending it back to you; only design questions come back.
- **Tick its kind** in the template: `parity` (Horizon now does what vanilla does), `bug` (a crash or breakage),
`perf`, `feature` (new for players), `extra` (Horizon-only, off by default), `tooling` or `docs`. A workflow sets
that label, and area labels (`launcher`, `mobs`, `worldgen`, `rendering`...) from the paths you change.
`label:parity` is the list of real progress toward vanilla.
- **Release labels** (we set them if you can't): `feature` also puts it under "New" in the release notes,
`skip-release` when players see no change (tooling, docs, tests), nothing for a fix.
- **Labels** (we set them if you can't): `feature` when players get something new (it appears under "New" in the
release notes), `skip-release` when players see no change (tooling, docs, tests), nothing for a fix.
`release-now` is for crash fixes that shouldn't wait. pr_ready suggests one.
Who reviews and merges: the Horizon Team, on CI for ordinary pull requests; risky ones (saves, network, world
@@ -119,4 +102,4 @@ new pushes, we add it again.
## Talk to us
[Discord](https://discord.gg/HcTeMZxe5E) for questions and ideas, [issues](https://github.com/horizon-rust/horizon/issues)
for bugs. To take something on, `/claim` its issue ([above](#claim-before-you-start)).
for bugs. If you want to take something on, say so in its issue so nobody else starts the same work.
Generated
+813 -86
View File
File diff suppressed because it is too large. Load diff
+13 -2
View File
@@ -9,11 +9,9 @@ members = [
"crates/horizon-client",
"crates/horizon-client-core",
"crates/horizon-client-input",
"crates/horizon-client-render",
"crates/horizon-command",
"crates/horizon-items",
"crates/horizon-server-files",
"crates/horizon-anticheat",
"crates/horizon-server",
"crates/horizon-bots",
"crates/horizon-assets",
@@ -24,13 +22,26 @@ members = [
"crates/horizon-bench",
"crates/horizon-friends",
"crates/horizon-relay",
"crates/horizon-mod-sdk",
"crates/horizon-mods",
"crates/horizon-mods/tests/guest",
"crates/horizon-mods/tests/ui_guest",
"crates/cargo-horizon-mod",
"crates/horizon-port-pack",
"crates/horizon-shaders",
"crates/horizon-shader-api",
"crates/horizon-release-sign",
"crates/horizon-mod-sdk/examples/coords-hud",
"crates/horizon-mod-sdk/examples/predator-missile",
"crates/horizon-mod-sdk/examples/welcome",
"crates/horizon-mod-sdk/examples/beacons",
"mods/official/fps-overlay",
"mods/official/keystrokes",
"mods/official/far-view",
"mods/official/minimap",
"mods/official/zoom",
"xtask",
"mods/official/recipes",
]
resolver = "2"
+7 -15
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="docs/media/banner.webp" alt="Horizon: Minecraft: Java Edition 26.3, rewritten in Rust and checked against vanilla by more than 300 differential harnesses" width="100%">
<img src="docs/media/banner.webp" alt="Horizon: Minecraft: Java Edition 26.3, rewritten in Rust and checked against vanilla by 281 differential harnesses" width="100%">
</p>
<p align="center">
@@ -7,7 +7,6 @@
<img src="https://img.shields.io/badge/Minecraft-Java%2026.3-5D9C3F" alt="Minecraft Java 26.3">
<img src="https://img.shields.io/badge/Rust-stable-B7410E?logo=rust&logoColor=white" alt="Rust">
<img src="https://img.shields.io/badge/vanilla%20parity-100%25-F0795A" alt="Vanilla parity 100%">
<a href="#project-status"><img src="https://img.shields.io/badge/player--visible%20gaps-833%20open-F0795A" alt="Player-visible gaps open"></a>
<img src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS%20%7C%20Windows-2A2470" alt="Linux, macOS and Windows">
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-3B2F7E" alt="MIT license"></a>
</p>
@@ -24,15 +23,15 @@
# Horizon
Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that reads the same worlds, follows the same rules and generates the same terrain as the Java game, and is checked against it by more than 300 differential harnesses. You play it through a small launcher, on the files from your own copy of Minecraft. It is free, open source and unofficial.
Horizon is Minecraft: Java Edition 26.3 rewritten in Rust: a native game that reads the same worlds, follows the same rules and generates the same terrain as the Java game, and is checked against it by 281 differential harnesses. You play it through a small launcher, on the files from your own copy of Minecraft. It is free, open source and unofficial.
> Not an official Minecraft product. Not approved by or associated with Mojang or Microsoft. Horizon contains no Minecraft code, assets or data: you need your own legally obtained copy of Minecraft: Java Edition 26.3.
## Download
Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/horizon-rust/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs the game and keeps it up to date with each new build (Horizon ships on one channel, the Nightly), prepares its files from your copy of Minecraft (your own install, or downloaded from Mojang for your account), and updates itself.
Horizon is installed through **the Horizon launcher**. Get it from [playhorizon.dev](https://playhorizon.dev) (the Download button picks your system) or from [the launcher releases](https://github.com/horizon-rust/horizon/releases?q=launcher-v&expanded=true), for Linux x86-64, macOS on Apple Silicon or Windows x64. The launcher installs and updates the game, prepares its files from your copy of Minecraft (your own install, or downloaded from Mojang for your account), and updates itself.
**You need** a Microsoft account that owns Minecraft: Java Edition (the launcher signs in with it, as other launchers do; see [Microsoft account](docs/microsoft-account.md)) and a GPU with Vulkan or OpenGL 3.3 on Linux, Vulkan or DirectX 12 on Windows, or any Apple Silicon Mac. Nothing else: with no Minecraft on your computer, Play downloads 26.3 and the Java it needs from Mojang for your account, as the official launcher does, then prepares it once. An install you already have (the official launcher, Prism, MultiMC and other launchers all work) is used instead. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
**You need** a Microsoft account that owns Minecraft: Java Edition (the launcher signs in with it, as other launchers do; see [Microsoft account](docs/microsoft-account.md)) and a GPU with Vulkan on Linux and Windows, or any Apple Silicon Mac. Nothing else: with no Minecraft on your computer, Play downloads 26.3 and the Java it needs from Mojang for your account, as the official launcher does, then prepares it once. An install you already have (the official launcher, Prism, MultiMC and other launchers all work) is used instead. Step by step, with macOS's first-open prompt and the first launch: [Install and first launch](https://playhorizon.dev/docs/install).
<table>
<tr>
@@ -47,9 +46,9 @@ The [documentation](https://playhorizon.dev/docs/) covers each of these.
- **The game:** singleplayer with vanilla's world generation, mobs, villagers, raids, redstone, every command, the HUD and the recipe book, on saves in vanilla's format. Worlds from 1.8 to 26.2 are upgraded as vanilla does. [Status table](#project-status).
- **Horizon's own extras:** new menus (vanilla's are one setting away), graphics presets, distant terrain up to 1024 chunks, controller support, optional zoom, minimap and more, all off by default where they would change the vanilla look. See [Settings](https://playhorizon.dev/docs/settings).
- **Resource packs and data packs:** resource packs work, and data packs load functions, predicates, item modifiers and world generation, taller levels included (vanilla's biomes for now).
- **Resource packs and data packs:** resource packs work, and data packs load functions, predicates and item modifiers.
- **Playing with others:** invite friends from the pause menu's Friends button with a code, Open to LAN, and joining servers, online-mode ones with the Microsoft account the launcher signs in with. See [Multiplayer](https://playhorizon.dev/docs/multiplayer).
- **Mods:** content mods add blocks, items and data, and native mods change the game's own Rust code, built by the launcher on your copy, with no Rust to install. Horizon's own (Zoom, FPS Counter, Keystrokes, Minimap, Recipes and Coordinates HUD) are native mods. Java mod jars do not run in Horizon. See [Mods and data packs](https://playhorizon.dev/docs/mods).
- **Mods:** Horizon has its own mod system (Rust compiled to WebAssembly). Java mod jars do not run. See [Mods and data packs](https://playhorizon.dev/docs/mods).
Screenshots, captured in the Rust client itself with vanilla assets and no mods or shaders:
@@ -128,8 +127,6 @@ It runs rustfmt, clippy with warnings denied, the tests of the crates you touche
## Project status
**Player-visible gaps: 833 open** of the 833 the [port ledger](tools/port_ledger.py) found, reading every vanilla 26.3 method against Horizon's code: vanilla behaviour a player would notice that Horizon doesn't have yet. By area: Screens, HUD and client packets [197](https://github.com/horizon-rust/horizon/issues/3518); Entity and block rendering, models [129](https://github.com/horizon-rust/horizon/issues/3519); Animals [110](https://github.com/horizon-rust/horizon/issues/3512); Server and players on the server [106](https://github.com/horizon-rust/horizon/issues/3520); Blocks, redstone and fluids [86](https://github.com/horizon-rust/horizon/issues/3516); Entities, projectiles, vehicles and decorations [64](https://github.com/horizon-rust/horizon/issues/3514); Monsters and bosses [53](https://github.com/horizon-rust/horizon/issues/3513); Mob AI, villagers and raids [35](https://github.com/horizon-rust/horizon/issues/3521); World, world generation and saves [32](https://github.com/horizon-rust/horizon/issues/3517); Items, enchantments and inventories [21](https://github.com/horizon-rust/horizon/issues/3515). This number goes down as gaps close (`tools/parity_gaps.py`); the harness results below say that what is tested matches.
The table below is the project's own audit of each subsystem. Every subsystem now matches vanilla in every harness that compares it. 100% means 100% of what the harnesses compare, not proof that nothing else differs. The remaining known differences are listed below.
### Java parity: 100%
@@ -142,11 +139,6 @@ average; `tests/test_parity.py` keeps it in sync with this table. Last audited
rerun whenever one of its inputs changed, and the Mac mini now runs every one of
them too (Rust uses Java's own float maths on each platform).
The harnesses measure behaviour. A second measure is method by method: the [port ledger](tools/port_ledger.py)
lists every method of vanilla 26.3 next to the Rust functions that port it, with a verdict for each one
(ported, folded into another function, missing, or needing no port), and the untested ports. Run
`python3 tools/port_ledger.py build`, then `coverage`, with the vanilla data in `.local/`.
| Subsystem | Score | Main gaps |
| --- | ---: | --- |
| Window, input and game loop | 1 | None: the game loop, options, camera, auto-jump, toggle sprint/sneak, local input and the frame limiter match vanilla |
@@ -166,7 +158,7 @@ lists every method of vanilla 26.3 next to the Rust functions that port it, with
### Known issues
Skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; item tooltips lack attribute lines.
Skins served over https show the default skin unless already cached; pack icons show the unknown-pack texture in game; the creative hotbar keys (C/X) aren't wired to the hotbar loader; item tooltips lack attribute lines.
## Licence
+436 -372
View File
File diff suppressed because it is too large. Load diff
-39
View File
@@ -19,42 +19,3 @@ by The Pixelify Sans Project Authors, licensed under the SIL Open Font License 1
[Pixelarticons](https://github.com/halfmage/pixelarticons) by Gerrit Halfmann, under the MIT
license (`crates/horizon-theme/icons/pixel/LICENSE-pixelarticons.txt`). `star.svg` is Horizon's own, drawn on
the same grid.
## AMD FidelityFX SDK (FSR 3.1 frame generation)
`crates/horizon-client-render/src/gfx/frame_gen/optical_flow.wgsl` is a port to WGSL of the
optical flow shaders of the [AMD FidelityFX SDK](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK)
1.1.4 (`sdk/include/FidelityFX/gpu/opticalflow`, at commit
[c6efa6bf7f20](https://github.com/GPUOpen-LibrariesAndSDKs/FidelityFX-SDK/tree/c6efa6bf7f2027b3ec94f28578bb5965eabb9e55)),
and `optical_flow.rs` follows the SDK's `sdk/src/components/opticalflow/ffx_opticalflow.cpp`
(its passes, their order and their dispatch sizes). Copyright (C) 2024 Advanced Micro Devices,
Inc., under the MIT license, whose text heads both files. AMD and FidelityFX are AMD's
trademarks; Horizon is not affiliated with AMD.
## Mod loader logos
The launcher shows the logo of the mod loader an instance plays with.
- `launcher/assets/logos/quilt.png` is the Quilt mini icon (`brand/128png/quilt_mini_icon_transparent.png`)
from [QuiltMC/art](https://github.com/QuiltMC/art), by the Quilt Project, dedicated to the public
domain under [CC0 1.0](https://creativecommons.org/publicdomain/zero/1.0/).
- `launcher/assets/logos/neoforge.png` is NeoForged's icon (`art/neoforged_icon_16x16.png`) from
[neoforged/.github](https://github.com/neoforged/.github/tree/main/art), © the NeoForged team,
created by Ridanisaurus, under [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). It is
unmodified (the launcher scales it up by whole pixels).
- Fabric's and Forge's icons are not shipped: neither publishes a license for its logo. The launcher
fetches them from their own sites when an instance needs them
([fabric-loader's icon](https://github.com/FabricMC/fabric-loader/blob/master/src/main/resources/assets/fabricloader/icon.png),
[files.minecraftforge.net's](https://files.minecraftforge.net/)).
Each logo belongs to its project. Showing it says which loader an instance runs; it does not mean
the project endorses Horizon.
## Sign in with Microsoft
The launcher's sign-in buttons follow Microsoft's published branding guidelines for apps that sign in
with Microsoft accounts
([Sign in with Microsoft branding](https://learn.microsoft.com/en-us/entra/identity-platform/howto-add-branding-in-apps)).
The four-square Microsoft symbol in `launcher/src/microsoft.rs` reproduces the squares, positions and
colours of Microsoft's official `ms-symbollockup_mssymbol_19.svg` from that page, unmodified. Microsoft
and its logo are trademarks of the Microsoft group of companies; Horizon is not endorsed by Microsoft.
@@ -1,773 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T01:13:01Z",
"app": {
"name": "horizon-client",
"version": "v0.2.97",
"commit": null
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080",
"vendor": "nvidia",
"driver": "NVIDIA 617.42",
"backend": "vulkan",
"kind": "discrete"
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 16,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 3158.208,
"stdev": 215.77,
"min": 3023.046,
"max": 3407.049,
"ci95": 536.046
},
"startup.world_ms": {
"n": 3,
"mean": 7170.164,
"stdev": 557.958,
"min": 6703.242,
"max": 7788.08,
"ci95": 1386.157
},
"chunks.village.load_ms": {
"n": 3,
"mean": 1694.647,
"stdev": 41.285,
"min": 1653.122,
"max": 1735.687,
"ci95": 102.566
},
"chunks.village.meshed_count": {
"n": 3,
"mean": 23544.0,
"stdev": 47.127,
"min": 23495.0,
"max": 23589.0,
"ci95": 117.081
},
"fps.village.avg_fps": {
"n": 3,
"mean": 1711.652,
"stdev": 77.412,
"min": 1623.403,
"max": 1768.093,
"ci95": 192.317
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 593.407,
"stdev": 32.279,
"min": 571.485,
"max": 630.473,
"ci95": 80.191
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 358.473,
"stdev": 27.832,
"min": 326.35,
"max": 375.353,
"ci95": 69.143
},
"memory.village.gpu_mb": {
"n": 3,
"mean": 631.813,
"stdev": 8.381,
"min": 626.803,
"max": 641.489,
"ci95": 20.822
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 2521.363,
"stdev": 291.624,
"min": 2336.881,
"max": 2857.57,
"ci95": 724.493
},
"chunks.forest.meshed_count": {
"n": 3,
"mean": 27346.667,
"stdev": 57.934,
"min": 27306.0,
"max": 27413.0,
"ci95": 143.927
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 2423.783,
"stdev": 55.746,
"min": 2386.353,
"max": 2487.851,
"ci95": 138.493
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 709.165,
"stdev": 66.309,
"min": 638.666,
"max": 770.286,
"ci95": 164.734
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 401.039,
"stdev": 40.413,
"min": 354.472,
"max": 426.929,
"ci95": 100.399
},
"memory.forest.gpu_mb": {
"n": 3,
"mean": 705.008,
"stdev": 6.062,
"min": 698.466,
"max": 710.435,
"ci95": 15.06
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 2094.909,
"stdev": 521.225,
"min": 1758.024,
"max": 2695.274,
"ci95": 1294.9
},
"chunks.ocean.meshed_count": {
"n": 3,
"mean": 24312.667,
"stdev": 261.934,
"min": 24116.0,
"max": 24610.0,
"ci95": 650.732
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 2201.125,
"stdev": 73.595,
"min": 2153.6,
"max": 2285.897,
"ci95": 182.834
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 553.968,
"stdev": 100.955,
"min": 445.599,
"max": 645.355,
"ci95": 250.806
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 325.078,
"stdev": 131.154,
"min": 177.4,
"max": 427.981,
"ci95": 325.831
},
"memory.ocean.gpu_mb": {
"n": 3,
"mean": 652.944,
"stdev": 5.177,
"min": 647.51,
"max": 657.818,
"ci95": 12.862
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 3304.58,
"stdev": 134.041,
"min": 3155.996,
"max": 3416.409,
"ci95": 333.003
},
"chunks.mountain.meshed_count": {
"n": 3,
"mean": 26591.0,
"stdev": 57.472,
"min": 26525.0,
"max": 26630.0,
"ci95": 142.779
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 1961.086,
"stdev": 39.725,
"min": 1921.241,
"max": 2000.69,
"ci95": 98.69
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 536.973,
"stdev": 38.828,
"min": 495.61,
"max": 572.635,
"ci95": 96.461
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 296.586,
"stdev": 30.236,
"min": 275.859,
"max": 331.281,
"ci95": 75.118
},
"memory.mountain.gpu_mb": {
"n": 3,
"mean": 896.941,
"stdev": 5.177,
"min": 891.506,
"max": 901.814,
"ci95": 12.862
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 1458.578,
"stdev": 3.229,
"min": 1455.32,
"max": 1461.777,
"ci95": 8.022
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 1236.28,
"stdev": 4.869,
"min": 1230.701,
"max": 1239.672,
"ci95": 12.096
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 21218,
"seconds": 12.0,
"avg_fps": 1768.093,
"low_1pct_fps": 630.473,
"low_01pct_fps": 375.353,
"p50_ms": 0.537,
"p95_ms": 0.846,
"p99_ms": 1.222,
"p999_ms": 2.081,
"max_ms": 6.256,
"cpu_p50_ms": 0.38,
"gpu_p50_ms": 0.104,
"histogram": [
20695,
499,
22,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 19482,
"seconds": 12.001,
"avg_fps": 1623.403,
"low_1pct_fps": 578.262,
"low_01pct_fps": 373.717,
"p50_ms": 0.586,
"p95_ms": 0.95,
"p99_ms": 1.357,
"p999_ms": 2.158,
"max_ms": 7.35,
"cpu_p50_ms": 0.445,
"gpu_p50_ms": 0.104,
"histogram": [
18729,
713,
38,
1,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 20922,
"seconds": 12.0,
"avg_fps": 1743.46,
"low_1pct_fps": 571.485,
"low_01pct_fps": 326.35,
"p50_ms": 0.526,
"p95_ms": 0.883,
"p99_ms": 1.313,
"p999_ms": 2.14,
"max_ms": 12.027,
"cpu_p50_ms": 0.379,
"gpu_p50_ms": 0.104,
"histogram": [
20308,
582,
28,
2,
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 29855,
"seconds": 12.0,
"avg_fps": 2487.851,
"low_1pct_fps": 770.286,
"low_01pct_fps": 421.717,
"p50_ms": 0.365,
"p95_ms": 0.619,
"p99_ms": 0.948,
"p999_ms": 1.717,
"max_ms": 9.446,
"cpu_p50_ms": 0.232,
"gpu_p50_ms": 0.157,
"histogram": [
29607,
233,
13,
0,
0,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 28766,
"seconds": 12.0,
"avg_fps": 2397.145,
"low_1pct_fps": 718.542,
"low_01pct_fps": 426.929,
"p50_ms": 0.374,
"p95_ms": 0.662,
"p99_ms": 1.016,
"p999_ms": 1.858,
"max_ms": 6.379,
"cpu_p50_ms": 0.239,
"gpu_p50_ms": 0.157,
"histogram": [
28457,
293,
14,
0,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 28637,
"seconds": 12.0,
"avg_fps": 2386.353,
"low_1pct_fps": 638.666,
"low_01pct_fps": 354.472,
"p50_ms": 0.373,
"p95_ms": 0.704,
"p99_ms": 1.159,
"p999_ms": 1.952,
"max_ms": 14.388,
"cpu_p50_ms": 0.233,
"gpu_p50_ms": 0.157,
"histogram": [
28198,
415,
18,
5,
0,
0,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 25968,
"seconds": 12.001,
"avg_fps": 2163.877,
"low_1pct_fps": 570.949,
"low_01pct_fps": 369.854,
"p50_ms": 0.408,
"p95_ms": 0.767,
"p99_ms": 1.339,
"p999_ms": 2.38,
"max_ms": 3.329,
"cpu_p50_ms": 0.271,
"gpu_p50_ms": 0.141,
"histogram": [
25383,
534,
47,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 25843,
"seconds": 12.0,
"avg_fps": 2153.6,
"low_1pct_fps": 445.599,
"low_01pct_fps": 177.4,
"p50_ms": 0.413,
"p95_ms": 0.725,
"p99_ms": 1.309,
"p999_ms": 3.451,
"max_ms": 12.071,
"cpu_p50_ms": 0.275,
"gpu_p50_ms": 0.142,
"histogram": [
25375,
373,
56,
22,
1,
7,
3,
5,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 27431,
"seconds": 12.0,
"avg_fps": 2285.897,
"low_1pct_fps": 645.355,
"low_01pct_fps": 427.981,
"p50_ms": 0.388,
"p95_ms": 0.693,
"p99_ms": 1.163,
"p999_ms": 2.041,
"max_ms": 3.068,
"cpu_p50_ms": 0.254,
"gpu_p50_ms": 0.141,
"histogram": [
27036,
363,
31,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 23536,
"seconds": 12.0,
"avg_fps": 1961.326,
"low_1pct_fps": 542.675,
"low_01pct_fps": 331.281,
"p50_ms": 0.436,
"p95_ms": 0.856,
"p99_ms": 1.425,
"p999_ms": 2.22,
"max_ms": 9.458,
"cpu_p50_ms": 0.296,
"gpu_p50_ms": 0.14,
"histogram": [
22819,
671,
40,
5,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 23056,
"seconds": 12.001,
"avg_fps": 1921.241,
"low_1pct_fps": 495.61,
"low_01pct_fps": 282.617,
"p50_ms": 0.44,
"p95_ms": 0.911,
"p99_ms": 1.516,
"p999_ms": 2.543,
"max_ms": 14.342,
"cpu_p50_ms": 0.299,
"gpu_p50_ms": 0.141,
"histogram": [
22198,
783,
65,
7,
0,
2,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 24009,
"seconds": 12.0,
"avg_fps": 2000.69,
"low_1pct_fps": 572.635,
"low_01pct_fps": 275.859,
"p50_ms": 0.436,
"p95_ms": 0.819,
"p99_ms": 1.274,
"p999_ms": 2.085,
"max_ms": 14.003,
"cpu_p50_ms": 0.297,
"gpu_p50_ms": 0.14,
"histogram": [
23421,
560,
22,
0,
1,
0,
2,
2,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "horizon-win-9800x3d-5080"
}
@@ -1,773 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T18:55:59Z",
"app": {
"name": "horizon-client",
"version": "v0.2.97",
"commit": null
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080",
"vendor": "nvidia",
"driver": "NVIDIA 617.42",
"backend": "vulkan",
"kind": "discrete"
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 32,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 2897.812,
"stdev": 82.455,
"min": 2844.677,
"max": 2992.8,
"ci95": 204.846
},
"startup.world_ms": {
"n": 3,
"mean": 10503.454,
"stdev": 493.592,
"min": 9934.491,
"max": 10816.992,
"ci95": 1226.251
},
"chunks.village.load_ms": {
"n": 3,
"mean": 3717.47,
"stdev": 1330.649,
"min": 2942.872,
"max": 5253.954,
"ci95": 3305.783
},
"chunks.village.meshed_count": {
"n": 3,
"mean": 47525.333,
"stdev": 1369.122,
"min": 46133.0,
"max": 48870.0,
"ci95": 3401.363
},
"fps.village.avg_fps": {
"n": 3,
"mean": 1163.541,
"stdev": 3.485,
"min": 1159.52,
"max": 1165.693,
"ci95": 8.658
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 415.992,
"stdev": 15.742,
"min": 399.062,
"max": 430.188,
"ci95": 39.108
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 215.549,
"stdev": 34.678,
"min": 177.857,
"max": 246.101,
"ci95": 86.151
},
"memory.village.gpu_mb": {
"n": 3,
"mean": 1833.432,
"stdev": 4.415,
"min": 1828.334,
"max": 1835.997,
"ci95": 10.969
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 5455.049,
"stdev": 593.897,
"min": 4973.659,
"max": 6118.723,
"ci95": 1475.44
},
"chunks.forest.meshed_count": {
"n": 3,
"mean": 82758.0,
"stdev": 413.547,
"min": 82487.0,
"max": 83234.0,
"ci95": 1027.39
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 1389.46,
"stdev": 28.128,
"min": 1371.096,
"max": 1421.843,
"ci95": 69.88
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 504.377,
"stdev": 13.251,
"min": 492.444,
"max": 518.637,
"ci95": 32.919
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 329.682,
"stdev": 47.451,
"min": 294.872,
"max": 383.732,
"ci95": 117.885
},
"memory.forest.gpu_mb": {
"n": 3,
"mean": 1985.175,
"stdev": 6.354,
"min": 1978.907,
"max": 1991.612,
"ci95": 15.786
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 4504.145,
"stdev": 745.393,
"min": 3650.589,
"max": 5026.8,
"ci95": 1851.809
},
"chunks.ocean.meshed_count": {
"n": 3,
"mean": 74927.333,
"stdev": 399.375,
"min": 74476.0,
"max": 75235.0,
"ci95": 992.182
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 1188.639,
"stdev": 10.807,
"min": 1177.005,
"max": 1198.365,
"ci95": 26.849
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 154.773,
"stdev": 3.712,
"min": 151.38,
"max": 158.738,
"ci95": 9.223
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 67.809,
"stdev": 3.032,
"min": 65.903,
"max": 71.305,
"ci95": 7.532
},
"memory.ocean.gpu_mb": {
"n": 3,
"mean": 2084.845,
"stdev": 9.674,
"min": 2074.009,
"max": 2092.615,
"ci95": 24.034
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 9048.431,
"stdev": 344.33,
"min": 8821.41,
"max": 9444.624,
"ci95": 855.432
},
"chunks.mountain.meshed_count": {
"n": 3,
"mean": 89659.667,
"stdev": 87.123,
"min": 89561.0,
"max": 89726.0,
"ci95": 216.442
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 1085.847,
"stdev": 13.819,
"min": 1070.378,
"max": 1096.974,
"ci95": 34.332
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 257.7,
"stdev": 31.437,
"min": 224.366,
"max": 286.814,
"ci95": 78.101
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 107.783,
"stdev": 14.883,
"min": 91.541,
"max": 120.768,
"ci95": 36.975
},
"memory.mountain.gpu_mb": {
"n": 3,
"mean": 2708.833,
"stdev": 9.674,
"min": 2697.997,
"max": 2716.603,
"ci95": 24.034
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2044.895,
"stdev": 10.562,
"min": 2032.875,
"max": 2052.691,
"ci95": 26.238
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 1730.107,
"stdev": 14.764,
"min": 1717.52,
"max": 1746.357,
"ci95": 36.678
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 13986,
"seconds": 12.001,
"avg_fps": 1165.41,
"low_1pct_fps": 399.062,
"low_01pct_fps": 177.857,
"p50_ms": 0.822,
"p95_ms": 1.21,
"p99_ms": 1.691,
"p999_ms": 3.499,
"max_ms": 13.089,
"cpu_p50_ms": 0.665,
"gpu_p50_ms": 0.193,
"histogram": [
12380,
1527,
58,
13,
2,
2,
1,
2,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 13915,
"seconds": 12.001,
"avg_fps": 1159.52,
"low_1pct_fps": 430.188,
"low_01pct_fps": 246.101,
"p50_ms": 0.809,
"p95_ms": 1.212,
"p99_ms": 1.702,
"p999_ms": 3.291,
"max_ms": 6.894,
"cpu_p50_ms": 0.648,
"gpu_p50_ms": 0.192,
"histogram": [
11996,
1839,
59,
17,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 13989,
"seconds": 12.001,
"avg_fps": 1165.693,
"low_1pct_fps": 418.725,
"low_01pct_fps": 222.688,
"p50_ms": 0.816,
"p95_ms": 1.22,
"p99_ms": 1.692,
"p999_ms": 3.264,
"max_ms": 7.781,
"cpu_p50_ms": 0.669,
"gpu_p50_ms": 0.193,
"histogram": [
12321,
1578,
72,
11,
2,
4,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 17063,
"seconds": 12.001,
"avg_fps": 1421.843,
"low_1pct_fps": 502.049,
"low_01pct_fps": 294.872,
"p50_ms": 0.666,
"p95_ms": 0.935,
"p99_ms": 1.549,
"p999_ms": 2.692,
"max_ms": 6.831,
"cpu_p50_ms": 0.533,
"gpu_p50_ms": 0.362,
"histogram": [
16417,
596,
40,
7,
2,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 16454,
"seconds": 12.001,
"avg_fps": 1371.096,
"low_1pct_fps": 492.444,
"low_01pct_fps": 310.443,
"p50_ms": 0.688,
"p95_ms": 0.979,
"p99_ms": 1.556,
"p999_ms": 2.693,
"max_ms": 4.596,
"cpu_p50_ms": 0.553,
"gpu_p50_ms": 0.36,
"histogram": [
15692,
697,
57,
7,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 16506,
"seconds": 12.001,
"avg_fps": 1375.442,
"low_1pct_fps": 518.637,
"low_01pct_fps": 383.732,
"p50_ms": 0.675,
"p95_ms": 1.017,
"p99_ms": 1.605,
"p999_ms": 2.369,
"max_ms": 3.201,
"cpu_p50_ms": 0.54,
"gpu_p50_ms": 0.364,
"histogram": [
15628,
833,
44,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 14381,
"seconds": 12.001,
"avg_fps": 1198.365,
"low_1pct_fps": 154.2,
"low_01pct_fps": 66.219,
"p50_ms": 0.731,
"p95_ms": 1.023,
"p99_ms": 3.003,
"p999_ms": 12.478,
"max_ms": 18.863,
"cpu_p50_ms": 0.596,
"gpu_p50_ms": 0.315,
"histogram": [
13586,
546,
105,
60,
13,
13,
8,
16,
8,
11,
5,
7,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 14287,
"seconds": 12.0,
"avg_fps": 1190.548,
"low_1pct_fps": 158.738,
"low_01pct_fps": 71.305,
"p50_ms": 0.741,
"p95_ms": 1.041,
"p99_ms": 2.9,
"p999_ms": 12.0,
"max_ms": 17.23,
"cpu_p50_ms": 0.602,
"gpu_p50_ms": 0.315,
"histogram": [
13450,
591,
109,
57,
13,
8,
10,
11,
14,
10,
7,
6,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 14124,
"seconds": 12.0,
"avg_fps": 1177.005,
"low_1pct_fps": 151.38,
"low_01pct_fps": 65.903,
"p50_ms": 0.739,
"p95_ms": 1.096,
"p99_ms": 2.928,
"p999_ms": 11.884,
"max_ms": 19.375,
"cpu_p50_ms": 0.604,
"gpu_p50_ms": 0.314,
"histogram": [
13052,
822,
114,
54,
16,
8,
4,
14,
11,
15,
3,
8,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 12845,
"seconds": 12.0,
"avg_fps": 1070.378,
"low_1pct_fps": 224.366,
"low_01pct_fps": 91.541,
"p50_ms": 0.825,
"p95_ms": 1.362,
"p99_ms": 2.325,
"p999_ms": 9.621,
"max_ms": 13.309,
"cpu_p50_ms": 0.689,
"gpu_p50_ms": 0.307,
"histogram": [
10937,
1699,
143,
25,
5,
6,
4,
8,
8,
8,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 13083,
"seconds": 12.001,
"avg_fps": 1090.188,
"low_1pct_fps": 261.921,
"low_01pct_fps": 111.039,
"p50_ms": 0.816,
"p95_ms": 1.335,
"p99_ms": 2.14,
"p999_ms": 8.222,
"max_ms": 11.95,
"cpu_p50_ms": 0.681,
"gpu_p50_ms": 0.306,
"histogram": [
11105,
1812,
112,
21,
5,
5,
5,
6,
11,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 13164,
"seconds": 12.0,
"avg_fps": 1096.974,
"low_1pct_fps": 286.814,
"low_01pct_fps": 120.768,
"p50_ms": 0.822,
"p95_ms": 1.307,
"p99_ms": 1.989,
"p999_ms": 7.701,
"max_ms": 9.429,
"cpu_p50_ms": 0.687,
"gpu_p50_ms": 0.307,
"histogram": [
11280,
1758,
82,
13,
5,
5,
6,
8,
7,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "horizon-win-9800x3d-5080"
}
@@ -1,773 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T18:37:03Z",
"app": {
"name": "horizon-client",
"version": "v0.2.97",
"commit": null
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080",
"vendor": "nvidia",
"driver": "NVIDIA 617.42",
"backend": "vulkan",
"kind": "discrete"
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 8,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 2950.343,
"stdev": 162.732,
"min": 2822.925,
"max": 3133.657,
"ci95": 404.282
},
"startup.world_ms": {
"n": 3,
"mean": 6135.1,
"stdev": 863.831,
"min": 5547.861,
"max": 7126.98,
"ci95": 2146.05
},
"chunks.village.load_ms": {
"n": 3,
"mean": 985.519,
"stdev": 28.184,
"min": 956.244,
"max": 1012.469,
"ci95": 70.019
},
"chunks.village.meshed_count": {
"n": 3,
"mean": 6908.0,
"stdev": 9.849,
"min": 6897.0,
"max": 6916.0,
"ci95": 24.468
},
"fps.village.avg_fps": {
"n": 3,
"mean": 2941.608,
"stdev": 79.283,
"min": 2850.416,
"max": 2994.188,
"ci95": 196.965
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 1271.318,
"stdev": 58.797,
"min": 1203.758,
"max": 1310.917,
"ci95": 146.072
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 839.261,
"stdev": 37.982,
"min": 795.415,
"max": 862.067,
"ci95": 94.36
},
"memory.village.gpu_mb": {
"n": 3,
"mean": 363.984,
"stdev": 0.926,
"min": 363.449,
"max": 365.053,
"ci95": 2.299
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 1350.752,
"stdev": 293.128,
"min": 1106.764,
"max": 1675.913,
"ci95": 728.23
},
"chunks.forest.meshed_count": {
"n": 3,
"mean": 8066.0,
"stdev": 108.885,
"min": 7986.0,
"max": 8190.0,
"ci95": 270.508
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 3494.693,
"stdev": 110.997,
"min": 3389.894,
"max": 3610.993,
"ci95": 275.755
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 1295.14,
"stdev": 159.638,
"min": 1148.468,
"max": 1465.171,
"ci95": 396.596
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 859.326,
"stdev": 119.845,
"min": 721.994,
"max": 942.743,
"ci95": 297.734
},
"memory.forest.gpu_mb": {
"n": 3,
"mean": 381.189,
"stdev": 5.222,
"min": 376.423,
"max": 386.77,
"ci95": 12.972
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 1123.386,
"stdev": 604.175,
"min": 734.302,
"max": 1819.414,
"ci95": 1500.976
},
"chunks.ocean.meshed_count": {
"n": 3,
"mean": 6613.0,
"stdev": 135.632,
"min": 6523.0,
"max": 6769.0,
"ci95": 336.955
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 3346.003,
"stdev": 59.312,
"min": 3303.535,
"max": 3413.77,
"ci95": 147.352
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 1357.991,
"stdev": 95.364,
"min": 1248.887,
"max": 1425.451,
"ci95": 236.917
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 911.822,
"stdev": 94.717,
"min": 802.528,
"max": 969.989,
"ci95": 235.308
},
"memory.ocean.gpu_mb": {
"n": 3,
"mean": 391.636,
"stdev": 5.435,
"min": 387.424,
"max": 397.771,
"ci95": 13.502
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 1588.954,
"stdev": 458.924,
"min": 1309.548,
"max": 2118.606,
"ci95": 1140.123
},
"chunks.mountain.meshed_count": {
"n": 3,
"mean": 7887.667,
"stdev": 41.041,
"min": 7862.0,
"max": 7935.0,
"ci95": 101.959
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 3375.623,
"stdev": 26.82,
"min": 3352.309,
"max": 3404.933,
"ci95": 66.629
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 1383.745,
"stdev": 67.628,
"min": 1324.071,
"max": 1457.203,
"ci95": 168.01
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 850.213,
"stdev": 103.149,
"min": 790.305,
"max": 969.318,
"ci95": 256.256
},
"memory.mountain.gpu_mb": {
"n": 3,
"mean": 448.64,
"stdev": 5.435,
"min": 444.428,
"max": 454.775,
"ci95": 13.502
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 1171.629,
"stdev": 0.337,
"min": 1171.398,
"max": 1172.016,
"ci95": 0.837
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 1082.078,
"stdev": 12.494,
"min": 1069.117,
"max": 1094.047,
"ci95": 31.04
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 35764,
"seconds": 12.0,
"avg_fps": 2980.22,
"low_1pct_fps": 1310.917,
"low_01pct_fps": 860.301,
"p50_ms": 0.317,
"p95_ms": 0.433,
"p99_ms": 0.633,
"p999_ms": 0.937,
"max_ms": 2.807,
"cpu_p50_ms": 0.192,
"gpu_p50_ms": 0.063,
"histogram": [
35741,
22,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 35931,
"seconds": 12.0,
"avg_fps": 2994.188,
"low_1pct_fps": 1299.278,
"low_01pct_fps": 795.415,
"p50_ms": 0.318,
"p95_ms": 0.428,
"p99_ms": 0.62,
"p999_ms": 0.943,
"max_ms": 5.797,
"cpu_p50_ms": 0.191,
"gpu_p50_ms": 0.063,
"histogram": [
35906,
23,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 34206,
"seconds": 12.0,
"avg_fps": 2850.416,
"low_1pct_fps": 1203.758,
"low_01pct_fps": 862.067,
"p50_ms": 0.326,
"p95_ms": 0.508,
"p99_ms": 0.705,
"p999_ms": 1.025,
"max_ms": 1.398,
"cpu_p50_ms": 0.196,
"gpu_p50_ms": 0.063,
"histogram": [
34167,
39,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 41800,
"seconds": 12.0,
"avg_fps": 3483.193,
"low_1pct_fps": 1271.782,
"low_01pct_fps": 913.242,
"p50_ms": 0.264,
"p95_ms": 0.415,
"p99_ms": 0.657,
"p999_ms": 0.935,
"max_ms": 1.482,
"cpu_p50_ms": 0.144,
"gpu_p50_ms": 0.075,
"histogram": [
41768,
32,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 43333,
"seconds": 12.0,
"avg_fps": 3610.993,
"low_1pct_fps": 1465.171,
"low_01pct_fps": 942.743,
"p50_ms": 0.263,
"p95_ms": 0.355,
"p99_ms": 0.561,
"p999_ms": 0.859,
"max_ms": 1.694,
"cpu_p50_ms": 0.143,
"gpu_p50_ms": 0.074,
"histogram": [
43310,
23,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 40679,
"seconds": 12.0,
"avg_fps": 3389.894,
"low_1pct_fps": 1148.468,
"low_01pct_fps": 721.994,
"p50_ms": 0.267,
"p95_ms": 0.446,
"p99_ms": 0.67,
"p999_ms": 1.183,
"max_ms": 2.434,
"cpu_p50_ms": 0.146,
"gpu_p50_ms": 0.076,
"histogram": [
40590,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 39849,
"seconds": 12.0,
"avg_fps": 3320.704,
"low_1pct_fps": 1399.634,
"low_01pct_fps": 969.989,
"p50_ms": 0.281,
"p95_ms": 0.404,
"p99_ms": 0.601,
"p999_ms": 0.875,
"max_ms": 1.494,
"cpu_p50_ms": 0.159,
"gpu_p50_ms": 0.069,
"histogram": [
39831,
18,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 40966,
"seconds": 12.0,
"avg_fps": 3413.77,
"low_1pct_fps": 1425.451,
"low_01pct_fps": 962.948,
"p50_ms": 0.278,
"p95_ms": 0.372,
"p99_ms": 0.581,
"p999_ms": 0.857,
"max_ms": 1.576,
"cpu_p50_ms": 0.157,
"gpu_p50_ms": 0.069,
"histogram": [
40947,
19,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 39643,
"seconds": 12.0,
"avg_fps": 3303.535,
"low_1pct_fps": 1248.887,
"low_01pct_fps": 802.528,
"p50_ms": 0.28,
"p95_ms": 0.413,
"p99_ms": 0.642,
"p999_ms": 1.087,
"max_ms": 2.215,
"cpu_p50_ms": 0.158,
"gpu_p50_ms": 0.069,
"histogram": [
39582,
60,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 40436,
"seconds": 12.0,
"avg_fps": 3369.626,
"low_1pct_fps": 1369.962,
"low_01pct_fps": 790.305,
"p50_ms": 0.279,
"p95_ms": 0.403,
"p99_ms": 0.604,
"p999_ms": 0.812,
"max_ms": 10.313,
"cpu_p50_ms": 0.159,
"gpu_p50_ms": 0.069,
"histogram": [
40425,
8,
1,
1,
0,
0,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 40860,
"seconds": 12.0,
"avg_fps": 3404.933,
"low_1pct_fps": 1457.203,
"low_01pct_fps": 969.318,
"p50_ms": 0.278,
"p95_ms": 0.389,
"p99_ms": 0.574,
"p999_ms": 0.814,
"max_ms": 2.714,
"cpu_p50_ms": 0.158,
"gpu_p50_ms": 0.069,
"histogram": [
40847,
11,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 40229,
"seconds": 12.0,
"avg_fps": 3352.309,
"low_1pct_fps": 1324.071,
"low_01pct_fps": 791.016,
"p50_ms": 0.28,
"p95_ms": 0.402,
"p99_ms": 0.617,
"p999_ms": 0.968,
"max_ms": 3.746,
"cpu_p50_ms": 0.159,
"gpu_p50_ms": 0.069,
"histogram": [
40192,
35,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "horizon-win-9800x3d-5080"
}
@@ -1,706 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T01:25:53Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
},
{
"name": "sodium",
"version": "mc26.3-0.9.2-fabric"
},
{
"name": "lithium",
"version": "mc26.3-0.26.2-fabric"
},
{
"name": "ferrite-core",
"version": "9.0.0-fabric"
},
{
"name": "immediatelyfast",
"version": "1.17.1+26.3-fabric"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 16,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 10777.756,
"stdev": 129.67,
"min": 10636.92,
"max": 10892.2,
"ci95": 322.144
},
"startup.world_ms": {
"n": 3,
"mean": 23477.423,
"stdev": 346.614,
"min": 23130.92,
"max": 23824.148,
"ci95": 861.106
},
"chunks.village.load_ms": {
"n": 3,
"mean": 6007.033,
"stdev": 104.227,
"min": 5891.431,
"max": 6093.825,
"ci95": 258.936
},
"fps.village.avg_fps": {
"n": 3,
"mean": 1282.11,
"stdev": 65.207,
"min": 1228.13,
"max": 1354.56,
"ci95": 161.997
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 343.465,
"stdev": 9.96,
"min": 335.223,
"max": 354.532,
"ci95": 24.744
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 131.669,
"stdev": 4.692,
"min": 126.427,
"max": 135.476,
"ci95": 11.656
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 8669.311,
"stdev": 434.39,
"min": 8280.854,
"max": 9138.35,
"ci95": 1079.173
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 1745.757,
"stdev": 13.014,
"min": 1734.41,
"max": 1759.963,
"ci95": 32.332
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 460.958,
"stdev": 10.859,
"min": 449.051,
"max": 470.316,
"ci95": 26.978
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 178.955,
"stdev": 3.777,
"min": 175.213,
"max": 182.766,
"ci95": 9.383
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 7056.368,
"stdev": 117.329,
"min": 6986.912,
"max": 7191.833,
"ci95": 291.485
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 1815.056,
"stdev": 47.875,
"min": 1759.788,
"max": 1843.745,
"ci95": 118.937
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 514.215,
"stdev": 57.205,
"min": 452.445,
"max": 565.368,
"ci95": 142.117
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 191.842,
"stdev": 23.217,
"min": 175.546,
"max": 218.426,
"ci95": 57.68
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 14094.582,
"stdev": 399.624,
"min": 13641.534,
"max": 14397.0,
"ci95": 992.801
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 1499.768,
"stdev": 22.197,
"min": 1477.269,
"max": 1521.651,
"ci95": 55.146
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 408.466,
"stdev": 16.114,
"min": 395.097,
"max": 426.358,
"ci95": 40.032
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 139.743,
"stdev": 3.969,
"min": 136.465,
"max": 144.156,
"ci95": 9.86
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2495.607,
"stdev": 75.339,
"min": 2412.738,
"max": 2559.965,
"ci95": 187.166
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 2326.611,
"stdev": 15.702,
"min": 2314.98,
"max": 2344.473,
"ci95": 39.01
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 14738,
"seconds": 12.0,
"avg_fps": 1228.13,
"low_1pct_fps": 335.223,
"low_01pct_fps": 133.103,
"p50_ms": 0.722,
"p95_ms": 1.384,
"p99_ms": 2.043,
"p999_ms": 5.224,
"max_ms": 11.459,
"histogram": [
12159,
2421,
128,
14,
1,
5,
2,
3,
4,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 16255,
"seconds": 12.0,
"avg_fps": 1354.56,
"low_1pct_fps": 354.532,
"low_01pct_fps": 135.476,
"p50_ms": 0.672,
"p95_ms": 1.136,
"p99_ms": 1.841,
"p999_ms": 4.913,
"max_ms": 16.94,
"histogram": [
14841,
1298,
86,
13,
2,
5,
4,
1,
3,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 15164,
"seconds": 12.0,
"avg_fps": 1263.64,
"low_1pct_fps": 340.639,
"low_01pct_fps": 126.427,
"p50_ms": 0.708,
"p95_ms": 1.299,
"p99_ms": 1.895,
"p999_ms": 5.173,
"max_ms": 16.748,
"histogram": [
13026,
2014,
94,
13,
1,
3,
3,
6,
2,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 20915,
"seconds": 12.0,
"avg_fps": 1742.897,
"low_1pct_fps": 470.316,
"low_01pct_fps": 182.766,
"p50_ms": 0.5,
"p95_ms": 0.936,
"p99_ms": 1.437,
"p999_ms": 2.77,
"max_ms": 13.414,
"histogram": [
20067,
788,
44,
4,
0,
4,
3,
3,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 21120,
"seconds": 12.0,
"avg_fps": 1759.963,
"low_1pct_fps": 449.051,
"low_01pct_fps": 178.887,
"p50_ms": 0.49,
"p95_ms": 0.901,
"p99_ms": 1.531,
"p999_ms": 3.005,
"max_ms": 12.907,
"histogram": [
20414,
644,
40,
10,
1,
3,
2,
2,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 20813,
"seconds": 12.0,
"avg_fps": 1734.41,
"low_1pct_fps": 463.506,
"low_01pct_fps": 175.213,
"p50_ms": 0.496,
"p95_ms": 0.924,
"p99_ms": 1.414,
"p999_ms": 2.733,
"max_ms": 16.832,
"histogram": [
20049,
707,
41,
5,
0,
1,
5,
2,
2,
0,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 22100,
"seconds": 12.0,
"avg_fps": 1841.634,
"low_1pct_fps": 565.368,
"low_01pct_fps": 218.426,
"p50_ms": 0.483,
"p95_ms": 0.835,
"p99_ms": 1.209,
"p999_ms": 2.082,
"max_ms": 14.627,
"histogram": [
21540,
532,
18,
1,
1,
1,
2,
2,
1,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 21118,
"seconds": 12.0,
"avg_fps": 1759.788,
"low_1pct_fps": 452.445,
"low_01pct_fps": 175.546,
"p50_ms": 0.489,
"p95_ms": 0.915,
"p99_ms": 1.532,
"p999_ms": 2.811,
"max_ms": 11.846,
"histogram": [
20308,
755,
36,
9,
0,
2,
0,
3,
2,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 22125,
"seconds": 12.0,
"avg_fps": 1843.745,
"low_1pct_fps": 524.832,
"low_01pct_fps": 181.555,
"p50_ms": 0.477,
"p95_ms": 0.855,
"p99_ms": 1.241,
"p999_ms": 2.236,
"max_ms": 12.478,
"histogram": [
21487,
608,
18,
1,
1,
1,
2,
2,
1,
2,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 18005,
"seconds": 12.0,
"avg_fps": 1500.383,
"low_1pct_fps": 403.944,
"low_01pct_fps": 136.465,
"p50_ms": 0.591,
"p95_ms": 1.058,
"p99_ms": 1.592,
"p999_ms": 3.186,
"max_ms": 12.608,
"histogram": [
16864,
1084,
32,
8,
0,
5,
3,
5,
1,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 17728,
"seconds": 12.001,
"avg_fps": 1477.269,
"low_1pct_fps": 395.097,
"low_01pct_fps": 138.609,
"p50_ms": 0.598,
"p95_ms": 1.042,
"p99_ms": 1.561,
"p999_ms": 5.033,
"max_ms": 11.462,
"histogram": [
16612,
1051,
39,
7,
1,
6,
5,
3,
1,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 18260,
"seconds": 12.0,
"avg_fps": 1521.651,
"low_1pct_fps": 426.358,
"low_01pct_fps": 144.156,
"p50_ms": 0.585,
"p95_ms": 1.015,
"p99_ms": 1.458,
"p999_ms": 3.609,
"max_ms": 11.945,
"histogram": [
17267,
943,
26,
6,
5,
2,
3,
3,
2,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "vanilla-mods-win-9800x3d-5080"
}
@@ -1,706 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T19:27:56Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
},
{
"name": "sodium",
"version": "mc26.3-0.9.2-fabric"
},
{
"name": "lithium",
"version": "mc26.3-0.26.2-fabric"
},
{
"name": "ferrite-core",
"version": "9.0.0-fabric"
},
{
"name": "immediatelyfast",
"version": "1.17.1+26.3-fabric"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 32,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 11038.922,
"stdev": 118.058,
"min": 10935.424,
"max": 11167.506,
"ci95": 293.295
},
"startup.world_ms": {
"n": 3,
"mean": 39248.588,
"stdev": 479.755,
"min": 38964.834,
"max": 39802.506,
"ci95": 1191.875
},
"chunks.village.load_ms": {
"n": 3,
"mean": 11176.953,
"stdev": 356.144,
"min": 10836.65,
"max": 11547.064,
"ci95": 884.781
},
"fps.village.avg_fps": {
"n": 3,
"mean": 925.977,
"stdev": 6.727,
"min": 918.832,
"max": 932.189,
"ci95": 16.713
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 250.092,
"stdev": 1.868,
"min": 248.431,
"max": 252.114,
"ci95": 4.64
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 92.692,
"stdev": 4.466,
"min": 88.423,
"max": 97.332,
"ci95": 11.095
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 17335.638,
"stdev": 687.588,
"min": 16544.168,
"max": 17785.772,
"ci95": 1708.201
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 929.034,
"stdev": 3.11,
"min": 926.32,
"max": 932.428,
"ci95": 7.727
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 312.69,
"stdev": 16.386,
"min": 297.667,
"max": 330.163,
"ci95": 40.708
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 129.331,
"stdev": 12.786,
"min": 115.486,
"max": 140.694,
"ci95": 31.765
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 12601.063,
"stdev": 148.042,
"min": 12430.182,
"max": 12690.506,
"ci95": 367.785
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 1016.598,
"stdev": 5.481,
"min": 1010.482,
"max": 1021.068,
"ci95": 13.618
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 325.361,
"stdev": 15.112,
"min": 315.682,
"max": 342.774,
"ci95": 37.543
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 117.042,
"stdev": 11.095,
"min": 107.807,
"max": 129.349,
"ci95": 27.563
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 38513.008,
"stdev": 958.119,
"min": 37447.333,
"max": 39303.226,
"ci95": 2380.292
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 644.782,
"stdev": 3.94,
"min": 640.866,
"max": 648.745,
"ci95": 9.788
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 166.029,
"stdev": 4.758,
"min": 162.326,
"max": 171.395,
"ci95": 11.819
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 86.231,
"stdev": 8.587,
"min": 76.632,
"max": 93.184,
"ci95": 21.334
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2964.911,
"stdev": 8.27,
"min": 2959.813,
"max": 2974.453,
"ci95": 20.545
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 2894.541,
"stdev": 12.847,
"min": 2879.928,
"max": 2904.059,
"ci95": 31.917
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 11123,
"seconds": 12.0,
"avg_fps": 926.911,
"low_1pct_fps": 249.732,
"low_01pct_fps": 92.322,
"p50_ms": 0.989,
"p95_ms": 1.492,
"p99_ms": 2.33,
"p999_ms": 7.409,
"max_ms": 15.258,
"histogram": [
6224,
4701,
147,
28,
3,
2,
5,
3,
3,
3,
1,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 11187,
"seconds": 12.001,
"avg_fps": 932.189,
"low_1pct_fps": 252.114,
"low_01pct_fps": 88.423,
"p50_ms": 0.984,
"p95_ms": 1.496,
"p99_ms": 2.328,
"p999_ms": 7.858,
"max_ms": 16.843,
"histogram": [
6518,
4486,
138,
20,
9,
1,
1,
6,
1,
2,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 11026,
"seconds": 12.0,
"avg_fps": 918.832,
"low_1pct_fps": 248.431,
"low_01pct_fps": 97.332,
"p50_ms": 0.989,
"p95_ms": 1.524,
"p99_ms": 2.37,
"p999_ms": 7.446,
"max_ms": 16.573,
"histogram": [
6075,
4740,
162,
23,
5,
2,
4,
7,
4,
1,
1,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 11117,
"seconds": 12.001,
"avg_fps": 926.32,
"low_1pct_fps": 310.239,
"low_01pct_fps": 131.814,
"p50_ms": 1.011,
"p95_ms": 1.34,
"p99_ms": 2.045,
"p999_ms": 4.711,
"max_ms": 14.077,
"histogram": [
3849,
7150,
78,
26,
5,
1,
3,
2,
1,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 11190,
"seconds": 12.001,
"avg_fps": 932.428,
"low_1pct_fps": 330.163,
"low_01pct_fps": 140.694,
"p50_ms": 1.008,
"p95_ms": 1.307,
"p99_ms": 1.869,
"p999_ms": 4.341,
"max_ms": 13.489,
"histogram": [
4273,
6822,
60,
20,
7,
0,
3,
3,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 11141,
"seconds": 12.001,
"avg_fps": 928.354,
"low_1pct_fps": 297.667,
"low_01pct_fps": 115.486,
"p50_ms": 1.005,
"p95_ms": 1.352,
"p99_ms": 2.054,
"p999_ms": 5.292,
"max_ms": 14.339,
"histogram": [
4901,
6118,
83,
23,
3,
2,
4,
3,
0,
1,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 12126,
"seconds": 12.0,
"avg_fps": 1010.482,
"low_1pct_fps": 317.626,
"low_01pct_fps": 113.971,
"p50_ms": 0.933,
"p95_ms": 1.23,
"p99_ms": 1.935,
"p999_ms": 4.393,
"max_ms": 14.824,
"histogram": [
9183,
2830,
82,
17,
3,
1,
2,
3,
0,
1,
3,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 12219,
"seconds": 12.0,
"avg_fps": 1018.243,
"low_1pct_fps": 342.774,
"low_01pct_fps": 129.349,
"p50_ms": 0.929,
"p95_ms": 1.222,
"p99_ms": 1.867,
"p999_ms": 4.329,
"max_ms": 10.33,
"histogram": [
9421,
2710,
60,
15,
3,
0,
0,
5,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 12253,
"seconds": 12.0,
"avg_fps": 1021.068,
"low_1pct_fps": 315.682,
"low_01pct_fps": 107.807,
"p50_ms": 0.923,
"p95_ms": 1.225,
"p99_ms": 1.969,
"p999_ms": 5.235,
"max_ms": 19.524,
"histogram": [
9231,
2904,
92,
10,
2,
5,
0,
4,
1,
2,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 7691,
"seconds": 12.001,
"avg_fps": 640.866,
"low_1pct_fps": 164.367,
"low_01pct_fps": 93.184,
"p50_ms": 1.454,
"p95_ms": 1.95,
"p99_ms": 3.4,
"p999_ms": 9.754,
"max_ms": 14.995,
"histogram": [
36,
7331,
233,
26,
17,
13,
20,
3,
6,
5,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 7737,
"seconds": 12.0,
"avg_fps": 644.736,
"low_1pct_fps": 162.326,
"low_01pct_fps": 76.632,
"p50_ms": 1.454,
"p95_ms": 1.905,
"p99_ms": 3.676,
"p999_ms": 9.926,
"max_ms": 18.459,
"histogram": [
46,
7399,
199,
24,
21,
24,
10,
6,
1,
1,
4,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 7785,
"seconds": 12.0,
"avg_fps": 648.745,
"low_1pct_fps": 171.395,
"low_01pct_fps": 88.876,
"p50_ms": 1.439,
"p95_ms": 1.886,
"p99_ms": 3.562,
"p999_ms": 10.342,
"max_ms": 12.927,
"histogram": [
57,
7432,
186,
44,
23,
20,
9,
3,
3,
7,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "vanilla-mods-win-9800x3d-5080"
}
@@ -1,706 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T18:49:40Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
},
{
"name": "sodium",
"version": "mc26.3-0.9.2-fabric"
},
{
"name": "lithium",
"version": "mc26.3-0.26.2-fabric"
},
{
"name": "ferrite-core",
"version": "9.0.0-fabric"
},
{
"name": "immediatelyfast",
"version": "1.17.1+26.3-fabric"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 8,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 11089.831,
"stdev": 46.336,
"min": 11036.36,
"max": 11118.192,
"ci95": 115.114
},
"startup.world_ms": {
"n": 3,
"mean": 17643.831,
"stdev": 47.672,
"min": 17589.192,
"max": 17676.942,
"ci95": 118.433
},
"chunks.village.load_ms": {
"n": 3,
"mean": 3603.773,
"stdev": 161.342,
"min": 3488.106,
"max": 3788.086,
"ci95": 400.828
},
"fps.village.avg_fps": {
"n": 3,
"mean": 2103.54,
"stdev": 40.465,
"min": 2078.464,
"max": 2150.222,
"ci95": 100.529
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 577.326,
"stdev": 33.693,
"min": 557.613,
"max": 616.23,
"ci95": 83.704
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 195.53,
"stdev": 18.899,
"min": 181.495,
"max": 217.019,
"ci95": 46.951
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 3282.612,
"stdev": 48.569,
"min": 3233.16,
"max": 3330.246,
"ci95": 120.661
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 2424.739,
"stdev": 26.074,
"min": 2394.789,
"max": 2442.383,
"ci95": 64.777
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 732.987,
"stdev": 11.926,
"min": 724.144,
"max": 746.55,
"ci95": 29.627
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 249.926,
"stdev": 8.826,
"min": 241.293,
"max": 258.934,
"ci95": 21.928
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 2705.954,
"stdev": 173.487,
"min": 2538.486,
"max": 2884.891,
"ci95": 431.0
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 2431.99,
"stdev": 33.071,
"min": 2394.02,
"max": 2454.493,
"ci95": 82.159
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 764.065,
"stdev": 14.782,
"min": 747.287,
"max": 775.168,
"ci95": 36.723
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 261.954,
"stdev": 14.724,
"min": 252.457,
"max": 278.916,
"ci95": 36.58
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 4982.865,
"stdev": 115.523,
"min": 4849.837,
"max": 5057.932,
"ci95": 286.997
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 2538.05,
"stdev": 67.405,
"min": 2462.815,
"max": 2592.938,
"ci95": 167.458
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 760.16,
"stdev": 13.503,
"min": 746.001,
"max": 772.895,
"ci95": 33.547
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 240.897,
"stdev": 17.872,
"min": 224.391,
"max": 259.878,
"ci95": 44.401
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2052.982,
"stdev": 57.756,
"min": 1992.574,
"max": 2107.66,
"ci95": 143.487
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 1903.921,
"stdev": 62.254,
"min": 1838.307,
"max": 1962.156,
"ci95": 154.659
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 25803,
"seconds": 12.0,
"avg_fps": 2150.222,
"low_1pct_fps": 616.23,
"low_01pct_fps": 217.019,
"p50_ms": 0.433,
"p95_ms": 0.642,
"p99_ms": 1.04,
"p999_ms": 2.307,
"max_ms": 7.466,
"histogram": [
25503,
269,
8,
6,
7,
6,
2,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 24942,
"seconds": 12.0,
"avg_fps": 2078.464,
"low_1pct_fps": 557.613,
"low_01pct_fps": 181.495,
"p50_ms": 0.45,
"p95_ms": 0.665,
"p99_ms": 1.1,
"p999_ms": 2.305,
"max_ms": 9.819,
"histogram": [
24615,
288,
17,
2,
4,
9,
2,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 24984,
"seconds": 12.0,
"avg_fps": 2081.934,
"low_1pct_fps": 558.135,
"low_01pct_fps": 188.076,
"p50_ms": 0.444,
"p95_ms": 0.682,
"p99_ms": 1.101,
"p999_ms": 2.412,
"max_ms": 11.567,
"histogram": [
24645,
308,
9,
3,
5,
5,
7,
1,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 29245,
"seconds": 12.0,
"avg_fps": 2437.044,
"low_1pct_fps": 728.266,
"low_01pct_fps": 249.55,
"p50_ms": 0.38,
"p95_ms": 0.555,
"p99_ms": 0.892,
"p999_ms": 1.851,
"max_ms": 6.973,
"histogram": [
29066,
154,
4,
6,
7,
6,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 28738,
"seconds": 12.0,
"avg_fps": 2394.789,
"low_1pct_fps": 724.144,
"low_01pct_fps": 241.293,
"p50_ms": 0.384,
"p95_ms": 0.571,
"p99_ms": 0.907,
"p999_ms": 1.833,
"max_ms": 8.35,
"histogram": [
28573,
140,
6,
3,
6,
5,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 29309,
"seconds": 12.0,
"avg_fps": 2442.383,
"low_1pct_fps": 746.55,
"low_01pct_fps": 258.934,
"p50_ms": 0.378,
"p95_ms": 0.566,
"p99_ms": 0.876,
"p999_ms": 1.744,
"max_ms": 10.291,
"histogram": [
29138,
148,
5,
6,
5,
2,
4,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 29454,
"seconds": 12.0,
"avg_fps": 2454.493,
"low_1pct_fps": 769.741,
"low_01pct_fps": 252.457,
"p50_ms": 0.378,
"p95_ms": 0.55,
"p99_ms": 0.853,
"p999_ms": 1.471,
"max_ms": 6.629,
"histogram": [
29323,
110,
2,
2,
7,
7,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 28729,
"seconds": 12.0,
"avg_fps": 2394.02,
"low_1pct_fps": 747.287,
"low_01pct_fps": 254.49,
"p50_ms": 0.383,
"p95_ms": 0.579,
"p99_ms": 0.896,
"p999_ms": 1.56,
"max_ms": 7.367,
"histogram": [
28567,
141,
3,
5,
4,
4,
4,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 29370,
"seconds": 12.0,
"avg_fps": 2447.458,
"low_1pct_fps": 775.168,
"low_01pct_fps": 278.916,
"p50_ms": 0.376,
"p95_ms": 0.559,
"p99_ms": 0.887,
"p999_ms": 1.567,
"max_ms": 9.65,
"histogram": [
29209,
141,
3,
9,
0,
5,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 31116,
"seconds": 12.0,
"avg_fps": 2592.938,
"low_1pct_fps": 761.584,
"low_01pct_fps": 224.391,
"p50_ms": 0.356,
"p95_ms": 0.511,
"p99_ms": 0.767,
"p999_ms": 1.843,
"max_ms": 8.478,
"histogram": [
31011,
76,
4,
3,
13,
4,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 29554,
"seconds": 12.0,
"avg_fps": 2462.815,
"low_1pct_fps": 746.001,
"low_01pct_fps": 238.423,
"p50_ms": 0.366,
"p95_ms": 0.579,
"p99_ms": 0.849,
"p999_ms": 1.75,
"max_ms": 7.607,
"histogram": [
29430,
101,
2,
3,
9,
4,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 30701,
"seconds": 12.0,
"avg_fps": 2558.396,
"low_1pct_fps": 772.895,
"low_01pct_fps": 259.878,
"p50_ms": 0.357,
"p95_ms": 0.537,
"p99_ms": 0.81,
"p999_ms": 1.702,
"max_ms": 6.682,
"histogram": [
30568,
112,
1,
6,
5,
3,
6,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "vanilla-mods-win-9800x3d-5080"
}
@@ -1,690 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T01:19:23Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 16,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 7681.834,
"stdev": 189.48,
"min": 7538.777,
"max": 7896.728,
"ci95": 470.732
},
"startup.world_ms": {
"n": 3,
"mean": 19898.834,
"stdev": 192.981,
"min": 19695.728,
"max": 20079.777,
"ci95": 479.431
},
"chunks.village.load_ms": {
"n": 3,
"mean": 6127.947,
"stdev": 26.756,
"min": 6097.19,
"max": 6145.854,
"ci95": 66.471
},
"fps.village.avg_fps": {
"n": 3,
"mean": 1218.486,
"stdev": 26.337,
"min": 1188.13,
"max": 1235.248,
"ci95": 65.43
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 318.468,
"stdev": 6.292,
"min": 313.2,
"max": 325.435,
"ci95": 15.632
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 126.59,
"stdev": 1.844,
"min": 124.744,
"max": 128.431,
"ci95": 4.58
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 8548.814,
"stdev": 152.302,
"min": 8380.912,
"max": 8678.071,
"ci95": 378.37
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 1912.359,
"stdev": 130.238,
"min": 1791.386,
"max": 2050.215,
"ci95": 323.555
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 401.907,
"stdev": 35.911,
"min": 379.849,
"max": 443.345,
"ci95": 89.216
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 149.26,
"stdev": 9.983,
"min": 139.809,
"max": 159.701,
"ci95": 24.801
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 6953.478,
"stdev": 276.636,
"min": 6635.649,
"max": 7140.072,
"ci95": 687.258
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 1860.512,
"stdev": 116.512,
"min": 1726.149,
"max": 1933.597,
"ci95": 289.454
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 446.336,
"stdev": 56.993,
"min": 382.26,
"max": 491.369,
"ci95": 141.589
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 164.934,
"stdev": 11.839,
"min": 152.493,
"max": 176.062,
"ci95": 29.413
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 15211.386,
"stdev": 256.348,
"min": 14938.008,
"max": 15446.375,
"ci95": 636.856
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 1653.223,
"stdev": 61.705,
"min": 1584.652,
"max": 1704.273,
"ci95": 153.297
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 331.929,
"stdev": 10.858,
"min": 319.394,
"max": 338.396,
"ci95": 26.974
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 113.436,
"stdev": 3.255,
"min": 110.869,
"max": 117.097,
"ci95": 8.086
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2540.129,
"stdev": 152.057,
"min": 2373.152,
"max": 2670.633,
"ci95": 377.761
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 2299.514,
"stdev": 81.451,
"min": 2207.129,
"max": 2360.973,
"ci95": 202.352
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 14785,
"seconds": 12.0,
"avg_fps": 1232.081,
"low_1pct_fps": 325.435,
"low_01pct_fps": 128.431,
"p50_ms": 0.742,
"p95_ms": 1.265,
"p99_ms": 2.032,
"p999_ms": 5.653,
"max_ms": 12.791,
"histogram": [
12845,
1784,
127,
7,
1,
8,
4,
3,
5,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 14258,
"seconds": 12.0,
"avg_fps": 1188.13,
"low_1pct_fps": 313.2,
"low_01pct_fps": 126.595,
"p50_ms": 0.757,
"p95_ms": 1.349,
"p99_ms": 2.12,
"p999_ms": 5.541,
"max_ms": 13.998,
"histogram": [
11994,
2076,
157,
9,
2,
8,
2,
4,
5,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 14823,
"seconds": 12.0,
"avg_fps": 1235.248,
"low_1pct_fps": 316.768,
"low_01pct_fps": 124.744,
"p50_ms": 0.744,
"p95_ms": 1.199,
"p99_ms": 2.047,
"p999_ms": 5.628,
"max_ms": 15.519,
"histogram": [
13214,
1453,
118,
16,
2,
8,
6,
3,
0,
1,
0,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 21497,
"seconds": 12.0,
"avg_fps": 1791.386,
"low_1pct_fps": 382.527,
"low_01pct_fps": 139.809,
"p50_ms": 0.474,
"p95_ms": 0.931,
"p99_ms": 1.646,
"p999_ms": 5.274,
"max_ms": 13.459,
"histogram": [
20598,
799,
66,
9,
3,
8,
8,
2,
2,
0,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 24603,
"seconds": 12.0,
"avg_fps": 2050.215,
"low_1pct_fps": 443.345,
"low_01pct_fps": 159.701,
"p50_ms": 0.426,
"p95_ms": 0.752,
"p99_ms": 1.442,
"p999_ms": 3.134,
"max_ms": 13.282,
"histogram": [
24041,
487,
48,
6,
5,
6,
2,
3,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 22746,
"seconds": 12.0,
"avg_fps": 1895.476,
"low_1pct_fps": 379.849,
"low_01pct_fps": 148.269,
"p50_ms": 0.456,
"p95_ms": 0.829,
"p99_ms": 1.561,
"p999_ms": 4.176,
"max_ms": 10.671,
"histogram": [
22092,
523,
91,
17,
4,
7,
3,
4,
4,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 23062,
"seconds": 12.0,
"avg_fps": 1921.791,
"low_1pct_fps": 465.379,
"low_01pct_fps": 166.247,
"p50_ms": 0.463,
"p95_ms": 0.809,
"p99_ms": 1.45,
"p999_ms": 2.398,
"max_ms": 11.808,
"histogram": [
22454,
561,
27,
3,
2,
6,
0,
4,
3,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 23204,
"seconds": 12.0,
"avg_fps": 1933.597,
"low_1pct_fps": 491.369,
"low_01pct_fps": 176.062,
"p50_ms": 0.466,
"p95_ms": 0.766,
"p99_ms": 1.406,
"p999_ms": 2.229,
"max_ms": 15.102,
"histogram": [
22699,
469,
19,
4,
1,
1,
4,
2,
2,
2,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 20714,
"seconds": 12.0,
"avg_fps": 1726.149,
"low_1pct_fps": 382.26,
"low_01pct_fps": 152.493,
"p50_ms": 0.5,
"p95_ms": 0.956,
"p99_ms": 1.742,
"p999_ms": 3.852,
"max_ms": 12.888,
"histogram": [
19814,
787,
83,
11,
2,
7,
3,
5,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 20049,
"seconds": 12.0,
"avg_fps": 1670.745,
"low_1pct_fps": 338.396,
"low_01pct_fps": 117.097,
"p50_ms": 0.502,
"p95_ms": 0.949,
"p99_ms": 1.673,
"p999_ms": 6.456,
"max_ms": 16.791,
"histogram": [
19187,
753,
70,
8,
1,
6,
12,
4,
3,
4,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 19016,
"seconds": 12.0,
"avg_fps": 1584.652,
"low_1pct_fps": 337.998,
"low_01pct_fps": 112.343,
"p50_ms": 0.531,
"p95_ms": 1.082,
"p99_ms": 1.717,
"p999_ms": 5.939,
"max_ms": 12.958,
"histogram": [
17849,
1069,
63,
7,
3,
6,
2,
7,
4,
5,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 20452,
"seconds": 12.0,
"avg_fps": 1704.273,
"low_1pct_fps": 319.394,
"low_01pct_fps": 110.869,
"p50_ms": 0.496,
"p95_ms": 0.911,
"p99_ms": 1.706,
"p999_ms": 5.938,
"max_ms": 24.863,
"histogram": [
19694,
626,
82,
14,
3,
14,
5,
4,
5,
3,
1,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "vanilla-win-9800x3d-5080"
}
@@ -1,690 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T19:06:49Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 32,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 7518.874,
"stdev": 42.968,
"min": 7469.532,
"max": 7548.049,
"ci95": 106.748
},
"startup.world_ms": {
"n": 3,
"mean": 35424.207,
"stdev": 144.711,
"min": 35318.049,
"max": 35589.041,
"ci95": 359.511
},
"chunks.village.load_ms": {
"n": 3,
"mean": 11146.828,
"stdev": 49.683,
"min": 11094.798,
"max": 11193.773,
"ci95": 123.43
},
"fps.village.avg_fps": {
"n": 3,
"mean": 882.053,
"stdev": 19.433,
"min": 866.126,
"max": 903.706,
"ci95": 48.279
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 183.995,
"stdev": 4.924,
"min": 178.512,
"max": 188.041,
"ci95": 12.234
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 83.193,
"stdev": 6.797,
"min": 77.734,
"max": 90.806,
"ci95": 16.886
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 18184.002,
"stdev": 266.879,
"min": 17880.667,
"max": 18382.735,
"ci95": 663.017
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 1202.907,
"stdev": 20.426,
"min": 1179.9,
"max": 1218.906,
"ci95": 50.744
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 228.139,
"stdev": 5.166,
"min": 222.394,
"max": 232.401,
"ci95": 12.833
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 107.956,
"stdev": 4.675,
"min": 105.185,
"max": 113.354,
"ci95": 11.614
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 13146.632,
"stdev": 507.943,
"min": 12572.118,
"max": 13536.145,
"ci95": 1261.902
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 1223.169,
"stdev": 13.11,
"min": 1208.837,
"max": 1234.556,
"ci95": 32.569
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 236.27,
"stdev": 6.77,
"min": 228.686,
"max": 241.702,
"ci95": 16.818
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 99.089,
"stdev": 8.354,
"min": 91.897,
"max": 108.253,
"ci95": 20.755
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 41846.641,
"stdev": 661.649,
"min": 41435.666,
"max": 42609.895,
"ci95": 1643.76
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 815.008,
"stdev": 24.644,
"min": 797.565,
"max": 843.201,
"ci95": 61.224
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 55.371,
"stdev": 5.128,
"min": 50.389,
"max": 60.633,
"ci95": 12.739
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 7.966,
"stdev": 1.103,
"min": 6.848,
"max": 9.053,
"ci95": 2.74
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2892.492,
"stdev": 29.54,
"min": 2859.574,
"max": 2916.691,
"ci95": 73.387
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 2799.159,
"stdev": 12.256,
"min": 2786.234,
"max": 2810.613,
"ci95": 30.447
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 10845,
"seconds": 12.001,
"avg_fps": 903.706,
"low_1pct_fps": 185.432,
"low_01pct_fps": 81.039,
"p50_ms": 0.98,
"p95_ms": 1.708,
"p99_ms": 3.082,
"p999_ms": 9.304,
"max_ms": 15.487,
"histogram": [
6030,
4403,
297,
49,
25,
16,
8,
2,
6,
2,
4,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 10516,
"seconds": 12.0,
"avg_fps": 876.328,
"low_1pct_fps": 188.041,
"low_01pct_fps": 90.806,
"p50_ms": 1.012,
"p95_ms": 1.806,
"p99_ms": 3.354,
"p999_ms": 8.714,
"max_ms": 14.39,
"histogram": [
4927,
5158,
292,
70,
33,
13,
6,
5,
6,
2,
3,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 10394,
"seconds": 12.001,
"avg_fps": 866.126,
"low_1pct_fps": 178.512,
"low_01pct_fps": 77.734,
"p50_ms": 1.026,
"p95_ms": 1.789,
"p99_ms": 3.399,
"p999_ms": 10.6,
"max_ms": 15.389,
"histogram": [
4437,
5552,
273,
65,
18,
28,
8,
1,
1,
3,
5,
3,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 14519,
"seconds": 12.0,
"avg_fps": 1209.916,
"low_1pct_fps": 232.401,
"low_01pct_fps": 105.185,
"p50_ms": 0.726,
"p95_ms": 1.306,
"p99_ms": 2.25,
"p999_ms": 7.033,
"max_ms": 13.303,
"histogram": [
13121,
1197,
103,
36,
24,
19,
4,
3,
8,
2,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 14159,
"seconds": 12.0,
"avg_fps": 1179.9,
"low_1pct_fps": 222.394,
"low_01pct_fps": 105.33,
"p50_ms": 0.732,
"p95_ms": 1.366,
"p99_ms": 2.499,
"p999_ms": 8.061,
"max_ms": 11.797,
"histogram": [
12501,
1356,
195,
45,
25,
14,
6,
3,
9,
5,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 14627,
"seconds": 12.0,
"avg_fps": 1218.906,
"low_1pct_fps": 229.622,
"low_01pct_fps": 113.354,
"p50_ms": 0.713,
"p95_ms": 1.292,
"p99_ms": 2.317,
"p999_ms": 7.136,
"max_ms": 12.041,
"histogram": [
13194,
1224,
97,
47,
27,
21,
2,
6,
6,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 14714,
"seconds": 12.001,
"avg_fps": 1226.113,
"low_1pct_fps": 238.423,
"low_01pct_fps": 97.117,
"p50_ms": 0.722,
"p95_ms": 1.223,
"p99_ms": 2.243,
"p999_ms": 7.032,
"max_ms": 13.21,
"histogram": [
13490,
1027,
115,
29,
18,
13,
7,
3,
3,
5,
4,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 14507,
"seconds": 12.001,
"avg_fps": 1208.837,
"low_1pct_fps": 228.686,
"low_01pct_fps": 91.897,
"p50_ms": 0.719,
"p95_ms": 1.256,
"p99_ms": 2.354,
"p999_ms": 7.473,
"max_ms": 15.432,
"histogram": [
13124,
1112,
180,
35,
23,
9,
8,
4,
2,
6,
2,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 14815,
"seconds": 12.0,
"avg_fps": 1234.556,
"low_1pct_fps": 241.702,
"low_01pct_fps": 108.253,
"p50_ms": 0.721,
"p95_ms": 1.2,
"p99_ms": 2.197,
"p999_ms": 6.689,
"max_ms": 12.791,
"histogram": [
13565,
1055,
107,
29,
23,
15,
8,
3,
4,
5,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 10119,
"seconds": 12.001,
"avg_fps": 843.201,
"low_1pct_fps": 60.633,
"low_01pct_fps": 9.053,
"p50_ms": 0.891,
"p95_ms": 1.845,
"p99_ms": 3.91,
"p999_ms": 8.209,
"max_ms": 316.409,
"histogram": [
6956,
2747,
240,
83,
45,
22,
8,
8,
5,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 9693,
"seconds": 12.052,
"avg_fps": 804.258,
"low_1pct_fps": 50.389,
"low_01pct_fps": 6.848,
"p50_ms": 0.906,
"p95_ms": 1.924,
"p99_ms": 4.157,
"p999_ms": 8.578,
"max_ms": 297.695,
"histogram": [
6578,
2678,
248,
94,
45,
18,
16,
5,
4,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
5,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 9571,
"seconds": 12.0,
"avg_fps": 797.565,
"low_1pct_fps": 55.09,
"low_01pct_fps": 7.997,
"p50_ms": 0.929,
"p95_ms": 1.944,
"p99_ms": 4.495,
"p999_ms": 7.764,
"max_ms": 321.994,
"histogram": [
5954,
3172,
230,
103,
39,
34,
19,
11,
4,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
4,
0,
0
]
}
],
"label": "vanilla-win-9800x3d-5080"
}
@@ -1,690 +0,0 @@
{
"format": "horizon-benchmark-report",
"version": 1,
"kind": "game",
"created": "2026-10-29T18:43:17Z",
"app": {
"name": "minecraft",
"version": "26.3",
"mods": [
{
"name": "fabric-loader",
"version": "0.19.5"
}
]
},
"hardware": {
"os": "windows",
"arch": "x86_64",
"cpu_threads": 16,
"os_version": "Microsoft Windows [Version 10.0.26200.8037]",
"cpu": "AMD Ryzen 7 9800X3D 8-Core Processor",
"ram_mb": 95943,
"gpu": {
"name": "NVIDIA GeForce RTX 5080/PCIe/SSE2",
"vendor": "NVIDIA Corporation",
"driver": "3.3.0 NVIDIA 617.42",
"backend": "opengl",
"kind": ""
}
},
"conditions": {
"scenario": "perf_bench:village,forest,ocean,mountain",
"seed": "1234",
"render_distance": 8,
"simulation_distance": 12,
"vsync": false,
"offscreen": false,
"repeats": 3,
"warmup_s": 2.0,
"window": [
1280,
720
]
},
"metrics": {
"startup.title_ms": {
"n": 3,
"mean": 7676.526,
"stdev": 305.763,
"min": 7426.024,
"max": 8017.247,
"ci95": 759.617
},
"startup.world_ms": {
"n": 3,
"mean": 13862.526,
"stdev": 284.577,
"min": 13569.024,
"max": 14137.247,
"ci95": 706.985
},
"chunks.village.load_ms": {
"n": 3,
"mean": 3808.014,
"stdev": 61.275,
"min": 3737.989,
"max": 3851.799,
"ci95": 152.227
},
"fps.village.avg_fps": {
"n": 3,
"mean": 2216.576,
"stdev": 45.247,
"min": 2166.285,
"max": 2253.985,
"ci95": 112.409
},
"fps.village.low_1pct_fps": {
"n": 3,
"mean": 545.307,
"stdev": 14.876,
"min": 528.15,
"max": 554.607,
"ci95": 36.957
},
"fps.village.low_01pct_fps": {
"n": 3,
"mean": 215.412,
"stdev": 5.692,
"min": 209.522,
"max": 220.882,
"ci95": 14.14
},
"chunks.forest.load_ms": {
"n": 3,
"mean": 3212.958,
"stdev": 151.722,
"min": 3076.655,
"max": 3376.428,
"ci95": 376.928
},
"fps.forest.avg_fps": {
"n": 3,
"mean": 2456.542,
"stdev": 336.369,
"min": 2068.162,
"max": 2654.549,
"ci95": 835.654
},
"fps.forest.low_1pct_fps": {
"n": 3,
"mean": 624.759,
"stdev": 90.0,
"min": 521.303,
"max": 685.008,
"ci95": 223.59
},
"fps.forest.low_01pct_fps": {
"n": 3,
"mean": 252.469,
"stdev": 21.044,
"min": 229.228,
"max": 270.233,
"ci95": 52.28
},
"chunks.ocean.load_ms": {
"n": 3,
"mean": 2983.236,
"stdev": 168.416,
"min": 2788.777,
"max": 3082.249,
"ci95": 418.403
},
"fps.ocean.avg_fps": {
"n": 3,
"mean": 2469.831,
"stdev": 333.258,
"min": 2085.121,
"max": 2669.9,
"ci95": 827.925
},
"fps.ocean.low_1pct_fps": {
"n": 3,
"mean": 688.684,
"stdev": 96.943,
"min": 576.803,
"max": 747.759,
"ci95": 240.839
},
"fps.ocean.low_01pct_fps": {
"n": 3,
"mean": 286.444,
"stdev": 21.36,
"min": 262.183,
"max": 302.422,
"ci95": 53.066
},
"chunks.mountain.load_ms": {
"n": 3,
"mean": 6079.869,
"stdev": 719.864,
"min": 5542.196,
"max": 6897.69,
"ci95": 1788.385
},
"fps.mountain.avg_fps": {
"n": 3,
"mean": 2605.12,
"stdev": 326.424,
"min": 2228.824,
"max": 2812.075,
"ci95": 810.948
},
"fps.mountain.low_1pct_fps": {
"n": 3,
"mean": 699.63,
"stdev": 87.846,
"min": 599.44,
"max": 763.45,
"ci95": 218.239
},
"fps.mountain.low_01pct_fps": {
"n": 3,
"mean": 264.461,
"stdev": 28.459,
"min": 239.602,
"max": 295.503,
"ci95": 70.701
},
"memory.rss_peak_mb": {
"n": 3,
"mean": 2120.426,
"stdev": 116.406,
"min": 2046.93,
"max": 2254.637,
"ci95": 289.191
},
"memory.rss_steady_mb": {
"n": 3,
"mean": 1912.642,
"stdev": 38.925,
"min": 1889.766,
"max": 1957.586,
"ci95": 96.702
}
},
"frames": [
{
"phase": "village",
"repeat": 0,
"frames": 27048,
"seconds": 12.0,
"avg_fps": 2253.985,
"low_1pct_fps": 553.164,
"low_01pct_fps": 215.833,
"p50_ms": 0.412,
"p95_ms": 0.617,
"p99_ms": 1.187,
"p999_ms": 2.238,
"max_ms": 9.792,
"histogram": [
26716,
296,
15,
4,
7,
5,
2,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 1,
"frames": 26754,
"seconds": 12.0,
"avg_fps": 2229.458,
"low_1pct_fps": 554.607,
"low_01pct_fps": 220.882,
"p50_ms": 0.417,
"p95_ms": 0.626,
"p99_ms": 1.212,
"p999_ms": 2.448,
"max_ms": 8.388,
"histogram": [
26423,
293,
16,
9,
4,
5,
1,
1,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "village",
"repeat": 2,
"frames": 25996,
"seconds": 12.0,
"avg_fps": 2166.285,
"low_1pct_fps": 528.15,
"low_01pct_fps": 209.522,
"p50_ms": 0.43,
"p95_ms": 0.662,
"p99_ms": 1.308,
"p999_ms": 2.477,
"max_ms": 11.033,
"histogram": [
25615,
338,
23,
5,
5,
5,
2,
2,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 0,
"frames": 31855,
"seconds": 12.0,
"avg_fps": 2654.549,
"low_1pct_fps": 667.966,
"low_01pct_fps": 257.945,
"p50_ms": 0.341,
"p95_ms": 0.519,
"p99_ms": 0.932,
"p999_ms": 1.761,
"max_ms": 10.944,
"histogram": [
31558,
275,
6,
2,
7,
0,
4,
2,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 1,
"frames": 31763,
"seconds": 12.0,
"avg_fps": 2646.916,
"low_1pct_fps": 685.008,
"low_01pct_fps": 270.233,
"p50_ms": 0.344,
"p95_ms": 0.52,
"p99_ms": 0.94,
"p999_ms": 1.685,
"max_ms": 11.406,
"histogram": [
31474,
272,
3,
4,
2,
2,
1,
3,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "forest",
"repeat": 2,
"frames": 24818,
"seconds": 12.0,
"avg_fps": 2068.162,
"low_1pct_fps": 521.303,
"low_01pct_fps": 229.228,
"p50_ms": 0.439,
"p95_ms": 0.767,
"p99_ms": 1.284,
"p999_ms": 2.351,
"max_ms": 11.468,
"histogram": [
24356,
410,
36,
4,
4,
3,
2,
2,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 0,
"frames": 32039,
"seconds": 12.0,
"avg_fps": 2669.9,
"low_1pct_fps": 741.491,
"low_01pct_fps": 294.727,
"p50_ms": 0.345,
"p95_ms": 0.501,
"p99_ms": 0.86,
"p999_ms": 1.431,
"max_ms": 9.257,
"histogram": [
31771,
250,
3,
2,
4,
6,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 1,
"frames": 31854,
"seconds": 12.0,
"avg_fps": 2654.471,
"low_1pct_fps": 747.759,
"low_01pct_fps": 302.422,
"p50_ms": 0.347,
"p95_ms": 0.503,
"p99_ms": 0.853,
"p999_ms": 1.404,
"max_ms": 13.925,
"histogram": [
31580,
261,
3,
2,
0,
1,
3,
3,
0,
0,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "ocean",
"repeat": 2,
"frames": 25022,
"seconds": 12.0,
"avg_fps": 2085.121,
"low_1pct_fps": 576.803,
"low_01pct_fps": 262.183,
"p50_ms": 0.428,
"p95_ms": 0.758,
"p99_ms": 1.214,
"p999_ms": 2.109,
"max_ms": 9.206,
"histogram": [
24600,
390,
20,
3,
2,
3,
2,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 0,
"frames": 33745,
"seconds": 12.0,
"avg_fps": 2812.075,
"low_1pct_fps": 736.0,
"low_01pct_fps": 258.279,
"p50_ms": 0.327,
"p95_ms": 0.471,
"p99_ms": 0.808,
"p999_ms": 1.689,
"max_ms": 10.07,
"histogram": [
33516,
205,
7,
0,
7,
4,
3,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 1,
"frames": 33294,
"seconds": 12.0,
"avg_fps": 2774.461,
"low_1pct_fps": 763.45,
"low_01pct_fps": 295.503,
"p50_ms": 0.334,
"p95_ms": 0.471,
"p99_ms": 0.813,
"p999_ms": 1.63,
"max_ms": 8.512,
"histogram": [
33056,
221,
3,
5,
1,
2,
3,
2,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
},
{
"phase": "mountain",
"repeat": 2,
"frames": 26747,
"seconds": 12.0,
"avg_fps": 2228.824,
"low_1pct_fps": 599.44,
"low_01pct_fps": 239.602,
"p50_ms": 0.403,
"p95_ms": 0.678,
"p99_ms": 1.107,
"p999_ms": 2.054,
"max_ms": 9.178,
"histogram": [
26418,
298,
13,
6,
2,
8,
0,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
]
}
],
"label": "vanilla-win-9800x3d-5080"
}
@@ -1,106 +0,0 @@
# Horizon v0.2.97 vs vanilla 26.3 on Windows 11: Ryzen 7 9800X3D + RTX 5080 (2026-10-29, RD 8 and 32 rerun 2026-10-30)
The first `tools/perf_bench.py` run on Windows ([docs/benchmark.md](../../docs/benchmark.md)): Horizon, vanilla 26.3 and
vanilla with performance mods, render distances 8, 16 and 32, 1280x720, three games each, every game from a fresh
world. The reports are the `*-win-9800x3d-5080-rd*.json` files next to this page.
```sh
python tools/perf_bench.py --table horizon-win-9800x3d-5080 vanilla-win-9800x3d-5080 vanilla-mods-win-9800x3d-5080
```
## Setup
- **Machine:** AMD Ryzen 7 9800X3D (8 cores, 16 threads), 94 GB RAM (DDR5, EXPO off), NVIDIA GeForce RTX 5080
(driver 617.42), Windows 11 Pro 26200, Balanced power plan, desktop. One 1920x1080 120 Hz display. The game windows
were on the desktop of an unlocked session.
- **Horizon:** release v0.2.97 as the launcher installs it (`--build %APPDATA%\horizon-launcher\versions\v0.2.97`,
`--resources` its `.local\horizon-client\26.3`), Vulkan.
- **Vanilla:** the 26.3 client jar with Fabric Loader 0.19.5 and the driver mod, Java 25.0.5 (Temurin), `-Xmx2G`
with the launcher's G1 flags and the manifest's `-XX:StackShadowPages=32`, OpenGL 3.3.
- **Vanilla + mods:** the same with Sodium mc26.3-0.9.2, Lithium mc26.3-0.26.2, FerriteCore 9.0.0 and
ImmediatelyFast 1.17.1 (`tools/benchmark-deps/mods.lock.json`).
- **Commands:** `python tools/perf_bench.py --game <game> --label <game>-win-9800x3d-5080 --distances <d>
--sizes 1280x720 --repeats 3` (plus `--build` and `--resources` for Horizon), with the games taking turns at
each distance.
- **Memory** is the working set on Windows (what Task Manager shows), sampled from outside the process. Horizon's
GPU figure is its own Vulkan allocator total. `nvidia-smi` gives no per-process figure under WDDM, so vanilla has
none.
## Load
Windows has no load average, so the reports have no `load_avg_1m`. Every game ran on an otherwise idle machine:
- **RD 8 and RD 32** (rerun on 2026-10-30, after the first pass had builds running alongside): a script started each
game only once no `rustc`, `cargo`, `link` (or other compiler) process and no other game (`horizon-client`, `java`,
`javaw`, Minecraft) was running, and the machine's CPU load had stayed under 15 % in every 5-second sample for
30 seconds. During each game it sampled every 2 seconds the machine's CPU load and the CPU of everything outside the
benchmark's own processes. A game during which a compiler or another game ran, or other processes used over 15 % of
the machine for 10 seconds, was discarded and run again: two of the 20 games were (vanilla + mods at RD 32, a
build started during one, background processes during the other).
- **RD 16** (2026-10-29): no `rustc`, `cargo` or `link` process at any point, the load logged every 5 seconds.
| Game | RD | Mean / max CPU load (machine, the game included) | Other processes' CPU, mean / max | Compiler processes |
|---|---|---|---|---|
| Horizon | 8 | 18 % / 49 % | 6 % / 12 % | 0 |
| Vanilla | 8 | 28 % / 75 % | 7 % / 20 % | 0 |
| Vanilla + mods | 8 | 30 % / 81 % | 7 % / 20 % | 0 |
| Horizon | 16 | 29 % / 80 % | – | 0 |
| Vanilla | 16 | 41 % / 91 % | – | 0 |
| Vanilla + mods | 16 | 51 % / 90 % | – | 0 |
| Horizon | 32 | 36 % / 100 % | 5 % / 15 % | 0 |
| Vanilla | 32 | 39 % / 73 % | 6 % / 18 % | 0 |
| Vanilla + mods | 32 | 42 % / 88 % | 6 % / 21 % | 0 |
"Other processes" is the machine's load minus the benchmark's own processes (the game and `perf_bench.py`), in
2-second samples. Most of it is the system's share of the game's own drawing (the graphics driver and the
compositor), which no process of the benchmark is charged for; the desktop apps left open (a browser, chat apps)
briefly reached 5 % at most. RD 16's load was logged from outside every 5 seconds, so it has no such split, and its mean includes the time between
games. Compared with the first pass, the idle RD 8 runs give Horizon about 10 % higher averages and about 50 % higher
1% lows, and vanilla up to 10 % higher averages.
## Results
Mean of 3 games ± 95% confidence interval. FPS over the 12-second flight at 16 blocks/s (average / 1% low /
0.1% low):
| RD | scene | Horizon v0.2.97 | Vanilla 26.3 | Vanilla + mods |
| --- | --- | --- | --- | --- |
| 8 | forest | 3495 ±276 / 1295 ±397 / 859 ±298 | 2457 ±836 / 625 ±224 / 252 ±52 | 2425 ±65 / 733 ±30 / 250 ±22 |
| 8 | mountain | 3376 ±67 / 1384 ±168 / 850 ±256 | 2605 ±811 / 700 ±218 / 264 ±71 | 2538 ±167 / 760 ±34 / 241 ±44 |
| 8 | ocean | 3346 ±147 / 1358 ±237 / 912 ±235 | 2470 ±828 / 689 ±241 / 286 ±53 | 2432 ±82 / 764 ±37 / 262 ±37 |
| 8 | village | 2942 ±197 / 1271 ±146 / 839 ±94 | 2217 ±112 / 545 ±37 / 215 ±14 | 2104 ±101 / 577 ±84 / 196 ±47 |
| 16 | forest | 2424 ±138 / 709 ±165 / 401 ±100 | 1912 ±324 / 402 ±89 / 149 ±25 | 1746 ±32 / 461 ±27 / 179 ±9 |
| 16 | mountain | 1961 ±99 / 537 ±96 / 297 ±75 | 1653 ±153 / 332 ±27 / 113 ±8 | 1500 ±55 / 408 ±40 / 140 ±10 |
| 16 | ocean | 2201 ±183 / 554 ±251 / 325 ±326 | 1861 ±289 / 446 ±142 / 165 ±29 | 1815 ±119 / 514 ±142 / 192 ±58 |
| 16 | village | 1712 ±192 / 593 ±80 / 358 ±69 | 1218 ±65 / 318 ±16 / 127 ±5 | 1282 ±162 / 343 ±25 / 132 ±12 |
| 32 | forest | 1389 ±70 / 504 ±33 / 330 ±118 | 1203 ±51 / 228 ±13 / 108 ±12 | 929 ±8 / 313 ±41 / 129 ±32 |
| 32 | mountain | 1086 ±34 / 258 ±78 / 108 ±37 | 815 ±61 / 55 ±13 / 8 ±3 | 645 ±10 / 166 ±12 / 86 ±21 |
| 32 | ocean | 1189 ±27 / 155 ±9 / 68 ±8 | 1223 ±33 / 236 ±17 / 99 ±21 | 1017 ±14 / 325 ±38 / 117 ±28 |
| 32 | village | 1164 ±9 / 416 ±39 / 216 ±86 | 882 ±48 / 184 ±12 / 83 ±17 | 926 ±17 / 250 ±5 / 93 ±11 |
Startup, loading and memory (means of 3 games):
| RD | | Horizon v0.2.97 | Vanilla 26.3 | Vanilla + mods |
| --- | --- | --- | --- | --- |
| 8 | start to title / in-world | 3.0 s / 6.1 s | 7.7 s / 13.9 s | 11.1 s / 17.6 s |
| 8 | mean scene load | 1.3 s | 4.0 s | 3.6 s |
| 8 | working set, steady / peak | 1082 / 1172 MB | 1913 / 2120 MB | 1904 / 2053 MB |
| 16 | start to title / in-world | 3.2 s / 7.2 s | 7.7 s / 19.9 s | 10.8 s / 23.5 s |
| 16 | mean scene load | 2.4 s | 9.2 s | 9.0 s |
| 16 | working set, steady / peak | 1236 / 1459 MB | 2300 / 2540 MB | 2327 / 2496 MB |
| 32 | start to title / in-world | 2.9 s / 10.5 s | 7.5 s / 35.4 s | 11.0 s / 39.2 s |
| 32 | mean scene load | 5.7 s | 21.1 s | 19.9 s |
| 32 | working set, steady / peak | 1730 / 2045 MB | 2799 / 2892 MB | 2895 / 2965 MB |
## What it shows
- At RD 8 and 16, Horizon's average FPS is 18–42 % above vanilla's in every scene. Its 1% lows are 1.2–2.3 times
vanilla's and its 0.1% lows 2.0–3.9 times. On this CPU and GPU the performance mods leave vanilla's averages
level or slightly lower, and raise its 1% lows by 6–23 %.
- At RD 32, Horizon's average is 15–33 % above vanilla's over the forest, the mountain and the village, with 1% lows
2.2–4.7 times vanilla's. Over the ocean its average is level with vanilla's, but its lows are lower than vanilla's
and the modded client's (155 vs 236 and 325 FPS 1% low, 68 vs 99 and 117 FPS 0.1% low), on an idle machine too.
That scene is worth a closer look.
- Horizon reaches the title screen 2.4–2.6 times faster than vanilla (3.4–3.8 times faster than the modded client)
and loads a scene's chunks 3–4 times faster. Its steady working set is 38–46 % smaller.
- Each game uses its own graphics API: Horizon Vulkan, vanilla OpenGL. That difference is part of what's compared.
+2 -2
View File
@@ -4,10 +4,10 @@ version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.86"
description = "cargo horizon-mod new/build/run/check: make Horizon content mods (docs/mods.md)"
description = "cargo horizon-mod new/build/run/check: make Horizon mods in Rust (docs/mods.md)"
[dependencies]
horizon-mods = { path = "../horizon-mods", default-features = false, features = ["index"] }
horizon-mods = { path = "../horizon-mods", default-features = false, features = ["pack", "runtime", "index"] }
serde_json = "1.0.151"
[lints]
+167 -18
View File
@@ -1,19 +1,35 @@
//! `cargo horizon-mod check <file>`: what the registry checks of a submission,
//! run anywhere: its kind's own checks (docs/api/mod-index.md), its signature
//! when given a key, and for a `.hmod` that it is content only.
//! when given a key, and for a mod a trial run in the sandbox: it must start,
//! survive ticks, frames, a chat line and each of its commands (a server mod:
//! a player joining, chatting, typing them and leaving), and import no more
//! than its capabilities.
use horizon_mods::{
Package,
Clock, GameMode, Mods, Output, Package, Player, ServerPlayer, Snapshot, Status,
index::{self, Facts, Kind},
manifest::component_imports,
};
use serde_json::{Value, json};
use std::path::Path;
/// How long the trial run plays: two seconds of game.
const TICKS: u64 = 40;
const FRAMES_PER_TICK: u64 = 3;
pub struct Report {
pub kind: Kind,
pub facts: Facts,
pub sha256: String,
pub size: u64,
pub signed: bool,
/// A mod has code to run (a content mod may have none).
pub code: bool,
/// A mod's component imports.
pub imports: Vec<String>,
/// A mod's commands, each run once.
pub commands: Vec<String>,
/// What the mod showed during the trial run.
pub output: Vec<String>,
}
impl Report {
@@ -37,6 +53,10 @@ impl Report {
"sha256": self.sha256,
"size": self.size,
"signed": self.signed,
"code": self.code,
"imports": self.imports,
"commands": self.commands,
"output": self.output,
})
}
@@ -80,8 +100,18 @@ impl Report {
if self.kind == Kind::NativeMod {
out += " native source: unsandboxed; not executed by the registry check. Compile and test against the exact pinned Horizon and Mixins revisions before review.\n";
}
if self.kind == Kind::Mod {
if self.kind == Kind::Mod && !self.code {
out += " no code: content only, nothing to run\n";
} else if self.kind == Kind::Mod {
let commands = if self.commands.is_empty() {
String::new()
} else {
format!(", /{}", self.commands.join(", /"))
};
out += &format!(
" trial run: started, {TICKS} ticks, {} frames, a chat line{commands}: ok\n",
TICKS * FRAMES_PER_TICK
);
}
out
}
@@ -123,26 +153,145 @@ pub fn check(
(None, None) => false,
_ => return Err("--key and --signature go together".into()),
};
if kind == Kind::Mod {
content_only(path)?;
}
Ok(Report {
let mut report = Report {
kind,
facts,
sha256: index::sha256_file(path)?,
size,
signed,
})
code: false,
imports: Vec::new(),
commands: Vec::new(),
output: Vec::new(),
};
if report.kind == Kind::Mod {
trial_run(path, &mut report)?;
}
Ok(report)
}
/// A mod is content only: WebAssembly code mods don't run any more, code mods are native
/// (`.hnmod`, docs/native-mods.md). `inspect` already read its content as the game does.
fn content_only(path: &Path) -> Result<(), String> {
match Package::read(path)?.wasm {
Some(_) => Err(
"it has WebAssembly code, which Horizon doesn't run any more: make it a native mod (docs/native-mods.md)"
.into(),
),
/// Runs a mod in the sandbox, as the game does, from a scratch copy so its
/// storage lands in a folder removed afterwards. A content mod has no code to
/// run: `inspect` already read its content as the game does.
fn trial_run(path: &Path, report: &mut Report) -> Result<(), String> {
let package = Package::read(path)?;
let Some(wasm) = package.wasm.as_deref() else {
return Ok(());
};
report.code = true;
report.imports = component_imports(wasm)?;
package
.manifest
.check_imports(report.imports.iter().map(String::as_str))?;
let dir = std::env::temp_dir().join(format!("horizon-mod-check-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let copy = dir.join("mod.hmod");
let result = std::fs::copy(path, &copy)
.map_err(|e| e.to_string())
.and_then(|_| play(&copy, report));
let _ = std::fs::remove_dir_all(&dir);
result
}
fn play(path: &Path, report: &mut Report) -> Result<(), String> {
let mut mods = Mods::load(&[path.to_path_buf()], |_| true, |_| false);
let failed = |mods: &Mods| match &mods.entries()[0].status {
Status::Failed(reason) => Some(reason.clone()),
_ => None,
};
if let Some(reason) = failed(&mods) {
return Err(format!("it didn't start: {reason}"));
}
let client: Vec<String> = mods.commands().map(str::to_owned).collect();
let server: Vec<String> = mods.server_commands().map(|c| c.name.clone()).collect();
report.commands = [client.clone(), server.clone()].concat();
// A server mod plays with one player on, who joins, chats and leaves.
let steve = ServerPlayer {
id: "00000000-0000-4000-8000-000000000001".into(),
name: "Steve".into(),
x: 0.5,
y: 64.0,
z: 0.5,
dimension: "minecraft:overworld".into(),
game_mode: GameMode::Survival,
health: 20.0,
};
let snapshot = |t: u64| Snapshot {
player: Some(Player {
x: 0.5 + t as f64 * 0.1,
y: 64.0,
z: 0.5,
yaw: 90.0,
pitch: 0.0,
health: 20.0,
food: 20,
dimension: "minecraft:overworld".into(),
}),
clock: Some(Clock {
game_time: t,
day_time: 1000 + t,
}),
players: vec![steve.clone()],
// The GUI of a 1280 x 720 window at scale 3.
gui_size: (427.0, 240.0),
..Snapshot::default()
};
mods.set_snapshot(snapshot(0));
mods.player_joined(&steve);
for t in 0..TICKS {
mods.set_snapshot(snapshot(t));
mods.tick(t);
mods.server_tick(t);
for _ in 0..FRAMES_PER_TICK {
mods.frame(1.0 / 60.0);
}
}
mods.chat("<Steve> hello");
mods.player_chat(&steve, "hello");
for name in &client {
mods.command(name);
}
for name in &server {
mods.server_command(&steve, name);
}
mods.set_snapshot(Snapshot::default());
mods.player_left(&steve);
for out in mods.drain() {
report.output.push(match out {
Output::Chat { text, .. } => format!("chat: {text}"),
Output::Tell { text, .. } => format!("tell: {text}"),
Output::Broadcast { text, .. } => format!("broadcast: {text}"),
Output::Feedback { text, error } | Output::Reply { text, error, .. } => {
format!("{}: {text}", if error { "error" } else { "feedback" })
}
Output::Command { line } => format!("command: /{line}"),
Output::QuietCommands { lines, .. } => {
format!("{} quiet command(s)", lines.len())
}
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")),
Output::SetBlocks {
dimension, blocks, ..
} => {
format!("set {} block(s) in {dimension}", blocks.len())
}
Output::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its screen".to_string(),
Output::PlaceRecipe { book_id, all } => {
format!("placed recipe {book_id}{}", if all { " (all)" } else { "" })
}
Output::Give { item, count, .. } => format!("gave {count} {item}"),
Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s")
}
});
}
let shapes = mods.hud_shapes().count();
if shapes > 0 {
report.output.push(format!("drew {shapes} HUD shape(s)"));
}
match failed(&mods) {
Some(reason) => Err(format!("it stopped: {reason}")),
None => Ok(()),
}
}
@@ -167,7 +316,7 @@ mod tests {
.text()
.contains("cozy 1.0.0 (modpack, format 1, for 26.3)")
);
// A mod with WebAssembly code is refused: code mods are native.
// The fixture mod's code is a stand-in: its manifest reads, its run fails.
let hmod = fixture("coords_hud-0.1.0.hmod");
let key = std::fs::read_to_string(fixture("test.pub")).unwrap();
let sig = std::fs::read_to_string(fixture("coords_hud-0.1.0.hmod.minisig")).unwrap();
@@ -175,7 +324,7 @@ mod tests {
let e = check(&hmod, Kind::Mod, Some(key), Some(&sig))
.err()
.unwrap();
assert!(e.contains("native mod"), "{e}");
assert!(e.contains("didn't start"), "{e}");
let e = check(
&hmod,
Kind::Mod,
+196 -38
View File
@@ -1,23 +1,32 @@
//! `cargo horizon-mod`: make Horizon content mods (`docs/modpacks.md`): blocks,
//! items, data and assets, no code. Code mods are native (docs/native-mods.md).
//! `cargo horizon-mod`: make Horizon mods in Rust (`docs/mods.md`).
//!
//! - `new <path> [--name "Name"]`: a content mod from the template.
//! - `build`: the `.hmod` in `target/horizon-mod/`, with the mod's `assets/`
//! and `data/`.
//! - `new <path> [--template code|content] [--name "Name"] [--sdk-path <dir>]`:
//! a mod from a template: a Rust crate, or a content mod (no code).
//! - `build [--debug]`: the `.hmod` in `target/horizon-mod/`, with the mod's
//! `assets/` and `data/`; a folder without `Cargo.toml` is content only.
//! - `run [--game <horizon-client>] [-- <game args>]`: build, then play with
//! the mod.
//! the mod; run `build` again and the game reloads it.
//! - `test [--debug] [--hmod <file>] [<name>]`: build, then run the mod's
//! `tests/*.toml` scripts in the sandbox, with no game.
//! - `check <file> [--json]`: what the registry checks of a submission
//! (`.hmod`, `.hnmod`, `.hpack`, resource pack `.zip`, `.hshader`).
//! (`.hmod`, `.hpack`, resource pack `.zip`), with a trial run for a mod.
//! - `registry build|review|check|list`: the registry repository's CI.
use horizon_mods::{Capability, Content, Manifest, Package, manifest::MANIFEST};
use horizon_mods::{
Capability, Content, Manifest, Package,
manifest::{MANIFEST, component_imports, componentize},
testing::{Script, TestGame},
};
mod check;
mod registry;
use std::{
path::{Path, PathBuf},
process::{Command, ExitCode},
process::{Command, ExitCode, Stdio},
};
const TARGET: &str = "wasm32-unknown-unknown";
const SDK_GIT: &str = "{ git = \"https://github.com/horizon-rust/horizon\" }";
fn main() -> ExitCode {
// Cargo runs `cargo-horizon-mod horizon-mod <args>`.
let mut args: Vec<String> = std::env::args().skip(1).collect();
@@ -26,13 +35,14 @@ fn main() -> ExitCode {
}
let result = match args.first().map(String::as_str) {
Some("new") => new(&args[1..]),
Some("build") => build().map(|p| {
Some("build") => build(!args.iter().any(|a| a == "--debug")).map(|p| {
println!("Built {}", p.display());
}),
Some("run") => run(&args[1..]),
Some("test") => test(&args[1..]),
Some("check") => check(&args[1..]),
Some("registry") => registry::main(&args[1..]),
_ => Err("usage: cargo horizon-mod new <path> [--name \"Name\"] | build | run [--game <horizon-client>] [-- <game args>] | check <file> [--kind <kind>] [--key <public key> --signature <file.minisig>] [--json] | registry build|review|check|list".into()),
_ => Err("usage: cargo horizon-mod new <path> [--template code|content] | build [--debug] | run [--game <horizon-client>] [-- <game args>] | test [--debug] [--hmod <file>] [<name>] | check <file> [--kind <kind>] [--key <public key> --signature <file.minisig>] [--json] | registry build|review|check|list".into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
@@ -73,9 +83,31 @@ fn new(args: &[String]) -> Result<(), String> {
})
.collect();
let name = flag(args, "--name").map_or_else(|| base.replace(['-', '_'], " "), str::to_string);
let fill = |t: &str| t.replace("{id}", &id).replace("{name}", &name);
let sdk = match flag(args, "--sdk-path") {
Some(p) => {
let p = std::fs::canonicalize(p).map_err(|e| format!("--sdk-path {p}: {e}"))?;
format!("{{ path = {:?} }}", p.display().to_string())
}
None => SDK_GIT.to_string(),
};
let fill = |t: &str| {
t.replace("{crate}", &id.replace('_', "-"))
.replace("{id}", &id)
.replace("{name}", &name)
.replace("{sdk}", &sdk)
};
let code = [
("Cargo.toml", include_str!("../template/Cargo.toml.in")),
(MANIFEST, include_str!("../template/horizon-mod.toml")),
("src/lib.rs", include_str!("../template/src/lib.rs")),
(".gitignore", include_str!("../template/gitignore")),
(
"tests/hello.toml",
include_str!("../template/tests/hello.toml"),
),
];
// A block copying a vanilla one, with its model, name, loot, recipe and tag.
let files = [
let content = [
(
MANIFEST,
include_str!("../template/content/horizon-mod.toml"),
@@ -114,12 +146,12 @@ fn new(args: &[String]) -> Result<(), String> {
),
(".gitignore", include_str!("../template/gitignore")),
];
if flag(args, "--template").is_some_and(|t| t != "content") {
return Err(
"only content mods are made here: code mods are native (docs/native-mods.md)".into(),
);
}
for (file, text) in files {
let files: &[(&str, &str)] = match flag(args, "--template").unwrap_or("code") {
"code" => &code,
"content" => &content,
other => return Err(format!("no template {other}: code or content")),
};
for &(file, text) in files {
let file = fill(file);
let file = file.as_str();
let to = dir.join(file);
@@ -137,24 +169,29 @@ fn new(args: &[String]) -> Result<(), String> {
Ok(())
}
/// Packs the content mod in the current folder into `target/horizon-mod/<id>.hmod`: the
/// manifest and the files in `assets/` and `data/`.
fn build() -> Result<PathBuf, String> {
build_in(Path::new("."))
/// Builds the mod in the current folder and packs `target/horizon-mod/<id>.hmod`:
/// the manifest, the crate's component (none without a `Cargo.toml`: a
/// content mod) and the files in `assets/` and `data/`.
fn build(release: bool) -> Result<PathBuf, String> {
build_in(Path::new("."), release)
}
fn build_in(root: &Path) -> Result<PathBuf, String> {
fn build_in(root: &Path, release: bool) -> Result<PathBuf, String> {
let manifest_text = std::fs::read_to_string(root.join(MANIFEST))
.map_err(|e| format!("{MANIFEST}: {e} (run this in a mod's folder)"))?;
let manifest = Manifest::parse(&manifest_text)?;
if root.join("Cargo.toml").exists() {
return Err("a Cargo.toml: code mods are native now (docs/native-mods.md)".into());
}
if !manifest.capabilities.contains(&Capability::Registries) {
let (wasm, target_dir) = if root.join("Cargo.toml").exists() {
let (wasm, target) = compile(root, release)?;
// The game refuses a component importing capabilities the manifest lacks.
manifest.check_imports(component_imports(&wasm)?.iter().map(String::as_str))?;
(Some(wasm), target)
} else if manifest.capabilities.contains(&Capability::Registries) {
(None, root.join("target"))
} else {
return Err(format!(
"a content mod has capability registries in {MANIFEST}"
"no Cargo.toml: only a content mod (capability registries in {MANIFEST}) has no code"
));
}
};
// The same checks as the game's, and the files in the order it lists them.
let content = Content::read(root, &manifest)?;
let mut reader = content.reader()?;
@@ -163,17 +200,53 @@ fn build_in(root: &Path) -> Result<PathBuf, String> {
files.push((name.as_str(), reader.read(name)?));
}
let files: Vec<(&str, &[u8])> = files.iter().map(|(n, b)| (*n, b.as_slice())).collect();
let dir = root.join("target/horizon-mod");
let dir = target_dir.join("horizon-mod");
std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
let path = dir.join(format!("{}.hmod", manifest.id));
// Write then rename, so a running game never reads half a file.
let partial = path.with_extension("hmod.partial");
let bytes = Package::write_files(&manifest_text, None, &files)?;
let bytes = Package::write_files(&manifest_text, wasm.as_deref(), &files)?;
std::fs::write(&partial, bytes).map_err(|e| e.to_string())?;
std::fs::rename(&partial, &path).map_err(|e| e.to_string())?;
Ok(path)
}
/// Builds the crate for WebAssembly: its component, and Cargo's target folder.
fn compile(root: &Path, release: bool) -> Result<(Vec<u8>, PathBuf), String> {
let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into());
let mut cmd = Command::new(cargo);
cmd.current_dir(root).args([
"build",
"--lib",
"--target",
TARGET,
"--message-format=json-render-diagnostics",
]);
if release {
cmd.arg("--release");
}
let out = cmd
.stderr(Stdio::inherit())
.output()
.map_err(|e| e.to_string())?;
if !out.status.success() {
return Err(format!(
"cargo build failed (is the target installed? rustup target add {TARGET})"
));
}
let core = String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.filter(|m| m["reason"] == "compiler-artifact")
.flat_map(|m| m["filenames"].as_array().cloned().unwrap_or_default())
.filter_map(|f| f.as_str().map(PathBuf::from))
.rfind(|f| f.extension().is_some_and(|e| e == "wasm"))
.ok_or("the build made no .wasm: is the crate a cdylib?")?;
let wasm = componentize(&std::fs::read(&core).map_err(|e| e.to_string())?)?;
let target = core.ancestors().nth(3).ok_or("unexpected target folder")?;
Ok((wasm, target.to_path_buf()))
}
/// `check <file>`: the registry's checks of a submission, printed; fails
/// when one does.
fn check(args: &[String]) -> Result<(), String> {
@@ -205,14 +278,74 @@ fn check(args: &[String]) -> Result<(), String> {
Ok(())
}
/// `test`: every `tests/*.toml` script (those whose name holds `<name>`)
/// against the built mod, or the `.hmod` given with `--hmod`.
fn test(args: &[String]) -> Result<(), String> {
let hmod = match flag(args, "--hmod") {
Some(p) => PathBuf::from(p),
None => build(!args.iter().any(|a| a == "--debug"))?,
};
let filter = args
.iter()
.enumerate()
.find(|(i, a)| !a.starts_with("--") && (*i == 0 || args[i - 1] != "--hmod"))
.map(|(_, a)| a.as_str());
let mut scripts: Vec<PathBuf> = std::fs::read_dir("tests")
.map_err(|e| {
format!(
"tests/: {e} (a mod's tests are tests/<name>.toml: docs/mods.md, \"Testing a mod\")"
)
})?
.filter_map(|e| Some(e.ok()?.path()))
.filter(|p| p.extension().is_some_and(|e| e == "toml"))
.filter(|p| filter.is_none_or(|f| p.to_string_lossy().contains(f)))
.collect();
scripts.sort();
if scripts.is_empty() {
return Err("no tests/*.toml to run".into());
}
println!(
"running {} scripts against {}",
scripts.len(),
hmod.display()
);
let mut failed = 0;
for path in &scripts {
let result = std::fs::read_to_string(path)
.map_err(|e| e.to_string())
.and_then(|text| Script::parse(&text))
.and_then(|script| {
let mut game = TestGame::load(&hmod)?;
script.run(&mut game)?;
Ok(script.steps.len())
});
match result {
Ok(steps) => println!("test {} ... ok ({steps} steps)", path.display()),
Err(e) => {
failed += 1;
println!("test {} ... FAILED\n {e}", path.display());
}
}
}
let passed = scripts.len() - failed;
if failed > 0 {
return Err(format!("{failed} failed, {passed} passed"));
}
println!("test result: ok. {passed} passed");
Ok(())
}
fn run(args: &[String]) -> Result<(), String> {
let path = build()?;
let path = build(true)?;
let game = flag(args, "--game")
.map(str::to_string)
.or_else(|| std::env::var("HORIZON_CLIENT").ok())
.unwrap_or_else(|| "horizon-client".into());
let extra = args.iter().skip_while(|a| *a != "--").skip(1);
println!("Starting {game} with {}", path.display());
println!(
"Starting {game} with {} (rebuild with `cargo horizon-mod build` to reload it)",
path.display()
);
let status = Command::new(&game)
.arg("--dev-mod")
.arg(&path)
@@ -231,6 +364,28 @@ fn run(args: &[String]) -> Result<(), String> {
mod tests {
use super::*;
#[test]
fn the_template_is_a_valid_mod() {
let dir = std::env::temp_dir().join(format!("horizon-mod-new-{}", std::process::id()));
let path = dir.join("My-Mod");
new(&[path.display().to_string(), "--name".into(), "My Mod".into()]).unwrap();
let manifest =
Manifest::parse(&std::fs::read_to_string(path.join(MANIFEST)).unwrap()).unwrap();
assert_eq!(
(manifest.id.as_str(), manifest.name.as_str()),
("my_mod", "My Mod")
);
let cargo = std::fs::read_to_string(path.join("Cargo.toml")).unwrap();
assert!(cargo.contains("name = \"my-mod\"") && cargo.contains(SDK_GIT));
let script = std::fs::read_to_string(path.join("tests/hello.toml")).unwrap();
assert_eq!(Script::parse(&script).unwrap().steps.len(), 3);
assert!(
new(&[path.display().to_string()]).is_err(),
"never overwrites"
);
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn the_content_template_builds_and_checks_with_no_code() {
let dir = std::env::temp_dir().join(format!("horizon-mod-content-{}", std::process::id()));
@@ -242,7 +397,7 @@ mod tests {
];
new(&new_args).unwrap();
assert!(!path.join("Cargo.toml").exists());
let hmod = build_in(&path).unwrap();
let hmod = build_in(&path, true).unwrap();
assert_eq!(hmod, path.join("target/horizon-mod/gems.hmod"));
let package = Package::read(&hmod).unwrap();
assert!(package.wasm.is_none());
@@ -254,14 +409,17 @@ mod tests {
);
assert_eq!(content.files.len(), 8, "{:?}", content.files);
let report = check::check(&hmod, check::kind_of(&hmod).unwrap(), None, None).unwrap();
assert!(!report.code);
assert!(
report.text().contains("no code: content only"),
"{}",
report.text()
);
// Code is native now.
std::fs::write(path.join("Cargo.toml"), "").unwrap();
assert!(build_in(&path).unwrap_err().contains("native"));
// Without registries, a mod needs code.
let manifest = std::fs::read_to_string(path.join(MANIFEST)).unwrap();
let manifest = manifest.replace("[\"registries\"]", "[]");
std::fs::write(path.join(MANIFEST), manifest).unwrap();
assert!(build_in(&path, true).unwrap_err().contains("no Cargo.toml"));
assert!(
new(&[
dir.join("x").display().to_string(),
+1 -71
View File
@@ -13,9 +13,7 @@ const SITE: &str = "https://horizon-rust.github.io/horizon-mods/";
const USAGE: &str = "usage: cargo horizon-mod registry build <checkout> --files <dir> --out <index.json> [--release <url>] [--site <url>] [--generated <time>]
cargo horizon-mod registry review <base checkout> <head checkout> --author <login> [--json]
cargo horizon-mod registry check <base checkout> <head checkout> --files <dir>
cargo horizon-mod registry list <checkout>
cargo horizon-mod registry release <checkout> <id> <file> --tag <tag> --published <YYYY-MM-DD> [--notes <file>] [--signature <file>] [--game <version>]
cargo horizon-mod registry page <checkout> <id> <horizon-registry.toml>";
cargo horizon-mod registry list <checkout>";
fn flag<'a>(args: &'a [String], name: &str) -> Option<&'a str> {
super::flag(args, name)
@@ -156,74 +154,6 @@ pub fn main(args: &[String]) -> Result<(), String> {
}
Ok(())
}
// A release of a project's repository, downloaded: the checks of a submission, then the
// version as the index lists it (JSON on stdout), for the registry's release sync.
Some("release") => {
let [checkout, id, file] = pos[..] else {
return Err(USAGE.into());
};
let (tag, published) = (
flag(rest, "--tag").ok_or(USAGE)?,
flag(rest, "--published").ok_or(USAGE)?,
);
let read = |name: &str| {
flag(rest, name)
.map(|p| std::fs::read_to_string(p).map_err(|e| format!("{p}: {e}")))
.transpose()
};
let (notes, signature) = (read("--notes")?, read("--signature")?);
let entry = entry_of(checkout, id)?;
let path = Path::new(file);
let cache = registry::Cache::read(Path::new(checkout), id)?;
let entry = entry.resolved(&cache.page);
let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
crate::check::check(
path,
entry.kind.clone(),
entry.key.as_deref(),
signature.as_deref(),
)?;
let version = registry::release_version(
&entry,
&registry::Release {
tag,
published,
notes: notes.as_deref().unwrap_or(""),
asset: flag(rest, "--name").unwrap_or(name),
game: flag(rest, "--game").unwrap_or("26.3"),
signature: signature.as_deref(),
},
path,
)?;
println!(
"{}",
serde_json::to_string(&version).map_err(|e| e.to_string())?
);
Ok(())
}
// The page file of a project's repository, checked against its entry: the page as JSON.
Some("page") => {
let [checkout, id, file] = pos[..] else {
return Err(USAGE.into());
};
let entry = entry_of(checkout, id)?;
let text = std::fs::read_to_string(file).map_err(|e| format!("{file}: {e}"))?;
let page = registry::page(&entry, &text)?;
println!(
"{}",
serde_json::to_string(&page).map_err(|e| e.to_string())?
);
Ok(())
}
_ => Err(USAGE.into()),
}
}
/// `mods/<id>.toml` of the checkout, which must name a repository.
fn entry_of(checkout: &str, id: &str) -> Result<registry::Entry, String> {
let (entries, _) = registry::load(Path::new(checkout)).map_err(lines)?;
entries
.into_iter()
.find(|e| e.id == id && e.repo.is_some())
.ok_or_else(|| format!("{id}: no entry with a repo"))
}
@@ -0,0 +1,14 @@
[package]
name = "{crate}"
version = "0.1.0"
edition = "2024"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = {sdk}
[profile.release]
opt-level = "s"
lto = true
@@ -0,0 +1,12 @@
id = "{id}"
name = "{name}"
version = "0.1.0"
description = ""
authors = []
# The Horizon mod API the SDK targets.
api = "0.1"
# client: runs in the player's game.
side = "client"
# What the mod may do, shown to players before they turn it on:
# game-read (position, health, time), chat (show messages), hud (draw text).
capabilities = ["chat"]
@@ -0,0 +1,19 @@
use horizon_mod_sdk::{Mod, Registration, chat};
struct MyMod {
greeted: u32,
}
impl Mod for MyMod {
fn init() -> Result<(Self, Registration), String> {
Ok((MyMod { greeted: 0 }, Registration::new().command("hello")))
}
fn command(&mut self, _name: &str, args: &str) -> Result<Option<String>, String> {
self.greeted += 1;
chat::show(&format!("Hello {args}! ({} so far)", self.greeted));
Ok(None)
}
}
horizon_mod_sdk::export_mod!(MyMod);
@@ -0,0 +1,14 @@
# `cargo horizon-mod test` runs every tests/*.toml against the built mod, with no game:
# steps happen in order, and `expect` checks what the mod showed during the step.
# Every key: docs/mods.md, "Testing a mod".
[[step]]
expect.commands = ["hello"]
[[step]]
command = "hello world"
expect.chat = ["Hello world! (1 so far)"]
[[step]]
command = "hello again"
expect.chat = ["Hello again! (2 so far)"]
-14
View File
@@ -1,14 +0,0 @@
[package]
name = "horizon-anticheat"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.85"
description = "The dedicated server's anticheat: its [anticheat] settings, violation levels and the checks' rules, with no game state (docs/anticheat.md)"
[dependencies]
serde = { version = "1", features = ["derive"] }
toml = "1.1"
[lints]
workspace = true
-303
View File
@@ -1,303 +0,0 @@
//! The dedicated server's anticheat (docs/anticheat.md), without the game: the `[anticheat]` section of
//! `server.toml`, each player's violation levels, and the rules of the checks. The server's hub
//! (`horizon_client::lan`) feeds it what players send and carries out what it decides.
//!
//! It is off unless the owner turns it on. A check that fails *flags* the player: its violation level
//! (VL) rises by the flag's weight and falls back by `decay` a second. From `setback` on, the move or
//! action is cancelled (the player is sent back where the server last had them); from `alert` on,
//! online operators and the console are told; from `kick` on, the player is disconnected. Nothing bans.
//! Any threshold at 0 turns that action off.
//!
//! The checks are written from vanilla 26.3's own rules and from what cheats are publicly described to
//! do, never from another anticheat's code.
use serde::{Deserialize, Serialize};
pub mod timer;
/// What one check's violation level leads to.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Actions {
pub setback: f32,
pub alert: f32,
pub kick: f32,
/// Violation level lost each second.
pub decay: f32,
}
macro_rules! checks {
($(
$(#[$doc:meta])*
$field:ident: $Check:ident => $Config:ident [$setback:expr, $alert:expr, $kick:expr, $decay:expr] {
$( $(#[$xdoc:meta])* $extra:ident: $ty:ty = $default:expr, )*
}
)*) => {
/// Every check, in the order of the players' violation levels.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Check { $($Check,)* }
impl Check {
pub const ALL: &[Check] = &[$(Check::$Check,)*];
/// Its name in `server.toml` and in alerts.
pub fn name(self) -> &'static str {
match self { $(Check::$Check => stringify!($field),)* }
}
}
$(
$(#[$doc])*
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct $Config {
pub enabled: bool,
pub setback: f32,
pub alert: f32,
pub kick: f32,
pub decay: f32,
$( $(#[$xdoc])* pub $extra: $ty, )*
}
impl Default for $Config {
fn default() -> Self {
Self {
enabled: true,
setback: $setback,
alert: $alert,
kick: $kick,
decay: $decay,
$($extra: $default,)*
}
}
}
)*
/// `server.toml`'s `[anticheat]`: off by default.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
pub enabled: bool,
/// Tell online operators of an alert in their chat (the console and the log always are).
pub alerts: bool,
/// The permission level a player needs to see alerts.
pub alert_level: u8,
/// Every flag, one line each, relative to the server's folder; empty: no file.
pub log: String,
$(pub $field: $Config,)*
}
impl Default for Config {
fn default() -> Self {
Self {
enabled: false,
alerts: true,
alert_level: 2,
log: "logs/anticheat.log".into(),
$($field: $Config::default(),)*
}
}
}
impl Config {
/// Whether `check` runs: the anticheat and the check both on.
pub fn runs(&self, check: Check) -> bool {
self.enabled && match check { $(Check::$Check => self.$field.enabled,)* }
}
pub fn actions(&self, check: Check) -> Actions {
match check {
$(Check::$Check => {
let c = &self.$field;
Actions { setback: c.setback, alert: c.alert, kick: c.kick, decay: c.decay }
})*
}
}
}
};
}
checks! {
/// Timer: more client ticks than the server's clock allows (a sped-up game). Vanilla's client ends
/// every tick with ServerboundClientTickEndPacket, at the server's tick rate; each one spends a tick's
/// time from a balance that wall-clock time fills, capped so a pause can't be saved up for a burst.
timer: Timer => TimerConfig [2.0, 5.0, 20.0, 0.02] {
/// How far ahead of the clock, in milliseconds, a client may get before it is flagged.
tolerance_ms: f64 = 300.0,
/// The most time, in milliseconds, a quiet connection banks for the ticks that follow (a lag
/// spike's backlog arrives at once).
max_lag_ms: f64 = 1000.0,
}
/// Ground: a move that says it ends on the ground with nothing there to stand on: no-fall (claiming
/// the ground to skip fall damage) and walking on water. The claim is always dropped, so vanilla's
/// fall damage follows; from `setback` on the player is also sent back.
ground: Ground => GroundConfig [5.0, 15.0, 60.0, 2.0] {}
}
/// How many checks there are.
pub const CHECKS: usize = Check::ALL.len();
impl Config {
/// The `[anticheat]` section of a whole `server.toml`; the default (off) when it has none.
pub fn from_server_toml(text: &str) -> Result<Self, String> {
#[derive(Deserialize)]
struct File {
#[serde(default)]
anticheat: Config,
}
// Other sections are the supervisor's to check: only this one is read here.
let mut table: toml::Table = toml::from_str(text).map_err(|e| e.to_string())?;
let mut only = toml::Table::new();
if let Some(section) = table.remove("anticheat") {
only.insert("anticheat".into(), section);
}
let file: File = only
.try_into()
.map_err(|e: toml::de::Error| format!("[anticheat]: {e}"))?;
file.anticheat.check()?;
Ok(file.anticheat)
}
/// Thresholds can't be negative.
pub fn check(&self) -> Result<(), String> {
for &c in Check::ALL {
let a = self.actions(c);
if [a.setback, a.alert, a.kick, a.decay]
.iter()
.any(|v| !v.is_finite() || *v < 0.0)
{
return Err(format!(
"anticheat.{}: setback, alert, kick and decay are numbers from 0 up",
c.name()
));
}
}
Ok(())
}
}
/// What a flag leads to.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Verdict {
/// The check's violation level after the flag.
pub vl: f32,
/// Cancel the move or action.
pub setback: bool,
/// Tell operators and the console (at most once a second per check).
pub alert: bool,
pub kick: bool,
}
/// One player's anticheat state. Clean players cost nothing: levels only change when a check flags.
#[derive(Clone, Debug, Default)]
pub struct Player {
vl: [f32; CHECKS],
/// The server tick of each check's last flag (its decay runs from there).
flagged: [u64; CHECKS],
/// The server tick of each check's last alert.
alerted: [Option<u64>; CHECKS],
pub timer: timer::Balance,
/// The server tick and height where the ground last held the player.
pub ground: Option<(u64, f64)>,
}
impl Player {
/// The check's violation level at `tick`, with its decay since the last flag.
pub fn vl(&self, config: &Config, check: Check, tick: u64) -> f32 {
let i = check as usize;
let seconds = tick.saturating_sub(self.flagged[i]) as f32 / 20.0;
(self.vl[i] - config.actions(check).decay * seconds).max(0.0)
}
/// `check` failed with this weight at server tick `tick`.
pub fn flag(&mut self, config: &Config, check: Check, weight: f32, tick: u64) -> Verdict {
let i = check as usize;
let a = config.actions(check);
let vl = self.vl(config, check, tick) + weight;
self.vl[i] = vl;
self.flagged[i] = tick;
let reached = |threshold: f32| threshold > 0.0 && vl >= threshold;
let alert = reached(a.alert) && self.alerted[i].is_none_or(|t| tick >= t + 20);
if alert {
self.alerted[i] = Some(tick);
}
Verdict {
vl,
setback: reached(a.setback),
alert,
kick: reached(a.kick),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn on() -> Config {
Config {
enabled: true,
..Config::default()
}
}
#[test]
fn off_by_default_and_without_a_section() {
assert!(!Config::default().enabled);
let c = Config::from_server_toml("[server]\nport = 25565\n").unwrap();
assert_eq!(c, Config::default());
assert!(!c.runs(Check::Timer));
assert!(!c.runs(Check::Ground));
}
#[test]
fn reads_its_section() {
let text = "[server]\nport = 1\n[anticheat]\nenabled = true\n[anticheat.timer]\nkick = 0\ntolerance_ms = 500\n";
let c = Config::from_server_toml(text).unwrap();
assert!(c.runs(Check::Timer));
assert_eq!(c.timer.kick, 0.0);
assert_eq!(c.timer.tolerance_ms, 500.0);
assert_eq!(c.timer.alert, TimerConfig::default().alert);
let off = "[anticheat]\nenabled = true\n[anticheat.timer]\nenabled = false\n";
assert!(!Config::from_server_toml(off).unwrap().runs(Check::Timer));
}
#[test]
fn refuses_unknown_keys_and_negative_levels() {
assert!(Config::from_server_toml("[anticheat]\nenable = true\n").is_err());
assert!(Config::from_server_toml("[anticheat.timer]\nkick = -1\n").is_err());
}
#[test]
fn levels_rise_decay_and_act_in_order() {
let mut c = on();
c.timer = TimerConfig {
setback: 2.0,
alert: 3.0,
kick: 5.0,
decay: 1.0,
..TimerConfig::default()
};
let mut p = Player::default();
let v = p.flag(&c, Check::Timer, 1.0, 100);
assert_eq!((v.setback, v.alert, v.kick), (false, false, false));
let v = p.flag(&c, Check::Timer, 1.0, 100);
assert_eq!((v.vl, v.setback, v.alert), (2.0, true, false));
let v = p.flag(&c, Check::Timer, 1.0, 100);
assert!(v.alert && !v.kick);
// At most one alert a second.
assert!(!p.flag(&c, Check::Timer, 0.5, 110).alert);
// 3 at tick 110 (half a level gone, half added); two seconds later two more are gone.
assert_eq!(p.vl(&c, Check::Timer, 150), 1.0);
assert_eq!(p.vl(&c, Check::Timer, 10_000), 0.0);
let v = p.flag(&c, Check::Timer, 5.0, 10_000);
assert!(v.kick && v.alert);
}
#[test]
fn zero_turns_an_action_off() {
let mut c = on();
c.timer.kick = 0.0;
let mut p = Player::default();
assert!(!p.flag(&c, Check::Timer, 1000.0, 1).kick);
}
}
-111
View File
@@ -1,111 +0,0 @@
//! The timer check's balance: how far a client's ticks are behind (positive) or ahead (negative) of the
//! server's clock, in milliseconds.
//!
//! The server adds the wall-clock time of each of its ticks, and every ServerboundClientTickEndPacket
//! takes away the length of one tick at the server's tick rate (vanilla's client ticks at that rate,
//! `TickRateManager.millisecondsPerTick`). The balance is capped at `max_lag_ms` *after* the tick's
//! packets are counted: a slow server tick that handles a second of packets at once also added that
//! second, and a quiet connection banks at most `max_lag_ms` for the burst that ends a lag spike.
use crate::TimerConfig;
#[derive(Clone, Debug, Default)]
pub struct Balance {
pub ms: f64,
}
impl Balance {
/// The start of a server tick that came `elapsed_ms` after the previous one.
pub fn elapse(&mut self, elapsed_ms: f64, config: &TimerConfig) {
self.ms = self.ms.min(config.max_lag_ms) + elapsed_ms;
}
/// One client tick ended, at a tick rate of `tick_rate` a second. Some(how far ahead, in ms) when the
/// client is further ahead than the tolerance; the balance starts again from zero then, so a
/// sustained speed-up is flagged again each time it gets that far ahead.
pub fn tick_end(&mut self, tick_rate: f32, config: &TimerConfig) -> Option<f64> {
self.ms -= 1000.0 / f64::from(tick_rate.max(1.0));
if self.ms < -config.tolerance_ms {
let ahead = -self.ms;
self.ms = 0.0;
return Some(ahead);
}
None
}
/// The tick rate changed or the player arrived: start again.
pub fn reset(&mut self) {
self.ms = 0.0;
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `seconds` of server ticks of `server_ms` each, with `per_tick` client ticks handled in each.
fn run(b: &mut Balance, server_ms: f64, per_tick: f64, seconds: f64) -> usize {
let c = TimerConfig::default();
let mut owed = 0.0;
let mut flags = 0;
for _ in 0..(seconds * 1000.0 / server_ms) as usize {
b.elapse(server_ms, &c);
owed += per_tick;
while owed >= 1.0 {
owed -= 1.0;
flags += usize::from(b.tick_end(20.0, &c).is_some());
}
}
flags
}
#[test]
fn a_vanilla_client_is_never_flagged() {
let mut b = Balance::default();
assert_eq!(run(&mut b, 50.0, 1.0, 600.0), 0);
// A server that runs at 10 ticks a second handles two client ticks in each.
assert_eq!(run(&mut b, 100.0, 2.0, 600.0), 0);
}
#[test]
fn a_slow_server_tick_with_its_backlog_is_not_flagged() {
let (mut b, c) = (Balance::default(), TimerConfig::default());
b.elapse(3000.0, &c);
for _ in 0..60 {
assert_eq!(b.tick_end(20.0, &c), None);
}
}
#[test]
fn a_short_network_stall_is_not_flagged() {
let (mut b, c) = (Balance::default(), TimerConfig::default());
// 800 ms with nothing arriving, then the 16 ticks sent meanwhile.
for _ in 0..16 {
b.elapse(50.0, &c);
}
b.elapse(50.0, &c);
for _ in 0..17 {
assert_eq!(b.tick_end(20.0, &c), None);
}
}
#[test]
fn a_sped_up_client_is_flagged_again_and_again() {
let mut b = Balance::default();
// 10 % faster: 5 ms ahead each tick, 300 ms after 3 s, so close to 20 flags a minute.
let flags = run(&mut b, 50.0, 1.1, 60.0);
assert!((15..=20).contains(&flags), "{flags}");
// Twice as fast: a flag every 7 ticks.
assert!(run(&mut Balance::default(), 50.0, 2.0, 10.0) >= 25);
}
#[test]
fn a_pause_cant_be_saved_for_a_burst() {
let (mut b, c) = (Balance::default(), TimerConfig::default());
for _ in 0..200 {
b.elapse(50.0, &c);
}
let flagged = (0..60).any(|_| b.tick_end(20.0, &c).is_some());
assert!(flagged);
}
}
+13 -352
View File
@@ -21,19 +21,18 @@ use horizon_protocol::{
connection::{ConnWriter, Connection},
crypto::offline_uuid,
ids,
item::Stack,
packets::{
Empty, configuration,
handshake::{self, Intention},
login::{self, ServerHello},
play, recipes,
play,
},
};
use serde_json::json;
use std::{
collections::HashSet,
sync::{
Arc, LazyLock, Mutex,
Arc, Mutex,
atomic::{AtomicBool, AtomicU64, Ordering},
},
thread,
@@ -45,75 +44,29 @@ horizon-bots: load-test bots for a Minecraft Java Edition 26.3 server (offline m
--server HOST:PORT default 127.0.0.1:25565
--bots N default 10
--behaviour B idle, walk, explore or mixed (60 % walk, 20 % explore, 20 % idle); default mixed.
stand: stays on the ground where the server puts it (/tp), for a survival test.
One abusive client, to test a server's limits (run it beside a normal crowd):
flood-move (--flood moves a tick, each 64 to 256 blocks away, ignoring chunks),
flood-acks (--flood chunk batch acks asking for 64 chunks a tick, while exploring),
flood-packets (--flood rotations a tick),
flood-chunks (one move a tick, 9.9 blocks straight ahead: as fast as the
moved-too-quickly check allows, never waiting for chunks),
and --flood a tick of packets that cost the server work:
flood-use (place and break stone around itself), flood-click (inventory
clicks with a stale state), flood-suggest (command suggestions, every
other one 30 000 characters long), flood-book (100 pages of 1024 characters
into a writable book), flood-sign (four 384-character lines on the block
below), flood-recipe (recipe book placements)
--flood N packets a tick for the flood behaviours; default 100
--attack NAME attack the player NAME twice a second, from wherever the bot is (a reach test);
the report gives each bot's last health
--attack-after S start attacking S seconds after joining; default 5
--no-read stop reading from the server once spawned (a client that lets the
server's replies pile up)
--behaviour B idle, walk, explore or mixed (60 % walk, 20 % explore, 20 % idle); default mixed
--join-every SECONDS default 1
--seconds N how long to run after the first bot joins; default 60
--view-distance N what the bots ask for; default 10
--seed N default 12345
--explore-speed B blocks a second an explore bot flies; default 22 (as fast as chunks come)
--name PREFIX bot names: PREFIX0, PREFIX1...; default Bot
--brand B the client brand sent in configuration (minecraft:brand); default none
--height H blocks above spawn the bots fly at (walk, explore, idle); default 24
--ground claim the ground in every move (with --height 0 on a flat world: walking
on it; higher, or over water: a no-fall or jesus cheat, to test an anticheat)
--timer F cheat, to test an anticheat: tick F times as fast as vanilla's client (1.5: 30 Hz)
--report FILE a JSON summary at the end (- prints it after the per-second lines)
";
#[derive(Clone, Copy, Debug, PartialEq)]
enum Behaviour {
Idle,
Stand,
Walk,
Explore,
FloodMove,
FloodAcks,
FloodPackets,
FloodChunks,
FloodUse,
FloodClick,
FloodSuggest,
FloodBook,
FloodSign,
FloodRecipe,
}
impl Behaviour {
fn name(self) -> &'static str {
match self {
Self::Idle => "idle",
Self::Stand => "stand",
Self::Walk => "walk",
Self::Explore => "explore",
Self::FloodMove => "flood-move",
Self::FloodAcks => "flood-acks",
Self::FloodPackets => "flood-packets",
Self::FloodChunks => "flood-chunks",
Self::FloodUse => "flood-use",
Self::FloodClick => "flood-click",
Self::FloodSuggest => "flood-suggest",
Self::FloodBook => "flood-book",
Self::FloodSign => "flood-sign",
Self::FloodRecipe => "flood-recipe",
}
}
}
@@ -128,19 +81,8 @@ struct Options {
view_distance: i8,
seed: u64,
explore_speed: f64,
/// The player to attack, and how long after joining to start.
attack: Option<String>,
attack_after: f64,
flood: usize,
no_read: bool,
height: f64,
ground: bool,
name: String,
/// The `minecraft:brand` to send, if any.
brand: Option<String>,
report: Option<String>,
/// How many times as fast as vanilla's 20 Hz the bots tick (a timer cheat above 1).
timer: f64,
}
fn options() -> Result<Options, String> {
@@ -154,16 +96,8 @@ fn options() -> Result<Options, String> {
view_distance: 10,
seed: 12345,
explore_speed: 22.0,
attack: None,
attack_after: 5.0,
flood: 100,
no_read: false,
height: 24.0,
ground: false,
name: "Bot".into(),
report: None,
brand: None,
timer: 1.0,
};
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
@@ -171,14 +105,6 @@ fn options() -> Result<Options, String> {
print!("{HELP}");
std::process::exit(0);
}
if arg == "--no-read" {
o.no_read = true;
continue;
}
if arg == "--ground" {
o.ground = true;
continue;
}
let value = args.next().ok_or(format!("{arg} needs a value"))?;
let number = |what: &str| format!("{arg} needs {what}, not {value:?}");
match arg.as_str() {
@@ -196,42 +122,14 @@ fn options() -> Result<Options, String> {
"--explore-speed" => {
o.explore_speed = value.parse().map_err(|_| number("blocks a second"))?;
}
"--flood" => o.flood = value.parse().map_err(|_| number("packets a tick"))?,
"--attack" => o.attack = Some(value),
"--attack-after" => o.attack_after = value.parse().map_err(|_| number("seconds"))?,
"--name" => o.name = value,
"--report" => o.report = Some(value),
"--brand" => o.brand = Some(value),
"--height" => o.height = value.parse().map_err(|_| number("blocks"))?,
"--timer" => {
o.timer = value.parse().map_err(|_| number("a speed, like 1.5"))?;
if !(o.timer >= 0.1 && o.timer <= 20.0) {
return Err(format!("--timer {value}: use 0.1 to 20"));
}
}
_ => return Err(format!("unknown option {arg}; --help lists them")),
}
}
const BEHAVIOURS: [&str; 15] = [
"idle",
"walk",
"explore",
"mixed",
"stand",
"flood-move",
"flood-acks",
"flood-packets",
"flood-chunks",
"flood-use",
"flood-click",
"flood-suggest",
"flood-book",
"flood-sign",
"flood-recipe",
];
if !BEHAVIOURS.contains(&o.behaviour.as_str()) {
if !["idle", "walk", "explore", "mixed"].contains(&o.behaviour.as_str()) {
return Err(format!(
"--behaviour {}: use idle, walk, explore, mixed or a flood behaviour (--help lists them)",
"--behaviour {}: use idle, walk, explore or mixed",
o.behaviour
));
}
@@ -258,13 +156,6 @@ struct Bot {
teleport: Mutex<Option<[f64; 3]>>,
error: Mutex<Option<String>>,
joined_after_ms: AtomicU64,
/// The bot stopped reading (--no-read).
deaf: AtomicBool,
/// `--attack`: the target's UUID and, once AddEntity showed it, its entity id.
target: Mutex<(Option<u128>, Option<i32>)>,
attacks: AtomicU64,
/// The last SetHealth.
health: Mutex<Option<f32>>,
}
/// A small deterministic generator (SplitMix64), so every run moves the bots the same way.
@@ -294,89 +185,6 @@ fn raw(id: i32, write: impl FnOnce(&mut Writer)) -> Vec<u8> {
w.data
}
/// Item ids of the pinned version (26.3's item registry).
const STONE: i32 = 1;
const WRITABLE_BOOK: i32 = 1371;
/// The `i`th packet of a costly flood this tick, the bot at `pos`; none for other behaviours.
fn costly(
behaviour: Behaviour,
i: usize,
sequence: i32,
pos: [f64; 3],
random: &mut Random,
) -> Option<Vec<u8>> {
use ids::play::serverbound as sb;
static LONG_COMMAND: LazyLock<String> =
LazyLock::new(|| format!("/msg {}", "x".repeat(30_000)));
static BOOK: LazyLock<Vec<u8>> = LazyLock::new(|| {
play::Serverbound::EditBook(play::EditBook {
slot: 0,
pages: vec!["a".repeat(1024); 100],
title: None,
})
.encode()
});
let block = pos.map(|v| v.floor() as i32);
let packet = match behaviour {
Behaviour::FloodUse => {
// A block within reach: place stone there, or break what is there.
let at = [0, 1, 2].map(|k| block[k] + (random.unit() * 7.0) as i32 - 3);
if i % 2 == 0 {
play::Serverbound::UseItemOn(play::UseItemOn {
hand: 0,
pos: at,
face: 1,
cursor: [0.5, 1.0, 0.5],
inside: false,
world_border: false,
sequence,
})
} else {
play::Serverbound::PlayerAction(play::PlayerAction {
action: 0,
pos: at,
direction: 1,
sequence,
})
}
}
Behaviour::FloodClick => play::Serverbound::ContainerClick(play::ContainerClick {
container: 0,
state: 0,
slot: 36 + (i % 9) as i16,
button: 0,
input: 0,
changed: Vec::new(),
carried: None,
}),
Behaviour::FloodSuggest => {
let text = if i % 2 == 0 {
"/"
} else {
LONG_COMMAND.as_str()
};
return Some(raw(sb::COMMAND_SUGGESTION, |w| {
w.varint(sequence);
w.string(text);
}));
}
Behaviour::FloodBook => return Some(BOOK.clone()),
Behaviour::FloodSign => play::Serverbound::SignUpdate(play::SignUpdate {
pos: [block[0], block[1] - 1, block[2]],
lines: std::array::from_fn(|_| "a".repeat(384)),
front: true,
}),
Behaviour::FloodRecipe => play::Serverbound::PlaceRecipe(recipes::PlaceRecipe {
container: 0,
recipe: (i % 2042) as i32,
use_max: true,
}),
_ => return None,
};
Some(packet.encode())
}
fn err(e: impl std::fmt::Display) -> String {
e.to_string()
}
@@ -444,19 +252,6 @@ fn join(o: &Options, name: &str) -> Result<Connection, String> {
.encode(),
)
.map_err(err)?;
// ClientBrandRetriever: vanilla's client says "vanilla", Horizon's "horizon".
if let Some(brand) = &o.brand {
let mut w = Writer::new();
w.string(brand);
c.send(
&configuration::Serverbound::CustomPayload(configuration::CustomPayload {
channel: "minecraft:brand".into(),
data: w.data,
})
.encode(),
)
.map_err(err)?;
}
loop {
let (id, body) = c.recv().map_err(err)?;
let reply = match id {
@@ -484,9 +279,8 @@ fn join(o: &Options, name: &str) -> Result<Connection, String> {
payload: None,
})
}
configuration::Clientbound::Disconnect(p) => {
let reason = horizon_protocol::text::plain(&p.reason, &Default::default());
return Err(format!("disconnected during configuration: {reason}"));
configuration::Clientbound::Disconnect(_) => {
return Err("disconnected during configuration".into());
}
configuration::Clientbound::FinishConfiguration(_) => {
c.send(&configuration::Serverbound::FinishConfiguration(Empty).encode())
@@ -545,12 +339,6 @@ fn read(
let mut batch = BatchSize::new();
let mut teleports = 0u64;
loop {
if bot.deaf.load(Ordering::Relaxed) {
while bot.online.load(Ordering::SeqCst) {
thread::sleep(Duration::from_millis(100));
}
return;
}
let (id, body) = match reader.recv() {
Ok(packet) => packet,
Err(e) => {
@@ -591,21 +379,6 @@ fn read(
}
Ok(())
}
cb::ADD_ENTITY => {
if let Ok(play::Clientbound::AddEntity(p)) = play::Clientbound::decode(id, &body) {
let mut target = lock(&bot.target);
if target.0 == Some(p.uuid) {
target.1 = Some(p.id);
}
}
Ok(())
}
cb::SET_HEALTH => {
if let Ok(play::Clientbound::SetHealth(p)) = play::Clientbound::decode(id, &body) {
*lock(&bot.health) = Some(p.health);
}
Ok(())
}
cb::CHUNK_BATCH_START => {
batch.started = Instant::now();
Ok(())
@@ -693,7 +466,6 @@ fn run_bot(
};
let (reader, writer) = connection.split();
let writer = Arc::new(Mutex::new(writer));
lock(&bot.target).0 = o.attack.as_deref().map(offline_uuid);
bot.online.store(true, Ordering::SeqCst);
{
let (writer, bot) = (writer.clone(), bot.clone());
@@ -717,31 +489,12 @@ fn run_bot(
.store(asked.elapsed().as_millis() as u64, Ordering::SeqCst);
let send = |body: Vec<u8>| lock(&writer).send(&body).is_ok();
send(raw(sb::PLAYER_LOADED, |_| {}));
bot.deaf.store(o.no_read, Ordering::Relaxed);
// What the costly floods need in hand (creative: the server takes the bot's word for it).
let tool = match behaviour {
Behaviour::FloodUse => Some(Stack::new(STONE, 64)),
Behaviour::FloodBook => Some(Stack::new(WRITABLE_BOOK, 1)),
_ => None,
};
if tool.is_some() {
send(
play::Serverbound::SetCreativeModeSlot(play::SetCreativeModeSlot {
slot: 36,
item: tool,
})
.encode(),
);
send(play::Serverbound::SetCarriedItem(play::SetCarriedItem { slot: 0 }).encode());
}
let mut sequence = 0;
let mut random = Random(o.seed ^ (index as u64).wrapping_mul(0x2545_F491_4F6C_DD1D));
let mut pos = spawn;
let cruise = spawn[1] + o.height;
let cruise = spawn[1] + 24.0;
let heading = random.unit() * std::f64::consts::TAU;
let mut target = pos;
let mut next = Instant::now();
let (joined, mut tick) = (Instant::now(), 0u64);
loop {
if lock(&until).is_some_and(|u| Instant::now() >= u) || !bot.online.load(Ordering::SeqCst) {
break;
@@ -751,46 +504,13 @@ fn run_bot(
pos = at;
}
let here = ((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4);
// The abusive client doesn't wait for its chunk, as a real client must.
if behaviour == Behaviour::Stand {
// Where the server put it, on the ground.
} else if behaviour == Behaviour::FloodMove {
// The last of these moves goes out below, with the tick's end.
pos[1] = cruise;
for _ in 1..o.flood.max(1) {
let angle = random.unit() * std::f64::consts::TAU;
let reach = 64.0 + random.unit() * 192.0;
pos[0] += angle.cos() * reach;
pos[2] += angle.sin() * reach;
send(
play::Serverbound::MovePlayerPos(play::MovePlayerPos {
x: pos[0],
y: pos[1],
z: pos[2],
flags: 0,
})
.encode(),
);
}
let angle = random.unit() * std::f64::consts::TAU;
pos[0] += angle.cos() * 128.0;
pos[2] += angle.sin() * 128.0;
} else if behaviour == Behaviour::FloodChunks {
// Up to cruising height first, then just under the server's 10 blocks a tick:
// every tick asks for new chunks.
if pos[1] < cruise {
pos[1] = (pos[1] + 0.5).min(cruise);
} else {
pos[0] += heading.cos() * 9.9;
pos[2] += heading.sin() * 9.9;
}
} else if !lock(&bot.held).contains(&here) {
if !lock(&bot.held).contains(&here) {
bot.waited.fetch_add(1, Ordering::Relaxed);
} else if pos[1] < cruise {
pos[1] = (pos[1] + 0.5).min(cruise);
} else {
match behaviour {
Behaviour::Idle | Behaviour::Stand => {}
Behaviour::Idle => {}
Behaviour::Walk => {
let (dx, dz) = (target[0] - pos[0], target[2] - pos[2]);
let distance = dx.hypot(dz);
@@ -809,37 +529,7 @@ fn run_bot(
pos[2] += dz / distance * step;
}
}
Behaviour::FloodMove
| Behaviour::FloodChunks
| Behaviour::FloodUse
| Behaviour::FloodClick
| Behaviour::FloodSuggest
| Behaviour::FloodBook
| Behaviour::FloodSign
| Behaviour::FloodRecipe => {}
Behaviour::FloodPackets => {
for i in 0..o.flood {
send(
play::Serverbound::MovePlayerRot(play::MovePlayerRot {
yaw: (i % 360) as f32,
pitch: 0.0,
flags: 0,
})
.encode(),
);
}
}
Behaviour::FloodAcks | Behaviour::Explore => {
if behaviour == Behaviour::FloodAcks {
for _ in 0..o.flood {
send(
play::Serverbound::ChunkBatchReceived(play::ChunkBatchReceived {
chunks_per_tick: 64.0,
})
.encode(),
);
}
}
Behaviour::Explore => {
// Flying in creative, by default about 22 blocks a second, which keeps new
// chunks coming as fast as the server sends them.
let step = o.explore_speed / 20.0;
@@ -848,28 +538,12 @@ fn run_bot(
}
}
}
// The costly floods go out wherever the bot is, chunks or not (--no-read gets none).
for i in 0..o.flood {
sequence += 1;
if let Some(body) = costly(behaviour, i, sequence, pos, &mut random) {
send(body);
}
}
let target = lock(&bot.target).1;
if let Some(id) = target
&& joined.elapsed().as_secs_f64() >= o.attack_after
&& tick % 10 == 0
{
send(play::Serverbound::Attack(play::Attack { id }).encode());
bot.attacks.fetch_add(1, Ordering::Relaxed);
}
tick += 1;
let ok = send(
play::Serverbound::MovePlayerPos(play::MovePlayerPos {
x: pos[0],
y: pos[1],
z: pos[2],
flags: u8::from(behaviour == Behaviour::Stand || o.ground),
flags: 0,
})
.encode(),
) && send(raw(sb::CLIENT_TICK_END, |_| {}));
@@ -877,7 +551,7 @@ fn run_bot(
bot.online.store(false, Ordering::SeqCst);
break;
}
next += Duration::from_secs_f64(0.05 / o.timer);
next += Duration::from_millis(50);
let now = Instant::now();
if next > now {
thread::sleep(next - now);
@@ -893,19 +567,8 @@ fn run_bot(
fn behaviour_of(mode: &str, index: usize) -> Behaviour {
match mode {
"idle" => Behaviour::Idle,
"stand" => Behaviour::Stand,
"walk" => Behaviour::Walk,
"explore" => Behaviour::Explore,
"flood-move" => Behaviour::FloodMove,
"flood-acks" => Behaviour::FloodAcks,
"flood-packets" => Behaviour::FloodPackets,
"flood-chunks" => Behaviour::FloodChunks,
"flood-use" => Behaviour::FloodUse,
"flood-click" => Behaviour::FloodClick,
"flood-suggest" => Behaviour::FloodSuggest,
"flood-book" => Behaviour::FloodBook,
"flood-sign" => Behaviour::FloodSign,
"flood-recipe" => Behaviour::FloodRecipe,
// mixed: of every five bots, three walk, one explores, one stands.
_ => match index % 5 {
0 | 2 | 4 => Behaviour::Walk,
@@ -1007,8 +670,6 @@ fn main() {
"pulled_back": b.pulled_back.load(Ordering::Relaxed),
"waited_ticks": b.waited.load(Ordering::Relaxed),
"error": *lock(&b.error),
"attacks": b.attacks.load(Ordering::Relaxed),
"health": *lock(&b.health),
})).collect::<Vec<_>>(),
});
if o.report.as_deref() == Some("-") {
@@ -494,11 +494,7 @@ pub fn canonical(tag: &Tag) -> Option<Tag> {
_ => string("minecraft:air"),
},
);
// Direction.LEGACY_ID_CODEC: the 3D data value as a byte.
f.put(
"facing",
Tag::Byte(int(tag.get("facing")).unwrap_or(0) as i8),
);
f.put("facing", Tag::Int(int(tag.get("facing")).unwrap_or(0)));
f.float("progress", 0.0);
f.flag("extending", false);
f.flag("source", false);
@@ -877,23 +873,6 @@ mod tests {
);
}
/// `PistonMovingBlockEntity.saveAdditional`: `facing` through
/// `Direction.LEGACY_ID_CODEC` (a byte), `progress` a float.
#[test]
fn moving_piston_fields_match_vanilla() {
let out = canon(
"{id:\"minecraft:piston\",x:1,y:2,z:3,blockState:{Name:\"minecraft:stone\"},\
facing:5,progress:0.5f,extending:1b,source:0b}",
);
assert_eq!(out.get("facing"), Some(&Tag::Byte(5)));
assert_eq!(out.get("progress"), Some(&f32_tag(0.5)));
assert_eq!(out.get("extending"), Some(&Tag::Byte(1)));
assert_eq!(out.get("source"), Some(&Tag::Byte(0)));
let fresh = canon("{id:\"minecraft:piston\",x:1,y:2,z:3}");
assert_eq!(fresh.get("facing"), Some(&Tag::Byte(0)));
assert_eq!(fresh.get("blockState"), Some(&string("minecraft:air")));
}
#[test]
fn loot_table_replaces_items_and_zero_seed_is_omitted() {
let out = canon(
+54 -252
View File
@@ -1,6 +1,6 @@
//! Text components from commands: `ComponentArgument` reads an SNBT (or JSON)
//! value, `ComponentSerialization` turns it into styled text.
use crate::text::{InlineObject, Style, Text, named_color};
use crate::text::{Style, Text, named_color};
use horizon_world::nbt::Tag;
use serde_json::{Map, Value};
@@ -11,18 +11,13 @@ pub fn parse_snbt(input: &str) -> Result<(Value, usize), String> {
let mut p = Parser {
s: input.as_bytes(),
i: 0,
depth: 0,
};
let v = p.value()?;
Ok((v, p.i))
}
/// Nesting deeper than NBT's own limit (`NbtAccounter`'s 512) is refused
/// rather than overflowing the stack.
const SNBT_MAX_DEPTH: usize = 512;
struct Parser<'a> {
s: &'a [u8],
i: usize,
depth: usize,
}
impl Parser<'_> {
fn ws(&mut self) {
@@ -46,22 +41,57 @@ impl Parser<'_> {
self.ws();
match self.peek() {
Some(b'{') => {
if self.depth >= SNBT_MAX_DEPTH {
return Err(format!("tag nesting too deep at {}", self.i));
self.i += 1;
let mut map = Map::new();
self.ws();
if self.peek() == Some(b'}') {
self.i += 1;
return Ok(Value::Object(map));
}
loop {
self.ws();
let key = self.string()?;
self.expect(b':')?;
map.insert(key, self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b'}') => {
self.i += 1;
return Ok(Value::Object(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
self.depth += 1;
let v = self.object();
self.depth -= 1;
v
}
Some(b'[') => {
if self.depth >= SNBT_MAX_DEPTH {
return Err(format!("tag nesting too deep at {}", self.i));
self.i += 1;
let mut list = Vec::new();
self.ws();
// Typed arrays [B;...], [I;...], [L;...].
if matches!(
self.s.get(self.i..self.i + 2),
Some([b'B' | b'I' | b'L', b';'])
) {
self.i += 2;
}
self.ws();
if self.peek() == Some(b']') {
self.i += 1;
return Ok(Value::Array(list));
}
loop {
list.push(self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b']') => {
self.i += 1;
return Ok(Value::Array(list));
}
_ => return Err("expected ',' or ']'".into()),
}
}
self.depth += 1;
let v = self.array();
self.depth -= 1;
v
}
Some(b'"' | b'\'') => Ok(Value::String(self.string()?)),
Some(_) => {
@@ -75,20 +105,10 @@ impl Parser<'_> {
_ => {
let digits = word
.trim_end_matches(['b', 'B', 's', 'S', 'l', 'L', 'f', 'F', 'd', 'D']);
// Only digits (and an exponent) make a number: `nan`
// or `Infinity`, which Rust's parse would take, stays
// a string.
if digits
.bytes()
.any(|c| c.is_ascii_alphabetic() && c != b'e' && c != b'E')
{
Value::String(word)
} else {
match (digits.parse::<i64>(), digits.parse::<f64>()) {
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
_ => Value::String(word),
}
match (digits.parse::<i64>(), digits.parse::<f64>()) {
(Ok(n), _) if digits.len() + 1 >= word.len() => Value::from(n),
(_, Ok(f)) if digits.len() + 1 >= word.len() => Value::from(f),
_ => Value::String(word),
}
}
})
@@ -96,59 +116,6 @@ impl Parser<'_> {
None => Err("expected a value".into()),
}
}
fn object(&mut self) -> Result<Value, String> {
self.i += 1;
let mut map = Map::new();
self.ws();
if self.peek() == Some(b'}') {
self.i += 1;
return Ok(Value::Object(map));
}
loop {
self.ws();
let key = self.string()?;
self.expect(b':')?;
map.insert(key, self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b'}') => {
self.i += 1;
return Ok(Value::Object(map));
}
_ => return Err("expected ',' or '}'".into()),
}
}
}
fn array(&mut self) -> Result<Value, String> {
self.i += 1;
let mut list = Vec::new();
self.ws();
// Typed arrays [B;...], [I;...], [L;...].
if matches!(
self.s.get(self.i..self.i + 2),
Some([b'B' | b'I' | b'L', b';'])
) {
self.i += 2;
}
self.ws();
if self.peek() == Some(b']') {
self.i += 1;
return Ok(Value::Array(list));
}
loop {
list.push(self.value()?);
self.ws();
match self.peek() {
Some(b',') => self.i += 1,
Some(b']') => {
self.i += 1;
return Ok(Value::Array(list));
}
_ => return Err("expected ',' or ']'".into()),
}
}
}
fn unquoted(&mut self) -> String {
let start = self.i;
while let Some(c) = self.peek() {
@@ -195,7 +162,6 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
}
style.shadow_color = o.get("shadow_color").and_then(shadow_color);
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
style.bold = flag("bold");
style.italic = flag("italic");
@@ -237,7 +203,7 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
_ => None,
};
}
// HoverEvent.ShowText, ShowItem and ShowEntity.
// HoverEvent.ShowText and ShowItem.
if let Some(e) = o.get("hover_event").and_then(Value::as_object) {
match e.get("action").and_then(Value::as_str) {
Some("show_text") => {
@@ -248,9 +214,6 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
Some("show_item") if e.get("id").is_some_and(Value::is_string) => {
style.hover_item = Some(Box::new(Value::Object(e.clone())));
}
Some("show_entity") if e.get("id").is_some_and(Value::is_string) => {
style.hover_entity = Some(Box::new(Value::Object(e.clone())));
}
_ => {}
}
}
@@ -260,28 +223,6 @@ fn object_style(o: &serde_json::Map<String, Value>) -> Style {
.map(str::to_owned);
style
}
/// `Style.shadow_color`: a packed ARGB int or normalized RGBA array.
pub(crate) fn shadow_color(value: &Value) -> Option<u32> {
if let Some(packed) = value.as_i64() {
return i32::try_from(packed).ok().map(|n| n as u32);
}
let rgba = value.as_array()?;
if rgba.len() != 4 {
return None;
}
let channels = rgba
.iter()
.map(|channel| {
// ExtraCodecs.ARGB_COLOR_CODEC reads floats; ARGB.as8BitChannel
// floors each normalized channel multiplied by 255.
let value = channel.as_f64()? as f32;
(value.is_finite() && (0.0..=1.0).contains(&value))
.then_some((value * 255.0_f32).floor() as u32)
})
.collect::<Option<Vec<_>>>()?;
Some(channels[3] << 24 | channels[0] << 16 | channels[1] << 8 | channels[2])
}
/// `ComponentSerialization.CODEC` decoding into text. `selector` components
/// are resolved by `resolve` (ComponentUtils.updateForEntity).
pub fn to_text(v: &Value, resolve: &mut dyn FnMut(&str) -> Text) -> Text {
@@ -322,10 +263,6 @@ pub fn to_text_with(
let style = object_style(o);
let content = if let Some(t) = contents(o) {
t
} else if let Some(object) = inline_object(o, resolve, contents) {
let mut text = Text::literal("\u{fffc}");
text.spans[0].style.inline_object = Some(object);
text
} else if let Some(t) = o.get("text") {
match t {
Value::String(s) => Text::literal(s.clone()),
@@ -362,74 +299,12 @@ pub fn to_text_with(
{
out.push(to_text_with(extra, resolve, contents).with_style(&style));
}
if o.contains_key("object") || o.contains_key("player") || o.contains_key("sprite") {
out.with_component(Value::Object(o.clone()))
} else {
out
}
out
}
Value::Null => Text::empty(),
}
}
fn inline_object(
object: &serde_json::Map<String, Value>,
resolve: &mut dyn FnMut(&str) -> Text,
contents: &mut dyn FnMut(&serde_json::Map<String, Value>) -> Option<Text>,
) -> Option<InlineObject> {
let kind = object.get("object").and_then(Value::as_str);
let fallback = object
.get("fallback")
.map(|value| to_text_with(value, resolve, contents).plain());
match kind {
Some("player") | None if object.contains_key("player") => {
let profile = object.get("player")?.clone();
// PlayerSprite.defaultFallback.
let fallback = fallback.unwrap_or_else(|| {
match profile
.as_str()
.or_else(|| profile.get("name").and_then(Value::as_str))
{
Some(name) => format!("[{name} head]"),
None => "[unknown player head]".to_owned(),
}
});
Some(InlineObject::Player {
profile,
hat: object.get("hat").and_then(Value::as_bool).unwrap_or(true),
fallback,
})
}
Some("atlas") | None if object.contains_key("sprite") => {
let atlas = object
.get("atlas")
.and_then(Value::as_str)
.unwrap_or("minecraft:blocks")
.to_owned();
let sprite = object.get("sprite")?.as_str()?.to_owned();
// AtlasSprite.defaultFallback: short names, the atlas unless blocks.
let fallback = fallback.unwrap_or_else(|| {
let short = |id: &str| match id.split_once(':') {
Some(("minecraft", path)) => path.to_owned(),
Some(_) => id.to_owned(),
None => id.to_owned(),
};
if short(&atlas) == "blocks" {
format!("[{}]", short(&sprite))
} else {
format!("[{}@{}]", short(&sprite), short(&atlas))
}
});
Some(InlineObject::Atlas {
atlas,
sprite,
fallback,
})
}
_ => None,
}
}
/// `CustomName` as text: a string keeps its legacy formatting codes, anything
/// else is a component (`ComponentSerialization`).
pub fn name_text(tag: &Tag) -> Text {
@@ -443,61 +318,6 @@ pub fn name_text(tag: &Tag) -> Text {
mod tests {
use super::*;
#[test]
fn shadow_color_accepts_packed_and_rgba_styles() {
let packed = serde_json::json!({"text": "A", "shadow_color": -16711936});
let text = to_text(&packed, &mut |_| Text::empty());
assert_eq!(text.spans[0].style.shadow_color, Some(0xff00ff00));
assert_eq!(text.component()["shadow_color"], -16711936);
let rgba = serde_json::json!({"text": "A", "shadow_color": [1, 0, 0.5, 1]});
let text = to_text(&rgba, &mut |_| Text::empty());
assert_eq!(text.spans[0].style.shadow_color, Some(0xffff007f));
let translucent = serde_json::json!({"text": "A", "shadow_color": [1, 0, 0.5, 0.5]});
let text = to_text(&translucent, &mut |_| Text::empty());
assert_eq!(text.spans[0].style.shadow_color, Some(0x7fff007f));
let no_shadow = serde_json::json!({"text": "A", "shadow_color": 0});
let text = to_text(&no_shadow, &mut |_| Text::empty());
assert_eq!(text.spans[0].style.shadow_color, Some(0));
}
#[test]
fn player_object_survives_text_parsing_and_keeps_its_siblings() {
let component = serde_json::json!({
"text": "<",
"extra": [
{"object": "player", "player": {"name": "elyapluggin"}, "hat": false,
"fallback": "[head]"},
{"text": " >", "color": "gold"}
]
});
let text = to_text(&component, &mut |_| Text::empty());
assert_eq!(text.plain(), "<[head] >");
assert!(matches!(
&text.spans[1].style.inline_object,
Some(InlineObject::Player { hat: false, .. })
));
assert!(text.spans[2].style.inline_object.is_none());
assert_eq!(text.component(), component);
let sprite = serde_json::json!({"object": "atlas", "sprite": "minecraft:item/porkchop"});
let text = to_text(&sprite, &mut |_| Text::empty());
assert!(matches!(
&text.spans[0].style.inline_object,
Some(InlineObject::Atlas { sprite, .. }) if sprite == "minecraft:item/porkchop"
));
// ObjectContents.visit without a fallback: the sprite's defaultFallback.
assert_eq!(text.plain(), "[item/porkchop]");
let head = serde_json::json!({"object": "player", "player": {"name": "Steve"}});
assert_eq!(
to_text(&head, &mut |_| Text::empty()).plain(),
"[Steve head]"
);
let gui = serde_json::json!({"atlas": "gui", "sprite": "hud/heart/full"});
assert_eq!(
to_text(&gui, &mut |_| Text::empty()).plain(),
"[hud/heart/full@gui]"
);
}
#[test]
fn snbt_and_json_components() {
let input = "{text:'Hi ',color:red,extra:[{text:\"there\",bold:1b}]} rest";
@@ -531,22 +351,4 @@ mod tests {
let t = to_text(&v, &mut |_| Text::empty());
assert_eq!(t.spans[0].style.font, None);
}
#[test]
fn snbt_nesting_is_bounded() {
let nest = |n: usize| format!("{}1{}", "[".repeat(n), "]".repeat(n));
assert!(parse_snbt(&nest(512)).is_ok());
assert!(parse_snbt(&nest(513)).is_err());
assert!(parse_snbt(&nest(100_000)).is_err());
}
#[test]
fn bare_words_that_look_numeric_stay_strings() {
let (v, _) = parse_snbt("{text:nan}").unwrap();
assert_eq!(v["text"], Value::String("nan".into()));
let (v, _) = parse_snbt("{text:Infinity}").unwrap();
assert_eq!(v["text"], Value::String("Infinity".into()));
let (v, _) = parse_snbt("{n:1.5}").unwrap();
assert_eq!(v["n"], Value::from(1.5));
}
}
+18 -87
View File
@@ -1,68 +1,32 @@
//! Key display names (`InputConstants.Key.getDisplayName`), shared by key
//! mappings and `keybind` text components.
use crate::text::Text;
use std::{collections::BTreeMap, sync::RwLock};
/// The keys that write a symbol, with what they write on a US layout.
const SYMBOLS: [(&str, &str); 11] = [
("key.keyboard.minus", "-"),
("key.keyboard.equal", "="),
("key.keyboard.left.bracket", "["),
("key.keyboard.right.bracket", "]"),
("key.keyboard.backslash", "\\"),
("key.keyboard.semicolon", ";"),
("key.keyboard.apostrophe", "'"),
("key.keyboard.grave.accent", "`"),
("key.keyboard.comma", ","),
("key.keyboard.period", "."),
("key.keyboard.slash", "/"),
];
/// What the player's keyboard layout writes on each key that writes
/// something, by key name, as the window reported it (`learn_layout`).
static LAYOUT: RwLock<BTreeMap<String, String>> = RwLock::new(BTreeMap::new());
/// The keyboard layout writes `text` on the key `key` (`key.keyboard.q`):
/// its name from now on, as `SDL_GetKeyFromScancode` names it with SDL's
/// default keycode options. Only letter and symbol keys take it; a letter
/// key keeps its Latin letter on a non-Latin layout (`latin_letters`), and
/// the number row keeps its digits (`french_numbers`).
pub fn learn_layout(key: &str, text: &str) {
let Some(rest) = key.strip_prefix("key.keyboard.") else {
return;
};
let mut chars = text.chars();
let (Some(c), None) = (chars.next(), chars.next()) else {
return;
};
let letter_key = rest.len() == 1 && rest.as_bytes()[0].is_ascii_lowercase();
let latin = c.is_ascii() || ('\u{C0}'..='\u{24F}').contains(&c);
if c.is_control()
|| c.is_whitespace()
|| !(letter_key || SYMBOLS.iter().any(|(k, _)| *k == key))
|| (letter_key && c.is_alphabetic() && !latin)
{
return;
}
if let Ok(mut layout) = LAYOUT.write() {
layout.insert(key.to_owned(), c.to_uppercase().collect());
}
}
/// InputConstants.Key.getDisplayName: what the layout writes on the key,
/// upper-case, else the US layout's character, else by translation.
/// InputConstants.Key.getDisplayName: one-character keys as the upper-case
/// character, others by translation.
pub fn display_name(key: &str) -> Text {
if let Some(label) = LAYOUT.read().ok().and_then(|l| l.get(key).cloned()) {
return Text::literal(label);
}
if let Some(rest) = key.strip_prefix("key.keyboard.")
&& rest.chars().count() == 1
{
let c = rest.to_uppercase();
return Text::literal(c);
}
if let Some((_, s)) = SYMBOLS.iter().find(|(k, _)| *k == key) {
return Text::literal(*s);
let symbol = match key {
"key.keyboard.minus" => Some("-"),
"key.keyboard.equal" => Some("="),
"key.keyboard.left.bracket" => Some("["),
"key.keyboard.right.bracket" => Some("]"),
"key.keyboard.backslash" => Some("\\"),
"key.keyboard.semicolon" => Some(";"),
"key.keyboard.apostrophe" => Some("'"),
"key.keyboard.grave.accent" => Some("`"),
"key.keyboard.comma" => Some(","),
"key.keyboard.period" => Some("."),
"key.keyboard.slash" => Some("/"),
_ => None,
};
if let Some(s) = symbol {
return Text::literal(s);
}
if let Some(n) = key.strip_prefix("key.mouse.")
&& n.parse::<u32>().is_ok()
@@ -72,36 +36,3 @@ pub fn display_name(key: &str) -> Text {
}
Text::translate(key, &[])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn keys_show_what_the_layout_writes() {
// The layout table is shared: these keys are this test's alone.
assert_eq!(display_name("key.keyboard.q").plain(), "Q");
// AZERTY: A on the Q key, M on the semicolon key, a dead ^ on the
// left bracket, a comma on the M key.
learn_layout("key.keyboard.q", "a");
learn_layout("key.keyboard.semicolon", "m");
learn_layout("key.keyboard.left.bracket", "^");
learn_layout("key.keyboard.m", ",");
assert_eq!(display_name("key.keyboard.q").plain(), "A");
assert_eq!(display_name("key.keyboard.semicolon").plain(), "M");
assert_eq!(display_name("key.keyboard.left.bracket").plain(), "^");
assert_eq!(display_name("key.keyboard.m").plain(), ",");
// The number row keeps its digits; a Cyrillic letter, nothing
// printable and keys that write nothing are left alone.
learn_layout("key.keyboard.1", "&");
learn_layout("key.keyboard.f", "а");
learn_layout("key.keyboard.g", "\u{8}");
learn_layout("key.keyboard.tab", "\t");
learn_layout("key.keyboard.h", "ab");
assert_eq!(display_name("key.keyboard.1").plain(), "1");
assert_eq!(display_name("key.keyboard.f").plain(), "F");
assert_eq!(display_name("key.keyboard.g").plain(), "G");
assert_eq!(display_name("key.keyboard.h").plain(), "H");
assert_eq!(display_name("key.keyboard.slash").plain(), "/");
}
}
+1 -51
View File
@@ -40,10 +40,6 @@ static BIDIRECTIONAL: AtomicBool = AtomicBool::new(false);
/// A source of resource files: the prepared root plus packs, highest priority last.
pub trait ResourceSource {
fn read(&self, path: &str) -> Option<Vec<u8>>;
/// Whether `path` is there, without reading it where the source can tell.
fn exists(&self, path: &str) -> bool {
self.read(path).is_some()
}
/// The namespaces under `assets/` (resource packs may add their own).
fn namespaces(&self) -> Vec<String> {
vec!["minecraft".into()]
@@ -60,12 +56,6 @@ impl ResourceSource for Bundled {
"assets/horizon/lang/ru_ru.json" => {
include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json")
}
"assets/horizon/lang/pl_pl.json" => {
include_str!("../../horizon-client/assets/horizon/lang/pl_pl.json")
}
"assets/horizon/lang/uk_ua.json" => {
include_str!("../../horizon-client/assets/horizon/lang/uk_ua.json")
}
_ => return None,
};
Some(body.as_bytes().to_vec())
@@ -78,9 +68,6 @@ impl ResourceSource for std::path::PathBuf {
fn read(&self, path: &str) -> Option<Vec<u8>> {
std::fs::read(self.join(path)).ok()
}
fn exists(&self, path: &str) -> bool {
self.join(path).is_file()
}
fn namespaces(&self) -> Vec<String> {
std::fs::read_dir(self.join("assets"))
.into_iter()
@@ -203,7 +190,7 @@ pub fn available(sources: &[&dyn ResourceSource]) -> Vec<LanguageInfo> {
for (code, info) in value["language"].as_object().into_iter().flatten() {
// Only languages whose file exists somewhere are selectable.
let file = format!("assets/minecraft/lang/{code}.json");
if code != DEFAULT && !sources.iter().any(|s| s.exists(&file)) {
if code != DEFAULT && !sources.iter().any(|s| s.read(&file).is_some()) {
continue;
}
found.insert(
@@ -272,21 +259,6 @@ mod tests {
assert_eq!(en.get("horizon.options.controller"), Some("Controller"));
let ru = Language::load(&[&empty], "ru_ru");
assert_eq!(ru.get("horizon.options.controller"), Some("Геймпад"));
// Every bundled string carries both languages: a key added to one file
// and forgotten in the other shows as a key name on screen.
for key in en.map().keys() {
assert!(ru.get(key).is_some(), "{key} has no ru_ru value");
}
assert_eq!(en.get("horizon.pages.mods"), Some("Mods"));
assert_eq!(ru.get("horizon.pages.mods"), Some("Моды"));
let pl = Language::load(&[&empty], "pl_pl");
assert_eq!(pl.get("horizon.options.controller"), Some("Kontroler"));
assert_eq!(pl.get("horizon.options.vibration"), Some("Wibracje"));
let uk = Language::load(&[&empty], "uk_ua");
assert_eq!(
uk.get("horizon.options.on_screen_keyboard"),
Some("Екранна клавіатура")
);
}
#[test]
@@ -312,26 +284,4 @@ mod tests {
);
assert_eq!(langs[1].label(), "Français (France)");
}
#[test]
fn languages_are_listed_without_reading_their_files() {
struct NoLangReads;
impl ResourceSource for NoLangReads {
fn read(&self, path: &str) -> Option<Vec<u8>> {
assert!(!path.contains("/lang/"), "read {path}");
(path == "assets/pack.mcmeta").then(|| {
br#"{"language":{"fr_fr":{"name":"French"},"de_de":{"name":"German"}}}"#
.to_vec()
})
}
fn exists(&self, path: &str) -> bool {
path == "assets/minecraft/lang/fr_fr.json"
}
}
let langs = available(&[&NoLangReads]);
assert_eq!(
langs.iter().map(|l| l.code.as_str()).collect::<Vec<_>>(),
["en_us", "fr_fr"]
);
}
}
@@ -55,12 +55,6 @@ particle_types! {
Rain = "rain",
Bubble = "bubble",
SulfurBubbles = "sulfur_bubbles",
NoxiousGas = "noxious_gas",
NoxiousGasCloud = "noxious_gas_cloud",
Geyser = "geyser",
GeyserBase = "geyser_base",
GeyserPoof = "geyser_poof",
GeyserPlume = "geyser_plume",
BubblePop = "bubble_pop",
BubbleColumnUp = "bubble_column_up",
CurrentDown = "current_down",
@@ -155,10 +149,6 @@ impl ParticleType {
matches!(
self,
Self::BlockMarker
| Self::Geyser
| Self::GeyserBase
| Self::GeyserPoof
| Self::GeyserPlume
| Self::DamageIndicator
| Self::ExplosionEmitter
| Self::Explosion
@@ -201,8 +191,6 @@ impl ParticleType {
// SpellParticle.
| Self::Effect | Self::InstantEffect | Self::EntityEffect
| Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
// NoxiousGasParticle.
| Self::NoxiousGas
// EmissiveRisingParticle.
| Self::Soul | Self::SculkSoul
// SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
+1 -2
View File
@@ -91,7 +91,6 @@ pub fn effect(id: &str) -> Option<&'static EffectDef> {
/// Namespaced effect ids for mob effect storage.
pub fn namespaced(id: &'static str) -> &'static str {
static IDS: OnceLock<HashMap<&'static str, &'static str>> = OnceLock::new();
let key = id.strip_prefix("minecraft:").unwrap_or(id);
IDS.get_or_init(|| {
EFFECTS
.iter()
@@ -103,7 +102,7 @@ pub fn namespaced(id: &'static str) -> &'static str {
})
.collect()
})
.get(key)
.get(id)
.copied()
.unwrap_or(id)
}
@@ -28,10 +28,6 @@ pub struct Registries {
/// Game rule name -> integer-valued.
pub game_rules: Vec<(String, bool)>,
pub players: Vec<String>,
/// `ClientSuggestionProvider.customCompletionSuggestions`: the extra chat
/// completions the server sent (ClientboundCustomChatCompletionsPacket),
/// each once.
pub custom_completions: std::collections::BTreeSet<String>,
/// Scoreboard objective names, team names and tracked score holders.
pub objectives: Vec<String>,
pub teams: Vec<String>,
@@ -58,12 +54,6 @@ pub struct Registries {
pub function_tags: Vec<String>,
/// The block the source is looking at (relevant coordinates).
pub target_block: Option<[i32; 3]>,
/// `ClientSuggestionProvider.getSelectedEntities`: the UUID of the
/// entity under the crosshair (`Entity.getStringUUID`), if any.
pub selected_entities: Vec<String>,
/// `ClientSuggestionProvider.getAbsoluteCoordinates`: the exact point of
/// that block hit, each coordinate as `%.2f` (`Locale.ROOT`).
pub target_point: Option<[String; 3]>,
/// Every registry's element and tag ids (`minecraft:item` -> ...), as
/// the server's registry access and reloadable registries hold them.
pub by_registry: BTreeMap<String, RegistryIds>,
@@ -91,55 +81,7 @@ pub struct RegistryIds {
pub tags: Vec<String>,
}
const EMPTY: &[String] = &[];
/// ClientboundCustomChatCompletionsPacket.Action.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CustomCompletionAction {
Add,
Remove,
Set,
}
impl CustomCompletionAction {
/// `Action.BY_ID`: `ByIdMap.continuous` with `OutOfBoundsStrategy.ZERO`,
/// so an unknown id is `ADD`.
pub fn from_id(id: i32) -> Self {
match id {
1 => Self::Remove,
2 => Self::Set,
_ => Self::Add,
}
}
}
/// `ClientSuggestionProvider.modifyCustomCompletions`: the server adds,
/// removes or replaces the extra chat completions.
pub fn modify_custom_completions(
set: &mut std::collections::BTreeSet<String>,
action: CustomCompletionAction,
entries: &[String],
) {
match action {
CustomCompletionAction::Add => set.extend(entries.iter().cloned()),
CustomCompletionAction::Remove => {
for e in entries {
set.remove(e);
}
}
CustomCompletionAction::Set => {
set.clear();
set.extend(entries.iter().cloned());
}
}
}
impl Registries {
/// `ClientSuggestionProvider.getCustomTabSuggestions`: what chat (not a
/// command) completes, the online players' names with the server's custom
/// completions, each once.
pub fn custom_tab_suggestions(&self) -> std::collections::BTreeSet<&str> {
self.players
.iter()
.chain(&self.custom_completions)
.map(String::as_str)
.collect()
}
/// Fill what the game did not build itself from vanilla's exported
/// registries (`command-registries.json`, written by
/// `VanillaCommandParseOracle registries`): built-in registries such as
+4 -63
View File
@@ -112,7 +112,6 @@ pub fn style_from_json(v: &Value) -> Style {
.and_then(|h| u32::from_str_radix(h, 16).ok())
});
}
s.shadow_color = o.get("shadow_color").and_then(component::shadow_color);
let flag = |k: &str| o.get(k).and_then(Value::as_bool);
s.bold = flag("bold");
s.italic = flag("italic");
@@ -663,22 +662,10 @@ pub fn name_shown(own: Option<&Team>, viewer: Option<&Team>, v: NameView) -> boo
}
!v.hud_hidden && !v.is_camera && visible && !v.is_vehicle
}
/// `ServerPlayer.die`: whether `other` hears the death message of `dying`
/// (`broadcastSystemMessage`, `broadcastSystemToTeam` or
/// `broadcastSystemToAllExceptTeam`, by the team's death message visibility).
pub fn death_message_reaches(board: &Scoreboard, dying: &str, other: &str) -> bool {
let Some(team) = board.players_team(dying) else {
return true;
};
let same_team = board
.players_team(other)
.is_some_and(|t| t.name == team.name);
match team.death_message_visibility {
Visibility::Always => true,
Visibility::Never => false,
Visibility::HideForOtherTeams => same_team && other != dying,
Visibility::HideForOwnTeam => !same_team,
}
/// `ServerPlayer.die`: whether a player's death message reaches the player
/// themselves (the team broadcasts leave out the dying player).
pub fn own_death_message_shown(team: Option<&Team>) -> bool {
team.is_none_or(|t| t.death_message_visibility == Visibility::Always)
}
// ---- objectives and scores ---------------------------------------------
@@ -1564,49 +1551,3 @@ mod tests {
);
}
}
/// `DamageSource.getLocalizedDeathMessage`: the cause's item with a custom
/// name gets the `<id>.item` message, with the item's name as a third
/// argument.
pub fn death_message_args(
key: &str,
victim: &Text,
cause: &Text,
item: Option<&Text>,
) -> (String, Vec<Text>) {
match item {
Some(item) => (
format!("{key}.item"),
vec![victim.clone(), cause.clone(), item.clone()],
),
None => (key.to_owned(), vec![victim.clone(), cause.clone()]),
}
}
#[cfg(test)]
mod death_message_tests {
use super::*;
#[test]
fn the_death_message_names_the_causes_item_when_it_has_a_custom_name() {
let victim = Text::literal("Steve");
let cause = Text::literal("Zombie");
// DamageSource.getLocalizedDeathMessage: the item variant, with the
// item's name as the third argument.
let (key, args) = death_message_args(
"death.attack.arrow",
&victim,
&cause,
Some(&Text::literal("My Sword")),
);
assert_eq!(key, "death.attack.arrow.item");
assert_eq!(args.len(), 3);
assert_eq!(args[0].plain(), "Steve");
assert_eq!(args[1].plain(), "Zombie");
assert_eq!(args[2].plain(), "My Sword");
// Without a custom name the message keeps its two arguments.
let (key, args) = death_message_args("death.attack.arrow", &victim, &cause, None);
assert_eq!(key, "death.attack.arrow");
assert_eq!(args.len(), 2);
}
}
+30 -79
View File
@@ -58,34 +58,10 @@ pub enum ClickEvent {
OpenFile(String),
}
/// A non-character `minecraft:object` embedded in a text component.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InlineObject {
Player {
profile: Value,
hat: bool,
fallback: String,
},
Atlas {
atlas: String,
sprite: String,
fallback: String,
},
}
impl InlineObject {
pub fn fallback(&self) -> &str {
match self {
Self::Player { fallback, .. } | Self::Atlas { fallback, .. } => fallback,
}
}
}
/// Text style; `None` fields inherit from the enclosing style.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Style {
pub color: Option<u32>,
/// Text component `shadow_color` as packed ARGB. Zero suppresses shadows.
pub shadow_color: Option<u32>,
pub bold: Option<bool>,
pub italic: Option<bool>,
pub underlined: Option<bool>,
@@ -96,15 +72,11 @@ pub struct Style {
pub hover: Option<Box<Text>>,
/// `HoverEvent.ShowItem`: the event's `{id, count?, components?}` object.
pub hover_item: Option<Box<Value>>,
/// `HoverEvent.ShowEntity`: the event's `{id, uuid, name?}` object.
pub hover_entity: Option<Box<Value>>,
/// `Style.insertion`: the text a Shift-click puts in the chat box.
pub insertion: Option<String>,
/// The font (`FontDescription.Resource`), a full id like
/// `minecraft:alt`; the default font when unset.
pub font: Option<String>,
/// Content metadata for a single U+FFFC object span; never inherited.
pub inline_object: Option<InlineObject>,
}
/// A style's `font` field: an identifier (`alt` is `minecraft:alt`).
pub fn font_id(v: &Value) -> Option<String> {
@@ -120,7 +92,6 @@ impl Style {
/// Fill unset fields from `base` (Style.applyTo).
pub fn inherit(&mut self, base: &Style) {
self.color = self.color.or(base.color);
self.shadow_color = self.shadow_color.or(base.shadow_color);
self.bold = self.bold.or(base.bold);
self.italic = self.italic.or(base.italic);
self.underlined = self.underlined.or(base.underlined);
@@ -129,12 +100,11 @@ impl Style {
if self.click.is_none() {
self.click.clone_from(&base.click);
}
// One HoverEvent: its three kinds are inherited together, so a style
// with its own event never picks up another kind from `base`.
if self.hover.is_none() && self.hover_item.is_none() && self.hover_entity.is_none() {
if self.hover.is_none() {
self.hover.clone_from(&base.hover);
}
if self.hover_item.is_none() {
self.hover_item.clone_from(&base.hover_item);
self.hover_entity.clone_from(&base.hover_entity);
}
if self.insertion.is_none() {
self.insertion.clone_from(&base.insertion);
@@ -367,13 +337,7 @@ impl Text {
}
/// Component.getString: the plain characters.
pub fn plain(&self) -> String {
self.spans
.iter()
.map(|s| match &s.style.inline_object {
Some(object) if s.text == "\u{fffc}" => object.fallback(),
_ => s.text.as_str(),
})
.collect()
self.spans.iter().map(|s| s.text.as_str()).collect()
}
pub fn is_empty(&self) -> bool {
self.spans.iter().all(|s| s.text.is_empty())
@@ -439,7 +403,31 @@ impl Text {
continue;
}
let Some(code) = chars.next() else { break };
let next = legacy_format(&style, code, &span.style);
let code = code.to_ascii_lowercase();
let next = if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
// Style.applyLegacyFormat: a colour clears the decorations.
Style {
color: Some(c.2),
bold: Some(false),
italic: Some(false),
underlined: Some(false),
strikethrough: Some(false),
obfuscated: Some(false),
..style.clone()
}
} else {
let mut s = style.clone();
match code {
'k' => s.obfuscated = Some(true),
'l' => s.bold = Some(true),
'm' => s.strikethrough = Some(true),
'n' => s.underlined = Some(true),
'o' => s.italic = Some(true),
'r' => s = span.style.clone(),
_ => {}
}
s
};
if next != style {
if !current.is_empty() {
out.spans.push(Span {
@@ -526,9 +514,8 @@ impl Text {
}
/// The style fields of a component's JSON.
const STYLE_KEYS: [&str; 11] = [
const STYLE_KEYS: [&str; 10] = [
"color",
"shadow_color",
"bold",
"italic",
"underlined",
@@ -549,9 +536,6 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
.map_or_else(|| format!("#{c:06X}"), |n| n.1.to_owned());
out.push(("color".to_owned(), name.into()));
}
if let Some(shadow) = style.shadow_color {
out.push(("shadow_color".to_owned(), Value::from(shadow as i32)));
}
for (key, flag) in [
("bold", style.bold),
("italic", style.italic),
@@ -594,10 +578,6 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
let mut event = item.clone();
event.insert("action".into(), "show_item".into());
out.push(("hover_event".to_owned(), Value::Object(event)));
} else if let Some(Value::Object(entity)) = style.hover_entity.as_deref() {
let mut event = entity.clone();
event.insert("action".into(), "show_entity".into());
out.push(("hover_event".to_owned(), Value::Object(event)));
}
if let Some(insertion) = &style.insertion {
out.push(("insertion".to_owned(), insertion.clone().into()));
@@ -608,35 +588,6 @@ fn style_json(style: &Style) -> Vec<(String, Value)> {
out
}
/// `Style.applyLegacyFormat` for the code after a `§`, `§r` going back to
/// `reset` (`StringDecomposer.iterateFormatted`); an unknown code changes nothing.
pub fn legacy_format(style: &Style, code: char, reset: &Style) -> Style {
let code = code.to_ascii_lowercase();
if let Some(c) = COLORS.iter().find(|c| c.0 == code) {
// A colour clears the decorations.
return Style {
color: Some(c.2),
bold: Some(false),
italic: Some(false),
underlined: Some(false),
strikethrough: Some(false),
obfuscated: Some(false),
..style.clone()
};
}
let mut s = style.clone();
match code {
'k' => s.obfuscated = Some(true),
'l' => s.bold = Some(true),
'm' => s.strikethrough = Some(true),
'n' => s.underlined = Some(true),
'o' => s.italic = Some(true),
'r' => s = reset.clone(),
_ => {}
}
s
}
/// TranslatableContents.decomposeTemplate: `%s` takes the next argument,
/// `%n$s` a numbered one and `%%` is a percent sign. Malformed templates are
/// shown verbatim.
@@ -60,19 +60,6 @@ pub fn edit_shortcut(
})
}
/// Windows reports AltGr as Ctrl plus Alt: the system presses a left Control
/// in front of the right Alt.
pub const ALTGR_IS_CTRL_ALT: bool = cfg!(windows);
/// Whether a key's text reaches the screen (`KeyboardHandler.textInput`, then
/// `charTyped` per code point). The edit modifier's shortcuts type nothing,
/// but `textInput` takes no modifiers: with AltGr held (Ctrl plus Alt where
/// `altgr_is_ctrl_alt`) the layout's third-level characters are text, as `/`
/// on ABNT2, `@`, `{` and `[` on German or the Polish letters.
pub fn types_text(edit_modifier: bool, alt: bool, altgr_is_ctrl_alt: bool) -> bool {
!edit_modifier || (altgr_is_ctrl_alt && alt)
}
/// `StringUtil.isAllowedChatCharacter`.
pub fn is_allowed_chat_character(c: char) -> bool {
c != '§' && c >= ' ' && c != '\u{7f}'
@@ -316,22 +303,6 @@ pub fn append_limited(value: &mut String, text: &str, max_chars: usize) -> bool
mod tests {
use super::*;
#[test]
fn altgr_types_text_where_it_is_ctrl_alt() {
// Plain keys and Shift type.
assert!(types_text(false, false, true));
assert!(types_text(false, false, false));
// Ctrl (Cmd) shortcuts do not.
assert!(!types_text(true, false, true));
assert!(!types_text(true, false, false));
// AltGr on Windows is Ctrl+Alt: ABNT2 `/`, German `@` type.
assert!(types_text(true, true, true));
// Where AltGr is its own modifier, Ctrl+Alt is a shortcut.
assert!(!types_text(true, true, false));
// Alt alone (macOS Option, Linux AltGr) types.
assert!(types_text(false, true, false));
}
#[test]
fn shortcuts_need_the_edit_modifier_alone() {
let c = Some('c');
-45
View File
@@ -2,9 +2,6 @@
//! Item-use and sneak multipliers come from the player's current state; this
//! module does not implement sprint eligibility, poses or the input lifecycle.
use std::collections::HashSet;
use winit::keyboard::{KeyCode, ModifiersState};
fn length(v: [f32; 2]) -> f32 {
f64::from(v[0] * v[0] + v[1] * v[1]).sqrt() as f32
}
@@ -68,45 +65,3 @@ fn square_movement(v: [f32; 2]) -> [f32; 2] {
},
)
}
/// `InputQuirks.isQuitShortcutDown`: checks whether the platform's window-closing
/// keyboard shortcut is held.
/// - On macOS: Command (`super_key()`) + `Q`.
/// - On Windows / Linux / other: Alt (`alt_key()`) + `F4`.
pub fn is_quit_shortcut_down(modifiers: ModifiersState, keys: &HashSet<KeyCode>) -> bool {
if cfg!(target_os = "macos") {
modifiers.super_key() && keys.contains(&KeyCode::KeyQ)
} else {
modifiers.alt_key() && keys.contains(&KeyCode::F4)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn quit_shortcut_follows_platform_modifiers_and_keys() {
let mut keys = HashSet::new();
let alt = ModifiersState::ALT;
let super_key = ModifiersState::SUPER;
assert!(!is_quit_shortcut_down(ModifiersState::empty(), &keys));
keys.insert(KeyCode::F4);
if cfg!(target_os = "macos") {
assert!(!is_quit_shortcut_down(alt, &keys));
keys.remove(&KeyCode::F4);
keys.insert(KeyCode::KeyQ);
assert!(is_quit_shortcut_down(super_key, &keys));
assert!(!is_quit_shortcut_down(alt, &keys));
} else {
assert!(is_quit_shortcut_down(alt, &keys));
assert!(!is_quit_shortcut_down(super_key, &keys));
keys.remove(&KeyCode::F4);
keys.insert(KeyCode::KeyQ);
assert!(!is_quit_shortcut_down(alt, &keys));
assert!(!is_quit_shortcut_down(super_key, &keys));
}
}
}
@@ -13,12 +13,6 @@ pub enum Button {
}
pub trait InteractionWorld {
/// Minecraft.pick before handleKeybinds: the tick's `hitResult`, which
/// every click of the tick reads, even after one of them changed the
/// block it names (a creative break, then a use that replaces it).
fn pick_hit_result(&mut self);
/// The tick's clicks are done: later picks follow the crosshair again.
fn release_hit_result(&mut self);
fn using_item(&self) -> bool;
fn release_using(&mut self);
fn start_attack(&mut self) -> bool;
@@ -54,7 +48,6 @@ impl InteractionInput {
pub fn tick(&mut self, world: &mut impl InteractionWorld, attack_down: bool, use_down: bool) {
let [attack, use_item, pick] = std::mem::take(&mut self.clicks);
world.pick_hit_result();
let mut instant = false;
if world.using_item() {
if !use_down {
@@ -77,7 +70,6 @@ impl InteractionInput {
world.start_use();
}
world.continue_attack(!instant && attack_down);
world.release_hit_result();
}
}
@@ -94,8 +86,6 @@ mod tests {
events: Vec<&'static str>,
}
impl InteractionWorld for World {
fn pick_hit_result(&mut self) {}
fn release_hit_result(&mut self) {}
fn using_item(&self) -> bool {
self.using
}
@@ -193,67 +183,4 @@ mod tests {
input.tick(&mut world, false, false);
assert_eq!(world.events, ["release", "continue"]);
}
/// A floating block in front of the crosshair, nothing behind it, and a
/// block item in the hand of a creative player.
#[derive(Default)]
struct Column {
block: bool,
hit: Option<Option<()>>,
placed: bool,
}
impl Column {
/// Minecraft.hitResult: the tick's pick, or a fresh one outside it.
fn target(&self) -> Option<()> {
self.hit.unwrap_or(self.block.then_some(()))
}
}
impl InteractionWorld for Column {
fn pick_hit_result(&mut self) {
self.hit = Some(self.target());
}
fn release_hit_result(&mut self) {
self.hit = None;
}
fn using_item(&self) -> bool {
false
}
fn release_using(&mut self) {}
fn start_attack(&mut self) -> bool {
// MultiPlayerGameMode.startDestroyBlock in creative: the
// predicted break leaves air.
if self.target().is_some() {
self.block = false;
}
!self.block
}
fn start_use(&mut self) {
// BlockItem.place: the clicked block, now air, can be replaced.
if self.target().is_some() && !self.block {
self.block = true;
self.placed = true;
}
}
fn pick(&mut self) {}
fn use_delay(&self) -> u32 {
0
}
fn continue_attack(&mut self, _: bool) {}
}
#[test]
fn attack_and_use_in_one_tick_share_the_hit_result() {
// #3006: both buttons at once replace the block the crosshair is on.
let mut input = InteractionInput::default();
let mut world = Column {
block: true,
..Default::default()
};
input.press(Button::Attack);
input.press(Button::Use);
input.tick(&mut world, false, false);
assert!(world.placed, "the use acts on the block the attack broke");
assert!(world.block);
assert!(world.hit.is_none(), "the next pick follows the crosshair");
}
}
+13 -68
View File
@@ -284,26 +284,6 @@ pub fn mouse_button(name: &str) -> Option<MouseButton> {
}
pub use horizon_client_core::key_display::display_name;
/// A key event: what the layout writes on its key, without modifiers, names
/// that key from now on (`key_display::learn_layout`), so an AZERTY player's
/// Q key shows A.
pub fn learn_layout(event: &winit::event::KeyEvent) {
use winit::keyboard::{Key, PhysicalKey};
use winit::platform::modifier_supplement::KeyEventExtModifierSupplement;
let PhysicalKey::Code(code) = event.physical_key else {
return;
};
let Some(name) = key_name(code) else {
return;
};
let learn = horizon_client_core::key_display::learn_layout;
match event.key_without_modifiers() {
Key::Character(text) => learn(name, &text),
Key::Dead(Some(c)) => learn(name, c.encode_utf8(&mut [0; 4])),
_ => {}
}
}
/// Current bindings by mapping name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyBinds {
@@ -320,8 +300,9 @@ impl Default for KeyBinds {
}
}
/// Each default key once, in order: two mappings that share a default key
/// (Pick Block and the spectator hotbar both on the middle button) are one
/// press of it, not two.
/// (Advancements and the debug profiler both on L) are one press of it, not
/// two (the second would close the screen the first opened). Vanilla clicks
/// both mappings, but the profiler one only acts with F3 held.
fn distinct<T: PartialEq>(keys: Vec<T>) -> Vec<T> {
let mut out = Vec::with_capacity(keys.len());
for k in keys {
@@ -387,25 +368,6 @@ impl KeyBinds {
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
}
/// The mappings bound to `key` that [`KeyBinds::translate_all`] follows:
/// all but the debug keys. Those act only with F3 held
/// (`KeyboardHandler.handleDebugKeys`, `debug_keys.rs` reads the physical
/// key and the binding itself); their defaults (A, S, D, T, L, 1 to 4...)
/// would otherwise turn the key back into its old gameplay meaning.
fn translated_mappings<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'static str> + 'a {
MAPPINGS
.iter()
.filter(|m| m.2 != "debug")
.map(|m| m.0)
.filter(move |n| self.get(n) == key)
}
/// Whether a mapping (other than a debug key) whose default is `key` was
/// bound elsewhere.
fn default_moved(&self, key: &str) -> bool {
MAPPINGS
.iter()
.any(|(n, d, c)| *d == key && *c != "debug" && !self.is_default(n))
}
/// Translate a physical key into the default key of the mapping it is
/// bound to, so game code written against vanilla defaults follows the
/// player's bindings. `None` means the key now does nothing; mouse
@@ -422,7 +384,7 @@ impl KeyBinds {
return vec![Ok(key)];
};
let bound: Vec<_> = self
.translated_mappings(name)
.mappings_for(name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match key_code(default) {
@@ -435,7 +397,10 @@ impl KeyBinds {
return distinct(bound);
}
// An unbound key whose default meaning was moved elsewhere is inert.
if self.default_moved(name) {
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return Vec::new();
}
vec![Ok(key)]
@@ -448,7 +413,7 @@ impl KeyBinds {
pub fn translate_mouse_all(&self, button: MouseButton) -> Vec<Result<KeyCode, MouseButton>> {
let name = mouse_name(button);
let bound: Vec<_> = self
.translated_mappings(&name)
.mappings_for(&name)
.filter_map(|mapping| {
let default = Self::default_of(mapping);
match mouse_button(default) {
@@ -460,7 +425,10 @@ impl KeyBinds {
if !bound.is_empty() {
return distinct(bound);
}
if self.default_moved(&name) {
if MAPPINGS
.iter()
.any(|(n, d, _)| *d == name && !self.is_default(n))
{
return Vec::new();
}
vec![Err(button)]
@@ -540,29 +508,6 @@ mod tests {
assert_eq!(k.conflicts("key.forward"), ["key.jump"]);
}
#[test]
fn a_moved_key_keeps_no_default_action() {
// #3158: the debug keys (F3+A, F3+1...) share these keys' defaults,
// and must not hand them back their gameplay meaning.
let mut k = KeyBinds::default();
k.set("key.hotbar.1", "key.keyboard.q");
assert_eq!(k.translate_all(KeyCode::Digit1), []);
assert_eq!(
k.translate_all(KeyCode::KeyQ),
[Ok(KeyCode::KeyQ), Ok(KeyCode::Digit1)]
);
k.set("key.inventory", "key.keyboard.a");
k.set("key.left", "key.keyboard.e");
assert_eq!(k.translate_all(KeyCode::KeyA), [Ok(KeyCode::KeyE)]);
assert_eq!(k.translate_all(KeyCode::KeyE), [Ok(KeyCode::KeyA)]);
k.set("key.back", "key.keyboard.down");
assert_eq!(k.translate_all(KeyCode::KeyS), []);
// Keys left alone still act, and a moved debug key changes nothing.
k.set("key.debug.fpsCharts", "key.keyboard.9");
assert_eq!(k.translate_all(KeyCode::Digit2), [Ok(KeyCode::Digit2)]);
assert_eq!(k.translate_all(KeyCode::Digit9), [Ok(KeyCode::Digit9)]);
assert_eq!(k.translate_all(KeyCode::F3), [Ok(KeyCode::F3)]);
}
#[test]
fn display_names() {
assert_eq!(display_name("key.keyboard.w").plain(), "W");
assert_eq!(display_name("key.keyboard.slash").plain(), "/");
-39
View File
@@ -342,28 +342,6 @@ pub fn mouse_position_after_grab_change(
}
}
/// `MacosUtil.setCtrlClickEmulatesRightClick`: with the option on (and only on
/// macOS), a left click made with Control held is a right click, and so is
/// its release, whatever Control does in between.
#[derive(Clone, Copy, Debug, Default)]
pub struct RightClickEmulation {
emulating: bool,
}
impl RightClickEmulation {
/// Whether the left button's `pressed` or released event is a right click.
/// `enabled` is the option on macOS.
pub fn is_right_click(&mut self, pressed: bool, control: bool, enabled: bool) -> bool {
if pressed {
self.emulating = enabled && control;
}
let right = self.emulating;
if !pressed {
self.emulating = false;
}
right
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -548,21 +526,4 @@ mod tests {
None
);
}
#[test]
fn control_click_is_a_right_click_until_released() {
let mut e = RightClickEmulation::default();
// The option off, or no Control: a left click stays one.
assert!(!e.is_right_click(true, true, false));
assert!(!e.is_right_click(false, true, false));
assert!(!e.is_right_click(true, false, true));
assert!(!e.is_right_click(false, true, true));
// Control held at the press: the press and the release are right clicks,
// even when Control was let go before the release.
assert!(e.is_right_click(true, true, true));
assert!(e.is_right_click(false, false, true));
// The next left click is its own.
assert!(!e.is_right_click(true, false, true));
assert!(!e.is_right_click(false, false, true));
}
}
+1 -246
View File
@@ -284,18 +284,12 @@ impl FramerateLimiter {
/// (`Window.updateFullscreenState` -> `Minecraft.fullscreenStateChanged`), and
/// the window is only asked to change when the option itself changes
/// (`Window.updateFullscreenIfChanged`), never re-forced to the option.
#[derive(Clone, Copy, Debug, PartialEq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FullscreenState {
/// The state the window system last reported (`Window.fullscreen`).
actual: bool,
/// The state last asked of the window system, or adopted from it.
requested: bool,
/// `Window.exclusiveFullscreen`.
exclusive: bool,
/// `Window.preferredFullscreenVideoMode`.
mode: Option<VideoMode>,
/// `Window.dirty`: the preferred mode changed and the screen has not been left yet.
mode_dirty: bool,
}
impl FullscreenState {
@@ -304,70 +298,9 @@ impl FullscreenState {
Self {
actual: false,
requested,
exclusive: false,
mode: None,
mode_dirty: false,
}
}
/// `Window.updateFullscreenIfChanged` with the exclusive option and preferred mode: asks the
/// window to enter, leave or change its fullscreen only when one of them changed.
/// `in_video_screen` holds a changed mode back until the Video Settings screen closes
/// (`changeFullscreenVideoMode`).
pub fn apply(
&mut self,
window: &winit::window::Window,
wanted: bool,
exclusive: bool,
preferred: Option<VideoMode>,
in_video_screen: bool,
) {
let request = self.request(wanted);
let reapply = self.set_exclusive(exclusive);
self.set_preferred_mode(preferred);
let mode_change = !in_video_screen && self.take_mode_change();
match request {
Some(false) => window.set_fullscreen(None),
Some(true) => window.set_fullscreen(Some(fullscreen_request(
window,
exclusive,
preferred.as_ref(),
))),
None if reapply || mode_change => window.set_fullscreen(Some(fullscreen_request(
window,
exclusive,
preferred.as_ref(),
))),
None => {}
}
}
/// `Window.setExclusiveFullscreen`: true when the option changed while fullscreen is
/// requested, so the window has to enter the other kind of fullscreen at once.
pub fn set_exclusive(&mut self, exclusive: bool) -> bool {
let changed = self.exclusive != exclusive;
self.exclusive = exclusive;
changed && self.requested
}
/// `Window.setPreferredFullscreenVideoMode`: a changed mode waits for `take_mode_change`.
pub fn set_preferred_mode(&mut self, mode: Option<VideoMode>) {
if self.mode != mode {
self.mode = mode;
self.mode_dirty = true;
}
}
/// `Window.changeFullscreenVideoMode` (the Video Settings screen closing): true once when
/// a changed mode has to be applied to a fullscreen window.
pub fn take_mode_change(&mut self) -> bool {
let apply = self.requested && self.mode_dirty;
if apply {
self.mode_dirty = false;
}
apply
}
/// `Window.updateFullscreenIfChanged`: the state to ask of the window
/// when the option `wanted` differs from what was last asked or adopted.
pub fn request(&mut self, wanted: bool) -> Option<bool> {
@@ -388,132 +321,6 @@ impl FullscreenState {
}
}
/// `VideoMode`: one display mode of a monitor, as `fullscreenResolution` in options.txt keeps it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VideoMode {
pub width: i32,
pub height: i32,
pub red_bits: i32,
pub green_bits: i32,
pub blue_bits: i32,
pub refresh_rate: f32,
}
impl VideoMode {
/// `VideoMode.read`: the JSON object `write` makes; any other string is None.
pub fn read(text: &str) -> Option<Self> {
let number = |key: &str| -> Option<f64> {
let at = text.find(&format!("\"{key}\""))? + key.len() + 2;
let rest = text[at..].trim_start().strip_prefix(':')?.trim_start();
let end = rest
.find(|c: char| !(c.is_ascii_digit() || matches!(c, '-' | '+' | '.' | 'e' | 'E')))
.unwrap_or(rest.len());
rest[..end].parse().ok()
};
if !text.trim_start().starts_with('{') {
return None;
}
Some(Self {
width: number("width")? as i32,
height: number("height")? as i32,
red_bits: number("red_bits")? as i32,
green_bits: number("green_bits")? as i32,
blue_bits: number("blue_bits")? as i32,
refresh_rate: number("refresh_rate")? as f32,
})
}
/// `VideoMode.write`: the Codec's JSON through Gson (a float prints as `60.0`).
pub fn write(&self) -> String {
let rate = if self.refresh_rate == self.refresh_rate.trunc() {
format!("{:.1}", self.refresh_rate)
} else {
self.refresh_rate.to_string()
};
format!(
"{{\"width\":{},\"height\":{},\"red_bits\":{},\"green_bits\":{},\"blue_bits\":{},\"refresh_rate\":{rate}}}",
self.width, self.height, self.red_bits, self.green_bits, self.blue_bits
)
}
/// `VideoMode.refreshRateLabel`: a whole rate without decimals, any other with two.
pub fn refresh_rate_label(&self) -> String {
if self.refresh_rate == self.refresh_rate.round_ties_even() {
(self.refresh_rate as i32).to_string()
} else {
format!("{:.2}", self.refresh_rate)
}
}
/// The colour depth `options.fullscreen.entry` shows.
pub fn bits(&self) -> i32 {
self.red_bits + self.green_bits + self.blue_bits
}
/// A winit mode: its depth is the total, split evenly over the channels.
pub fn from_winit(mode: &winit::monitor::VideoModeHandle) -> Self {
let depth = i32::from(mode.bit_depth());
let size = mode.size();
Self {
width: size.width as i32,
height: size.height as i32,
red_bits: depth / 3,
green_bits: depth / 3,
blue_bits: depth - 2 * (depth / 3),
refresh_rate: mode.refresh_rate_millihertz() as f32 / 1000.0,
}
}
}
/// `Monitor.videoModes`: the modes a monitor offers.
pub fn monitor_video_modes(monitor: &winit::monitor::MonitorHandle) -> Vec<VideoMode> {
monitor
.video_modes()
.map(|m| VideoMode::from_winit(&m))
.collect()
}
/// `Monitor.currentMode`: the monitor's desktop mode; winit has no such query, so the mode of
/// the monitor's own size with the highest refresh rate and depth.
fn monitor_current_mode(
monitor: &winit::monitor::MonitorHandle,
) -> Option<winit::monitor::VideoModeHandle> {
let size = monitor.size();
monitor
.video_modes()
.filter(|m| m.size() == size)
.max_by_key(|m| (m.refresh_rate_millihertz(), m.bit_depth()))
}
/// `Window.applyFullscreen`: the fullscreen the window asks for. Exclusive fullscreen takes
/// `Monitor.getPreferredVideoMode` (the preferred mode if the monitor has it, else the desktop
/// mode); a monitor with no usable mode falls back to borderless, as vanilla does.
pub fn fullscreen_request(
window: &winit::window::Window,
exclusive: bool,
preferred: Option<&VideoMode>,
) -> winit::window::Fullscreen {
use winit::window::Fullscreen;
if !exclusive {
return Fullscreen::Borderless(None);
}
let Some(monitor) = window
.current_monitor()
.or_else(|| window.primary_monitor())
else {
return Fullscreen::Borderless(None);
};
let wanted = preferred.and_then(|p| {
monitor
.video_modes()
.find(|m| VideoMode::from_winit(m) == *p)
});
match wanted.or_else(|| monitor_current_mode(&monitor)) {
Some(mode) => Fullscreen::Exclusive(mode),
None => Fullscreen::Borderless(None),
}
}
/// Horizon's icon for the window's title bar and the task bar (X11 and Windows; Wayland takes
/// it from the `horizon.desktop` entry, macOS from the app bundle). `None` if it can't be read.
pub fn icon() -> Option<winit::window::Icon> {
@@ -533,63 +340,11 @@ pub fn icon() -> Option<winit::window::Icon> {
mod tests {
use super::*;
#[test]
fn video_mode_round_trips_the_options_json() {
let mode = VideoMode {
width: 1920,
height: 1080,
red_bits: 8,
green_bits: 8,
blue_bits: 8,
refresh_rate: 60.0,
};
let text = mode.write();
assert_eq!(
text,
r#"{"width":1920,"height":1080,"red_bits":8,"green_bits":8,"blue_bits":8,"refresh_rate":60.0}"#
);
assert_eq!(VideoMode::read(&text), Some(mode));
assert_eq!(VideoMode::read("1920x1080"), None);
assert_eq!(VideoMode::read(r#"{"width":1}"#), None);
}
#[test]
fn refresh_rate_label_is_whole_or_two_decimals() {
let mut mode = VideoMode::read(
r#"{"width":1,"height":1,"red_bits":8,"green_bits":8,"blue_bits":8,"refresh_rate":144.0}"#,
)
.unwrap();
assert_eq!(mode.refresh_rate_label(), "144");
mode.refresh_rate = 59.94;
assert_eq!(mode.refresh_rate_label(), "59.94");
assert_eq!(mode.bits(), 24);
}
#[test]
fn the_window_icon_decodes() {
assert!(icon().is_some());
}
#[test]
fn exclusive_fullscreen_reapplies_only_while_fullscreen_is_requested() {
let mut f = FullscreenState::new(false);
assert!(!f.set_exclusive(true));
assert!(!f.set_exclusive(true));
assert_eq!(f.request(true), Some(true));
assert!(f.set_exclusive(false));
assert!(!f.set_exclusive(false));
}
#[test]
fn a_changed_video_mode_applies_once_when_fullscreen() {
let mode = VideoMode::read(
r#"{"width":1,"height":1,"red_bits":8,"green_bits":8,"blue_bits":8,"refresh_rate":60.0}"#,
);
let mut f = FullscreenState::new(false);
f.set_preferred_mode(mode);
assert!(!f.take_mode_change());
f.request(true);
f.set_preferred_mode(mode);
assert!(f.take_mode_change());
assert!(!f.take_mode_change());
}
#[test]
fn fullscreen_follows_the_option_only_when_it_changes() {
let mut f = FullscreenState::new(false);
-69
View File
@@ -1,69 +0,0 @@
[package]
name = "horizon-client-render"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.90"
description = "The client's world data, rendering and screens: chunks, meshing, light, streaming, the renderer, the HUD, menus and settings; no gameplay"
[dependencies]
horizon-assets = { path = "../horizon-assets" }
horizon-bench = { path = "../horizon-bench" }
horizon-client-core = { path = "../horizon-client-core" }
horizon-client-input = { path = "../horizon-client-input" }
horizon-command = { path = "../horizon-command" }
horizon-core = { path = "../horizon-core" }
horizon-hdr = { path = "../horizon-hdr" }
horizon-items = { path = "../horizon-items" }
horizon-protocol = { path = "../horizon-protocol" }
horizon-shader-api = { path = "../horizon-shader-api" }
horizon-shaders = { path = "../horizon-shaders" }
horizon-telemetry = { path = "../horizon-telemetry", default-features = false, features = ["live"] }
horizon-theme = { path = "../horizon-theme" }
horizon-threads = { path = "../horizon-threads" }
horizon-world = { path = "../horizon-world" }
ab_glyph = "0.2.32"
base64 = "0.22"
bytemuck = { version = "1.24", features = ["derive"] }
# Sound (ALSA on Linux); the `audio` feature.
cpal = { version = "0.16", optional = true }
chrono = { version = "0.4.42", default-features = false, features = ["clock", "std"] }
flate2 = { version = "1.1.10", default-features = false, features = ["zlib-rs", "runtime_detection"] }
glam = "0.30"
log = "0.4"
miniz_oxide = "0.8"
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
png = "0.18"
pollster = "0.4"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1.0.151", features = ["raw_value"] }
sha1 = "0.10"
sha2 = "0.10.9"
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
unicode-bidi = "0.3.18"
ureq = { version = "2", default-features = false, features = ["tls"] }
wgpu = { version = "30.0.1", default-features = false, features = ["std", "parking_lot", "vulkan", "metal", "wgsl", "naga-ir"] }
winit = "0.30.13"
zip = { version = "2", default-features = false, features = ["deflate"] }
[target.'cfg(unix)'.dependencies]
rustix = { version = "1", default-features = false, features = ["std", "time"] }
[target.'cfg(windows)'.dependencies]
wgpu = { version = "30.0.1", default-features = false, features = ["dx12"] }
[target.'cfg(not(target_os = "macos"))'.dependencies]
wgpu = { version = "30.0.1", default-features = false, features = ["gles"] }
[features]
# Sound output: horizon-client's `audio` feature.
audio = ["dep:cpal"]
# Helpers horizon-client's tests build their fixtures with.
test-support = []
[lints]
workspace = true
[dev-dependencies]
horizon-items = { path = "../horizon-items", features = ["test-support"] }
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] }
@@ -1,151 +0,0 @@
//! Two offscreen frames presented in one window, without game resources or player data.
//! `cargo run --profile fast -p horizon-client-render --example compositor -- --smoke`
use horizon_client_render::gfx::compositor::Compositor;
use std::sync::Arc;
use winit::{
application::ApplicationHandler,
event::WindowEvent,
event_loop::{ActiveEventLoop, EventLoop},
window::{Window, WindowId},
};
struct Frames {
window: Arc<Window>,
compositor: Compositor,
textures: [wgpu::Texture; 2],
}
impl Frames {
fn new(event_loop: &ActiveEventLoop) -> horizon_client_render::Result<Self> {
let window = Arc::new(
event_loop.create_window(
Window::default_attributes()
.with_title("Compositor: red and blue views")
.with_inner_size(winit::dpi::PhysicalSize::new(640, 360)),
)?,
);
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_with_display_handle(
Box::new(window.clone()),
));
let surface = instance.create_surface(window.clone())?;
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
compatible_surface: Some(&surface),
..Default::default()
}))?;
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default()))?;
let textures = [[0, 0, 255, 255], [255, 0, 0, 255]].map(|pixel| {
let size = wgpu::Extent3d {
width: 320,
height: 360,
depth_or_array_layers: 1,
};
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Offscreen view"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage: wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
texture.as_image_copy(),
&pixel.repeat(320 * 360),
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(320 * 4),
rows_per_image: Some(360),
},
size,
);
texture
});
let compositor = Compositor::new(
surface,
&adapter,
&device,
&queue,
window.inner_size().into(),
)?;
Ok(Self {
window,
compositor,
textures,
})
}
}
#[derive(Default)]
struct Demo {
frames: Option<Frames>,
error: Option<String>,
presented: usize,
smoke: bool,
}
impl ApplicationHandler for Demo {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.frames.is_none() {
match Frames::new(event_loop) {
Ok(frames) => self.frames = Some(frames),
Err(error) => {
self.error = Some(error.to_string());
event_loop.exit();
}
}
}
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
let Some(f) = &mut self.frames else { return };
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => f.compositor.resize(size.width, size.height),
// Uncovered pixels are black; resize smaller to exercise clipping.
WindowEvent::RedrawRequested
if f.compositor
.present(&[(&f.textures[0], [0, 0]), (&f.textures[1], [320, 0])]) =>
{
self.presented += 1;
if self.smoke && self.presented == 10 {
f.compositor.set_vsync(false);
f.compositor.resize(0, 0);
assert!(!f.compositor.present(&[]));
f.compositor.resize(u32::MAX, u32::MAX);
assert!(!f.compositor.present(&[]));
f.compositor.resize(400, 240);
let _ = f
.window
.request_inner_size(winit::dpi::PhysicalSize::new(400, 240));
}
if self.smoke && self.presented == 20 {
println!("compositor: 20 frames, resize, suspension and clipping passed");
event_loop.exit();
}
}
_ => {}
}
}
fn about_to_wait(&mut self, _: &ActiveEventLoop) {
if let Some(f) = &self.frames {
f.window.request_redraw();
}
}
}
fn main() -> horizon_client_render::Result<()> {
let mut demo = Demo {
smoke: std::env::args().any(|a| a == "--smoke"),
..Default::default()
};
EventLoop::new()?.run_app(&mut demo)?;
if let Some(error) = demo.error {
return Err(error.into());
}
if demo.smoke && demo.presented < 20 {
return Err("smoke test closed early".into());
}
Ok(())
}
@@ -1,214 +0,0 @@
//! Splitscreen: several players' renderers draw offscreen on one device, and the
//! compositor copies each frame into its place on a window's surface. A window holds views but
//! never owns them, so a view can later move to another window (another monitor, detached).
use super::Renderer;
use crate::Result;
use std::sync::Arc;
use winit::window::Window;
pub struct Compositor {
surface: wgpu::Surface<'static>,
device: wgpu::Device,
queue: wgpu::Queue,
config: wgpu::SurfaceConfiguration,
present_modes: Vec<wgpu::PresentMode>,
suspended: bool,
}
impl Renderer {
/// A compositor for `window` on this renderer's device, presenting on the surface it gave up.
pub fn compositor(&self, window: Arc<Window>) -> Result<Compositor> {
// The surface this renderer set aside for its successor (`release_surface`), else a new
// one: a window can't keep two.
let spare = self
.spare_surface
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.take();
let surface = match spare {
Some(surface) => surface,
None => self.instance.create_surface(window.clone())?,
};
Compositor::new(
surface,
&self.adapter,
&self.device,
&self.queue,
window.inner_size().into(),
)
}
/// The last offscreen frame (`--offscreen`), for the compositor.
pub fn offscreen_frame(&self) -> Option<&wgpu::Texture> {
self.offscreen.as_ref()
}
/// Splitscreen turned off: a compositor's surface, set aside for the renderer that draws on
/// the window again (it takes it, as after `release_surface`).
pub fn take_back(&self, compositor: Compositor) {
*self
.spare_surface
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(compositor.surface);
}
}
impl Compositor {
/// Present offscreen BGRA frames on a compatible surface using their existing device.
/// The surface must support COPY_DST and Bgra8Unorm; unsupported surfaces return an error.
pub fn new(
surface: wgpu::Surface<'static>,
adapter: &wgpu::Adapter,
device: &wgpu::Device,
queue: &wgpu::Queue,
size: [u32; 2],
) -> Result<Self> {
let caps = surface.get_capabilities(adapter);
// ponytail: a plain texture copy needs the offscreen frames' format; a blit pass would
// take any surface format (Rgba8Unorm on some Linux drivers).
if !caps.usages.contains(wgpu::TextureUsages::COPY_DST) {
return Err("surface does not support copying offscreen frames".into());
}
let format = wgpu::TextureFormat::Bgra8Unorm;
if !caps.formats.contains(&format) {
return Err(format!(
"splitscreen needs a {format:?} surface; this one offers {:?}",
caps.formats
)
.into());
}
let max = device.limits().max_texture_dimension_2d;
let config = wgpu::SurfaceConfiguration {
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
format,
width: size[0].clamp(1, max),
height: size[1].clamp(1, max),
present_mode: wgpu::PresentMode::Fifo,
desired_maximum_frame_latency: 2,
alpha_mode: wgpu::CompositeAlphaMode::Opaque,
view_formats: vec![],
color_space: wgpu::SurfaceColorSpace::default(),
};
surface.configure(device, &config);
Ok(Compositor {
surface,
device: device.clone(),
queue: queue.clone(),
config,
present_modes: caps.present_modes,
suspended: !super::drawable_size(size[0], size[1], max),
})
}
/// Vsync on: presents wait for the display. Off: they don't (Mailbox, else Immediate).
pub fn set_vsync(&mut self, vsync: bool) {
let mode = [wgpu::PresentMode::Mailbox, wgpu::PresentMode::Immediate]
.into_iter()
.find(|m| !vsync && self.present_modes.contains(m))
.unwrap_or(wgpu::PresentMode::Fifo);
if mode != self.config.present_mode {
self.config.present_mode = mode;
self.surface.configure(&self.device, &self.config);
}
}
pub fn resize(&mut self, width: u32, height: u32) {
self.suspended =
!super::drawable_size(width, height, self.device.limits().max_texture_dimension_2d);
if !self.suspended {
self.config.width = width;
self.config.height = height;
self.surface.configure(&self.device, &self.config);
}
}
/// Copy each view's frame to its top-left corner on the window and present. Frames that
/// don't fit are clipped; parts of the window no view covers (a view before its first frame,
/// one still at its old size after a resize) are black. Nothing when the window has no frame
/// to give (occluded, resized, timed out). Returns true when a frame was submitted.
pub fn present(&mut self, views: &[(&wgpu::Texture, [u32; 2])]) -> bool {
if self.suspended {
return false;
}
let frame = match self.surface.get_current_texture() {
wgpu::CurrentSurfaceTexture::Success(f)
| wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost => {
self.surface.configure(&self.device, &self.config);
return false;
}
_ => return false,
};
let mut encoder = self
.device
.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("Splitscreen compositor"),
});
let target = frame.texture.create_view(&Default::default());
drop(encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Splitscreen compositor clear"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
}));
for &(texture, [x, y]) in views {
let [width, height] = clipped_size(
[texture.width(), texture.height()],
[x, y],
[self.config.width, self.config.height],
);
if width == 0 || height == 0 {
continue;
}
encoder.copy_texture_to_texture(
texture.as_image_copy(),
wgpu::TexelCopyTextureInfo {
origin: wgpu::Origin3d { x, y, z: 0 },
..frame.texture.as_image_copy()
},
wgpu::Extent3d {
width,
height,
depth_or_array_layers: 1,
},
);
}
self.queue.submit([encoder.finish()]);
self.queue.present(frame);
true
}
}
/// Copies never reach past the surface, including while a resized view still has its old frame.
fn clipped_size(view: [u32; 2], at: [u32; 2], surface: [u32; 2]) -> [u32; 2] {
[
view[0].min(surface[0].saturating_sub(at[0])),
view[1].min(surface[1].saturating_sub(at[1])),
]
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn frames_are_clipped_to_the_window_during_resize() {
assert_eq!(clipped_size([640, 480], [0, 0], [1280, 720]), [640, 480]);
assert_eq!(
clipped_size([640, 480], [1000, 600], [1280, 720]),
[280, 120]
);
assert_eq!(clipped_size([640, 480], [1280, 720], [1280, 720]), [0, 0]);
assert_eq!(
clipped_size([640, 480], [u32::MAX, 0], [1280, 720]),
[0, 480]
);
}
}
@@ -1,7 +0,0 @@
//! Frame generation: FSR 3.1's frame interpolation will show a frame halfway between each
//! two real ones. So far this holds its optical flow; the interpolation and the setting
//! that runs them come next.
// Unused until the interpolation and the renderer use it.
#[allow(dead_code)]
mod optical_flow;
@@ -1,653 +0,0 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 Advanced Micro Devices, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//! FSR 3.1's optical flow (AMD FidelityFX SDK 1.1.4, `ffx_opticalflow*`, MIT), ported to
//! WGSL (`optical_flow.wgsl`): block motion between the previous frame's colour and this
//! one's, and scene change detection, for frame interpolation (`interpolation.rs`).
//!
//! As in `ffx_opticalflow.cpp`: luma at the display size and 6 halvings, ping-ponged
//! between frames; a histogram of the luma for scene change detection; then from the
//! coarsest of 7 levels down, a block search seeded by the level above, a 3x3 filter and
//! a scale to the next level. The ported passes differ only where WGSL needs it: the luma
//! levels are `R32Float` holding AMD's 8-bit integers, wave operations are workgroup
//! atomics, and the luma pyramid is one dispatch per level instead of one for all (SPD).
//! The luma textures aren't cleared on a reset (AMD's are): its first 6 frames report a
//! scene change and no motion, and rewrite them.
//!
//! The vectors point from a block of this frame to where it was in the previous one, in
//! display pixels: content moving right by 4 pixels gives (-4, 0).
/// The size in pixels of the square blocks the flow has one vector for.
pub const BLOCK_SIZE: u32 = 8;
/// `OpticalFlowMaxPyramidLevels`: the search's levels.
const LEVELS: usize = 7;
/// `HistogramBins * HistogramsPerDim²`: the scene change histograms.
const HISTOGRAM_WIDTH: u64 = 256 * 9;
/// `optical_flow.wgsl`'s `Params`.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct Params {
display: [i32; 2],
level: u32,
level_count: u32,
frame_index: u32,
transfer_function: u32,
min_max_luminance: [f32; 2],
}
struct Pipelines {
prepare_luma: wgpu::ComputePipeline,
luma_pyramid: wgpu::ComputePipeline,
scd_histogram: wgpu::ComputePipeline,
scd_divergence: wgpu::ComputePipeline,
search: wgpu::ComputePipeline,
filter: wgpu::ComputePipeline,
scale: wgpu::ComputePipeline,
}
/// One frame parity's bindings: which luma pyramid is this frame's.
struct Frame {
/// This frame's luma at the display size, where `prepare_luma` writes.
luma0: wgpu::TextureView,
luma_pyramid: [wgpu::BindGroup; LEVELS - 1],
scd_histogram: wgpu::BindGroup,
search: [wgpu::BindGroup; LEVELS],
scale: [wgpu::BindGroup; LEVELS - 1],
}
pub struct OpticalFlow {
display: [u32; 2],
pipelines: Pipelines,
/// One per level, the level's constants (the passes outside the search use level 0's).
params: Vec<wgpu::Buffer>,
/// The bindings of the frames whose luma lands in pyramid 0, and in pyramid 1.
frames: [Frame; 2],
filter: [wgpu::BindGroup; LEVELS],
scd_divergence: wgpu::BindGroup,
scd_histogram: wgpu::Buffer,
scd_previous_histogram: wgpu::Buffer,
scd_temp: wgpu::Buffer,
scd_output: wgpu::Buffer,
vectors: wgpu::TextureView,
flow_sizes: [[u32; 2]; LEVELS],
/// `resourceFrameIndex` and `frameIndex`.
resource_frame: u32,
frame_index: u32,
first: bool,
}
fn texture(
device: &wgpu::Device,
label: &str,
size: [u32; 2],
format: wgpu::TextureFormat,
) -> wgpu::TextureView {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0].max(1),
height: size[1].max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::STORAGE_BINDING
| wgpu::TextureUsages::TEXTURE_BINDING
| wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
})
.create_view(&Default::default())
}
fn buffer(device: &wgpu::Device, label: &str, size: u64) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size,
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
})
}
/// Bind `entries` (binding number, resource) for `pipeline`'s own layout.
fn bind(
device: &wgpu::Device,
pipeline: &wgpu::ComputePipeline,
entries: &[(u32, wgpu::BindingResource)],
) -> wgpu::BindGroup {
let entries: Vec<_> = entries
.iter()
.map(|(binding, resource)| wgpu::BindGroupEntry {
binding: *binding,
resource: resource.clone(),
})
.collect();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Optical flow"),
layout: &pipeline.get_bind_group_layout(0),
entries: &entries,
})
}
fn view(v: &wgpu::TextureView) -> wgpu::BindingResource<'_> {
wgpu::BindingResource::TextureView(v)
}
fn whole(b: &wgpu::Buffer) -> wgpu::BindingResource<'_> {
b.as_entire_binding()
}
impl OpticalFlow {
/// For frames of `display` size.
pub fn new(device: &wgpu::Device, display: [u32; 2]) -> Self {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Optical flow"),
source: wgpu::ShaderSource::Wgsl(include_str!("optical_flow.wgsl").into()),
});
let pipeline = |entry: &str| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(entry),
layout: None,
module: &module,
entry_point: Some(entry),
compilation_options: Default::default(),
cache: None,
})
};
let pipelines = Pipelines {
prepare_luma: pipeline("prepare_luma"),
luma_pyramid: pipeline("luma_pyramid"),
scd_histogram: pipeline("scd_histogram_pass"),
scd_divergence: pipeline("scd_divergence_pass"),
search: pipeline("search_pass"),
filter: pipeline("filter_flow"),
scale: pipeline("scale_pass"),
};
let params: Vec<_> = (0..LEVELS)
.map(|_| {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Optical flow constants"),
size: std::mem::size_of::<Params>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
})
.collect();
let luma: [Vec<wgpu::TextureView>; 2] = [0, 1].map(|_| {
(0..LEVELS)
.map(|k| {
let size = display.map(|v| (v >> k).max(1));
texture(
device,
"Optical flow luma",
size,
wgpu::TextureFormat::R32Float,
)
})
.collect()
});
let mut flow_sizes = [[0; 2]; LEVELS];
flow_sizes[0] = display.map(|v| v.div_ceil(BLOCK_SIZE));
for l in 1..LEVELS {
flow_sizes[l] = flow_sizes[l - 1].map(|v| v.div_ceil(2));
}
let flow = |label| -> Vec<wgpu::TextureView> {
flow_sizes
.iter()
.map(|&size| texture(device, label, size, wgpu::TextureFormat::Rg32Sint))
.collect()
};
// Per level: the scaled prediction from the level above, the search's vectors and
// the filtered ones (level 0's are the output).
let (predicted, searched, filtered) = (
flow("Optical flow prediction"),
flow("Optical flow search"),
flow("Optical flow"),
);
let scd_histogram = buffer(device, "Scene change histogram", HISTOGRAM_WIDTH * 4);
let scd_previous_histogram = buffer(
device,
"Scene change previous histogram",
HISTOGRAM_WIDTH * 4,
);
let scd_temp = buffer(device, "Scene change temp", 12);
let scd_output = buffer(device, "Scene change detection", 12);
let frame = |current: usize| {
let (cur, prev) = (&luma[current], &luma[1 - current]);
Frame {
luma0: cur[0].clone(),
luma_pyramid: std::array::from_fn(|k| {
bind(
device,
&pipelines.luma_pyramid,
&[(2, view(&cur[k + 1])), (3, view(&cur[k]))],
)
}),
scd_histogram: bind(
device,
&pipelines.scd_histogram,
&[
(0, whole(&params[0])),
(3, view(&cur[0])),
(7, whole(&scd_histogram)),
],
),
search: std::array::from_fn(|l| {
bind(
device,
&pipelines.search,
&[
(0, whole(&params[l])),
(3, view(&cur[l])),
(4, view(&prev[l])),
(5, view(&predicted[l])),
(6, view(&searched[l])),
(10, whole(&scd_output)),
],
)
}),
scale: std::array::from_fn(|i| {
let l = i + 1;
bind(
device,
&pipelines.scale,
&[
(0, whole(&params[l])),
(3, view(&cur[l])),
(4, view(&prev[l])),
(5, view(&filtered[l])),
(6, view(&predicted[l - 1])),
(10, whole(&scd_output)),
],
)
}),
}
};
let frames = [frame(0), frame(1)];
let filter = std::array::from_fn(|l| {
bind(
device,
&pipelines.filter,
&[(5, view(&searched[l])), (6, view(&filtered[l]))],
)
});
let scd_divergence = bind(
device,
&pipelines.scd_divergence,
&[
(7, whole(&scd_histogram)),
(8, whole(&scd_previous_histogram)),
(9, whole(&scd_temp)),
(10, whole(&scd_output)),
],
);
Self {
display,
pipelines,
params,
frames,
filter,
scd_divergence,
scd_histogram,
scd_previous_histogram,
scd_temp,
scd_output,
vectors: filtered[0].clone(),
flow_sizes,
resource_frame: 0,
frame_index: 0,
first: true,
}
}
/// The flow from the previous call's `color` to this one's. `color`: `display` size,
/// a float texture holding Horizon's frame (gamma-encoded RGB, the swapchain's
/// values: AMD's SDR back buffer). `reset`: the previous frame is unrelated (first
/// frame, resize, teleport).
pub fn dispatch(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
color: &wgpu::TextureView,
reset: bool,
) {
let reset = reset || self.first;
self.first = false;
self.frame_index = if reset { 0 } else { self.frame_index + 1 };
if reset {
for b in [
&self.scd_temp,
&self.scd_output,
&self.scd_histogram,
&self.scd_previous_histogram,
] {
encoder.clear_buffer(b, 0, None);
}
}
for (level, buffer) in self.params.iter().enumerate() {
let params = Params {
display: self.display.map(|v| v as i32),
level: level as u32,
level_count: LEVELS as u32,
frame_index: self.frame_index,
transfer_function: 0,
min_max_luminance: [0.0, 1.0],
};
queue.write_buffer(buffer, 0, bytemuck::bytes_of(&params));
}
let frame = &self.frames[(self.resource_frame & 1) as usize];
let prepare = bind(
device,
&self.pipelines.prepare_luma,
&[
(0, whole(&self.params[0])),
(1, view(color)),
(2, view(&frame.luma0)),
],
);
let p = &self.pipelines;
let [w, h] = self.display;
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("Optical flow"),
timestamp_writes: None,
});
let mut run = |pipeline: &wgpu::ComputePipeline, group: &wgpu::BindGroup, x, y, z| {
pass.set_pipeline(pipeline);
pass.set_bind_group(0, group, &[]);
pass.dispatch_workgroups(x, y, z);
};
run(
&p.prepare_luma,
&prepare,
(w.div_ceil(2)).div_ceil(16),
(h.div_ceil(2)).div_ceil(16),
1,
);
for (k, group) in frame.luma_pyramid.iter().enumerate() {
let size = self.display.map(|v| (v >> (k + 1)).max(1));
run(
&p.luma_pyramid,
group,
size[0].div_ceil(8),
size[1].div_ceil(8),
1,
);
}
run(
&p.scd_histogram,
&frame.scd_histogram,
((w / 4) / 3).div_ceil(32),
16,
9,
);
run(&p.scd_divergence, &self.scd_divergence, 9, 3, 1);
for level in (0..LEVELS).rev() {
let luma = self.display.map(|v| (v >> level).max(1));
run(
&p.search,
&frame.search[level],
(luma[0].div_ceil(4) * 16).div_ceil(64),
luma[1].div_ceil(16),
1,
);
let size = self.flow_sizes[level];
run(
&p.filter,
&self.filter[level],
size[0].div_ceil(16),
size[1].div_ceil(4),
1,
);
if level > 0 {
let next = self.flow_sizes[level - 1];
run(
&p.scale,
&frame.scale[level - 1],
next[0].div_ceil(4),
next[1].div_ceil(4),
1,
);
}
}
drop(pass);
self.resource_frame = (self.resource_frame + 1) % 16;
}
/// This frame's vectors, one per `BLOCK_SIZE` block: `Rg32Sint`, the display size
/// over `BLOCK_SIZE` rounded up,
/// holding the values FSR's `R16G16_SINT` optical flow vector texture holds.
pub fn vectors(&self) -> &wgpu::TextureView {
&self.vectors
}
/// FSR's scene change detection texture (`R32_UINT`, 3 texels) as a storage
/// buffer of 3 `u32`: element `i` holds texel `i`'s value.
pub fn scene_change(&self) -> &wgpu::Buffer {
&self.scd_output
}
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
#[test]
fn shader_validates() {
let module = naga::front::wgsl::parse_str(include_str!("optical_flow.wgsl")).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::empty(),
)
.validate(&module)
.unwrap();
}
/// A device with WebGPU's default limits (what every GPU wgpu runs on has), or `None`
/// without a GPU.
pub fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
/// Noise in 4x4 pixel cells, moved by `shift` pixels: what was at `p` is at `p + shift`.
/// A `seed` of 100 or more gives cells of one primary each.
pub fn pattern(size: [u32; 2], seed: u32, shift: [i32; 2]) -> Vec<u8> {
let mut pixels = Vec::with_capacity((size[0] * size[1] * 4) as usize);
for y in 0..size[1] as i32 {
for x in 0..size[0] as i32 {
let (cx, cy) = ((x - shift[0]).div_euclid(4), (y - shift[1]).div_euclid(4));
let mut h = (cx as u32).wrapping_mul(0x9e37_79b9)
^ (cy as u32).wrapping_mul(0x85eb_ca6b)
^ seed.wrapping_mul(0xc2b2_ae35);
h ^= h >> 15;
h = h.wrapping_mul(0x2c1b_3c6d);
h ^= h >> 12;
let v = (h & 0xff) as u8;
if seed >= 100 {
// Primaries: no two neighbours' colours point the same way.
let mut c = [0, 0, 0, 255];
c[(h >> 8) as usize % 3] = 128 + v / 2;
pixels.extend_from_slice(&c);
} else {
pixels.extend_from_slice(&[v, v.wrapping_add(40), v / 2, 255]);
}
}
}
pixels
}
pub fn upload(
device: &wgpu::Device,
queue: &wgpu::Queue,
size: [u32; 2],
pixels: &[u8],
) -> wgpu::TextureView {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
queue.write_texture(
texture.as_image_copy(),
pixels,
wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(size[0] * 4),
rows_per_image: None,
},
texture.size(),
);
texture.create_view(&Default::default())
}
/// `texture`'s texels (`texel` bytes each), row by row.
pub fn read(
device: &wgpu::Device,
queue: &wgpu::Queue,
texture: &wgpu::Texture,
texel: u32,
) -> Vec<u8> {
let size = texture.size();
let row = (size.width * texel).next_multiple_of(256);
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(row * size.height),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = device.create_command_encoder(&Default::default());
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &buffer,
layout: wgpu::TexelCopyBufferLayout {
offset: 0,
bytes_per_row: Some(row),
rows_per_image: None,
},
},
size,
);
queue.submit([encoder.finish()]);
buffer.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let mapped = buffer.slice(..).get_mapped_range().unwrap();
mapped
.chunks(row as usize)
.flat_map(|r| r[..(size.width * texel) as usize].to_vec())
.collect()
}
fn run(
device: &wgpu::Device,
queue: &wgpu::Queue,
flow: &mut OpticalFlow,
color: &wgpu::TextureView,
reset: bool,
) {
let mut encoder = device.create_command_encoder(&Default::default());
flow.dispatch(device, queue, &mut encoder, color, reset);
queue.submit([encoder.finish()]);
}
fn vectors(device: &wgpu::Device, queue: &wgpu::Queue, flow: &OpticalFlow) -> Vec<[i32; 2]> {
read(device, queue, flow.vectors.texture(), 8)
.chunks(8)
.map(|c| {
[
i32::from_le_bytes(c[0..4].try_into().unwrap()),
i32::from_le_bytes(c[4..8].try_into().unwrap()),
]
})
.collect()
}
/// A frame moved right by 16 and down by 8: the blocks inside report where they were
/// (-16, -8), and nothing reads as a scene change. A much darker frame then does.
#[test]
fn finds_a_shift_and_a_scene_change() {
let Some((device, queue)) = device() else {
return;
};
let size = [512, 288];
let still = upload(&device, &queue, size, &pattern(size, 1, [0, 0]));
let moved = upload(&device, &queue, size, &pattern(size, 1, [16, 8]));
// Scene changes are told by the luma's histogram: a much darker frame.
let dark: Vec<u8> = pattern(size, 2, [0, 0]).iter().map(|v| v / 5).collect();
let other = upload(&device, &queue, size, &dark);
let mut flow = OpticalFlow::new(&device, size);
// The first 6 frames after a reset are scene changes.
run(&device, &queue, &mut flow, &still, true);
for _ in 0..6 {
run(&device, &queue, &mut flow, &still, false);
}
run(&device, &queue, &mut flow, &moved, false);
let [w, h] = flow.flow_sizes[0];
let found = vectors(&device, &queue, &flow);
let inside: Vec<_> = (4..h - 4)
.flat_map(|y| (4..w - 4).map(move |x| (x, y)))
.map(|(x, y)| found[(y * w + x) as usize])
.collect();
let right = inside.iter().filter(|v| **v == [-16, -8]).count();
assert!(
right * 10 >= inside.len() * 9,
"{right} of {} blocks: {:?}",
inside.len(),
&inside[..8]
);
let scd = |device: &wgpu::Device, queue: &wgpu::Queue, flow: &OpticalFlow| {
let mut encoder = device.create_command_encoder(&Default::default());
let buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: 12,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
encoder.copy_buffer_to_buffer(flow.scene_change(), 0, &buffer, 0, 12);
queue.submit([encoder.finish()]);
buffer.slice(..).map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let bytes = buffer.slice(..).get_mapped_range().unwrap().to_vec();
u32::from_le_bytes(bytes[4..8].try_into().unwrap())
};
assert_eq!(scd(&device, &queue, &flow) & 0xf, 0);
run(&device, &queue, &mut flow, &other, false);
assert_eq!(scd(&device, &queue, &flow) & 1, 1);
assert!(vectors(&device, &queue, &flow).iter().all(|v| *v == [0, 0]));
}
}
@@ -1,537 +0,0 @@
// This file is part of the FidelityFX SDK.
//
// Copyright (C) 2024 Advanced Micro Devices, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and /or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// FidelityFX SDK 1.1.4's optical flow (ffx_opticalflow_*.h, the GLSL path), ported to WGSL
// for Horizon. What differs from AMD's (optical_flow.rs lists why):
// - luma levels are r32float (AMD: r8ui); loads truncate to the same integers;
// - the luma pyramid is one pass per level instead of SPD's single pass;
// - wave sums and minimums are workgroup atomics, and the reductions AMD leaves to a
// wave's lockstep have barriers;
// - the scene change textures are storage buffers;
// - the search reads its prediction from one texture and writes another (rg32sint can't
// be read_write everywhere).
struct Params {
// Display size (cbOF.iInputLumaResolution).
display: vec2<i32>,
level: u32,
level_count: u32,
frame_index: u32,
transfer_function: u32,
min_max_luminance: vec2<f32>,
};
@group(0) @binding(0) var<uniform> params: Params;
@group(0) @binding(1) var input_color: texture_2d<f32>;
@group(0) @binding(2) var luma_out: texture_storage_2d<r32float, write>;
// The current frame's luma at this level, and the previous frame's.
@group(0) @binding(3) var luma_in: texture_2d<f32>;
@group(0) @binding(4) var luma_previous: texture_2d<f32>;
// Search: the prediction from the level above; filter: the search; scale: the filtered.
@group(0) @binding(5) var flow_in: texture_2d<i32>;
@group(0) @binding(6) var flow_out: texture_storage_2d<rg32sint, write>;
@group(0) @binding(7) var<storage, read_write> scd_histogram: array<atomic<u32>>;
@group(0) @binding(8) var<storage, read_write> scd_previous_histogram: array<f32>;
@group(0) @binding(9) var<storage, read_write> scd_temp: array<atomic<u32>, 3>;
@group(0) @binding(10) var<storage, read_write> scd_output: array<atomic<u32>, 3>;
const SCD_OUTPUT_SCENE_CHANGE_SLOT: u32 = 0u;
const SCD_OUTPUT_HISTORY_BITS_SLOT: u32 = 1u;
const SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT: u32 = 2u;
fn load_luma(t: texture_2d<f32>, p: vec2<i32>) -> u32 {
let size = vec2<i32>(textureDimensions(t));
if any(p < vec2(0)) || any(p >= size) {
return 0u;
}
return u32(textureLoad(t, p, 0).x);
}
fn load_flow(p: vec2<i32>) -> vec2<i32> {
let size = vec2<i32>(textureDimensions(flow_in));
if any(p < vec2(0)) || any(p >= size) {
return vec2(0);
}
return textureLoad(flow_in, p, 0).xy;
}
fn store_flow(p: vec2<i32>, v: vec2<i32>) {
let size = vec2<i32>(textureDimensions(flow_out));
if all(p >= vec2(0)) && all(p < size) {
textureStore(flow_out, p, vec4(v, 0, 0));
}
}
fn packed_luma(width: i32, x: i32, luma0: u32, luma1: u32, luma2: u32, luma3: u32) -> u32 {
var packed = luma0 | (luma1 << 8u) | (luma2 << 16u) | (luma3 << 24u);
if x < 0 {
let filler = packed & 0xffu;
if x <= -1 {
packed = (packed << 8u) | filler;
}
if x <= -2 {
packed = (packed << 8u) | filler;
}
if x <= -3 {
packed = (packed << 8u) | filler;
}
} else if x > width - 4 {
let filler = packed & 0xff000000u;
if x >= width - 3 {
packed = (packed >> 8u) | filler;
}
if x >= width - 2 {
packed = (packed >> 8u) | filler;
}
if x >= width - 1 {
packed = (packed >> 8u) | filler;
}
}
return packed;
}
fn load_packed(t: texture_2d<f32>, p: vec2<i32>) -> u32 {
let width = params.display.x >> params.level;
let height = params.display.y >> params.level;
let q = vec2(clamp(p.x, 0, width - 4), clamp(p.y, 0, height - 1));
return packed_luma(
width,
p.x,
load_luma(t, q),
load_luma(t, q + vec2(1, 0)),
load_luma(t, q + vec2(2, 0)),
load_luma(t, q + vec2(3, 0)),
);
}
fn sad(a: u32, b: u32) -> u32 {
return u32(abs(i32(a & 0xffu) - i32(b & 0xffu))
+ abs(i32((a >> 8u) & 0xffu) - i32((b >> 8u) & 0xffu))
+ abs(i32((a >> 16u) & 0xffu) - i32((b >> 16u) & 0xffu))
+ abs(i32((a >> 24u) & 0xffu) - i32((b >> 24u) & 0xffu)));
}
fn qsad(a0_in: u32, a1_in: u32, b: u32) -> vec4<u32> {
var a0 = a0_in;
var a1 = a1_in;
var s: vec4<u32>;
s.x = sad(a0, b);
a0 = (a0 >> 8u) | ((a1 & 0xffu) << 24u);
a1 = a1 >> 8u;
s.y = sad(a0, b);
a0 = (a0 >> 8u) | ((a1 & 0xffu) << 24u);
a1 = a1 >> 8u;
s.z = sad(a0, b);
a0 = (a0 >> 8u) | ((a1 & 0xffu) << 24u);
s.w = sad(a0, b);
return s;
}
fn is_scene_changed() -> bool {
if params.frame_index <= 5u {
return true;
}
return (atomicLoad(&scd_output[SCD_OUTPUT_HISTORY_BITS_SLOT]) & 0xfu) != 0u;
}
// ffx_opticalflow_prepare_luma.h, for an SDR back buffer (transfer function 0: Horizon's
// frames); the HDR transfer functions follow AMD's.
fn luminance_to_perceived(luminance: f32) -> f32 {
var perceived: f32;
if luminance <= 216.0 / 24389.0 {
perceived = luminance * (24389.0 / 27.0);
} else {
perceived = pow(luminance, 1.0 / 3.0) * 116.0 - 16.0;
}
return perceived * 0.01;
}
fn linear_from_pq(x: vec3<f32>) -> vec3<f32> {
let p = pow(x, vec3(0.0126833));
return pow(clamp(p - vec3(0.835938), vec3(0.0), vec3(1.0)) / (vec3(18.8516) - 18.6875 * p), vec3(6.27739));
}
@compute @workgroup_size(16, 16)
fn prepare_luma(@builtin(global_invocation_id) gid: vec3<u32>) {
for (var y = 0; y < 2; y++) {
for (var x = 0; x < 2; x++) {
let pos = vec2<i32>(gid.xy) * 2 + vec2(x, y);
if any(pos >= params.display) {
continue;
}
let c = textureLoad(input_color, pos, 0).rgb;
var y_lum = 0.0;
if params.transfer_function == 0u {
y_lum = dot(c, vec3(0.2126, 0.7152, 0.0722));
} else if params.transfer_function == 1u {
let linear = linear_from_pq(c) * (10000.0 / params.min_max_luminance.y);
y_lum = luminance_to_perceived(dot(linear, vec3(0.2627, 0.678, 0.0593)));
} else if params.transfer_function == 2u {
let mn = params.min_max_luminance.x;
let mx = params.min_max_luminance.y;
let linear = (c - vec3(mn / 80.0)) / vec3((mx - mn) / 80.0);
y_lum = luminance_to_perceived(dot(linear, vec3(0.2126, 0.7152, 0.0722)));
}
textureStore(luma_out, pos, vec4(f32(u32(y_lum * 255.0)), 0.0, 0.0, 0.0));
}
}
}
// ffx_opticalflow_compute_luminance_pyramid.h: SPD's average of 2x2, a level per pass.
@compute @workgroup_size(8, 8)
fn luma_pyramid(@builtin(global_invocation_id) gid: vec3<u32>) {
let p = vec2<i32>(gid.xy);
if any(p >= vec2<i32>(textureDimensions(luma_out))) {
return;
}
let s = p * 2;
let v = (textureLoad(luma_in, s, 0).x + textureLoad(luma_in, s + vec2(1, 0), 0).x
+ textureLoad(luma_in, s + vec2(0, 1), 0).x + textureLoad(luma_in, s + vec2(1, 1), 0).x) * 0.25;
textureStore(luma_out, p, vec4(v, 0.0, 0.0, 0.0));
}
// ffx_opticalflow_generate_scd_histogram.h
const LBASE: u32 = 10u;
var<workgroup> scd_buffer: array<atomic<u32>, 2560>;
@compute @workgroup_size(32, 8)
fn scd_histogram_pass(
@builtin(global_invocation_id) gid: vec3<u32>,
@builtin(local_invocation_index) local_index: u32,
) {
let histograms_per_dim = 3u;
let div = vec2<u32>(params.display) / histograms_per_dim;
let nx = gid.z % histograms_per_dim;
let ny = gid.z / histograms_per_dim;
let start = div * vec2(nx, ny);
let stop = start + div;
let offset = local_index * LBASE;
for (var i = 0u; i < LBASE; i++) {
atomicStore(&scd_buffer[offset + i], 0u);
}
workgroupBarrier();
var coord = vec2<i32>(i32(start.x + 4u * gid.x), i32(start.y + gid.y));
if u32(coord.x) < stop.x {
for (; u32(coord.y) < stop.y; coord.y += 128) {
let color = vec4(
load_luma(luma_in, coord),
load_luma(luma_in, coord + vec2(1, 0)),
load_luma(luma_in, coord + vec2(2, 0)),
load_luma(luma_in, coord + vec2(3, 0)),
) * LBASE;
let scrambling = local_index % LBASE;
atomicAdd(&scd_buffer[color.x + scrambling], 1u);
atomicAdd(&scd_buffer[color.y + scrambling], 1u);
atomicAdd(&scd_buffer[color.z + scrambling], 1u);
atomicAdd(&scd_buffer[color.w + scrambling], 1u);
}
}
workgroupBarrier();
var value = 0u;
for (var i = 0u; i < LBASE; i++) {
value += atomicLoad(&scd_buffer[offset + i]);
}
let histogram_start = 256u * gid.z;
atomicAdd(&scd_histogram[histogram_start + local_index], value);
}
// ffx_opticalflow_compute_scd_divergence.h
var<workgroup> source_histogram: array<f32, 256>;
var<workgroup> filtered_histogram: array<f32, 256>;
var<workgroup> temp_buffer: array<f32, 256>;
var<workgroup> temp_buffer2: array<vec2<f32>, 256>;
@compute @workgroup_size(256)
fn scd_divergence_pass(
@builtin(global_invocation_id) gid: vec3<u32>,
@builtin(local_invocation_index) local_index: u32,
) {
let factor = 1000000.0;
let where_to_stop = 3u * 9u - 1u;
let histogram_count = 9.0;
let kernel = array(0.0088122291, 0.027143577, 0.065114059, 0.12164907, 0.17699835, 0.20056541);
let li = i32(local_index);
source_histogram[li] = f32(atomicLoad(&scd_histogram[gid.x]));
workgroupBarrier();
let read = li - 5;
var val = 0.0;
val += kernel[0] * source_histogram[clamp(read + 0, 0, 255)];
val += kernel[1] * source_histogram[clamp(read + 1, 0, 255)];
val += kernel[2] * source_histogram[clamp(read + 2, 0, 255)];
val += kernel[3] * source_histogram[clamp(read + 3, 0, 255)];
val += kernel[4] * source_histogram[clamp(read + 4, 0, 255)];
val += kernel[5] * source_histogram[clamp(read + 5, 0, 255)];
val += kernel[4] * source_histogram[clamp(read + 6, 0, 255)];
val += kernel[3] * source_histogram[clamp(read + 7, 0, 255)];
val += kernel[2] * source_histogram[clamp(read + 8, 0, 255)];
val += kernel[1] * source_histogram[clamp(read + 9, 0, 255)];
val += kernel[0] * source_histogram[clamp(read + 10, 0, 255)];
val += 1.0;
if gid.y == 0u {
if li == 0 {
filtered_histogram[255] = 1.0;
} else {
filtered_histogram[li - 1] = val;
}
} else if gid.y == 1u {
filtered_histogram[li] = val;
} else if gid.y == 2u {
if li == 255 {
filtered_histogram[0] = 1.0;
} else {
filtered_histogram[li + 1] = val;
}
}
workgroupBarrier();
temp_buffer[li] = filtered_histogram[li];
workgroupBarrier();
for (var stride = 128; stride > 0; stride >>= 1u) {
if li < stride {
temp_buffer[li] += temp_buffer[li + stride];
}
workgroupBarrier();
}
filtered_histogram[li] /= temp_buffer[0];
let current = filtered_histogram[li];
let previous = scd_previous_histogram[gid.x];
temp_buffer2[li] = vec2(current * log(current / previous), previous * log(previous / current));
workgroupBarrier();
for (var stride = 128; stride > 0; stride >>= 1u) {
if li < stride {
temp_buffer2[li] += temp_buffer2[li + stride];
}
workgroupBarrier();
}
if li == 0 {
let sum = temp_buffer2[0];
let res_float = 1.0 - exp(-(abs(sum.x) + abs(sum.y)));
let res_uint = u32((res_float / histogram_count) * factor);
atomicAdd(&scd_temp[gid.y], res_uint);
let finished = atomicAdd(&scd_output[SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT], 1u);
if finished == where_to_stop {
let res0 = atomicLoad(&scd_temp[0]);
let res1 = atomicLoad(&scd_temp[1]);
let res2 = atomicLoad(&scd_temp[2]);
let scene_change = f32(min(res0, min(res1, res2))) / factor;
var history = atomicLoad(&scd_output[SCD_OUTPUT_HISTORY_BITS_SLOT]) << 1u;
if scene_change > 0.45 {
history |= 1u;
}
atomicStore(&scd_output[SCD_OUTPUT_SCENE_CHANGE_SLOT], bitcast<u32>(scene_change));
atomicStore(&scd_output[SCD_OUTPUT_HISTORY_BITS_SLOT], history);
atomicStore(&scd_output[SCD_OUTPUT_COMPLETED_WORKGROUPS_SLOT], 0u);
atomicStore(&scd_temp[0], 0u);
atomicStore(&scd_temp[1], 0u);
atomicStore(&scd_temp[2], 0u);
}
}
if gid.y == 1u {
scd_previous_histogram[gid.x] = current;
atomicStore(&scd_histogram[gid.x], 0u);
}
}
// ffx_opticalflow_compute_optical_flow_v5.h: block matching of 8x8 blocks over +-8 pixels,
// 2x2 blocks per workgroup of 64.
var<workgroup> pixels: array<array<u32, 2>, 8>;
// SearchBufferSizeY (24) rows of SearchBufferSizeX (6) packed lumas.
var<workgroup> search_buffer: array<u32, 144>;
var<workgroup> sad_map: array<array<array<u32, 5>, 16>, 4>;
var<workgroup> wave_min: atomic<u32>;
var<workgroup> wave_sum: atomic<u32>;
var<workgroup> scene_changed: u32;
fn abs_2(v: vec2<i32>) -> vec2<u32> {
let mask = v >> vec2(31u);
return vec2<u32>((v + mask) ^ mask);
}
// FFX_OPTICALFLOW_FIX_TOP_LEFT_BIAS: the nearest of equal SADs wins.
fn encode_search_coord(coord: vec2<i32>) -> u32 {
let a = abs_2(coord - 8);
return (a.y << 12u) | (a.x << 8u) | (u32(coord.y) << 4u) | u32(coord.x);
}
fn decode_search_coord(bits: u32) -> vec2<i32> {
return vec2(i32(bits & 0xfu) - 8, i32((bits >> 4u) & 0xfu) - 8);
}
fn calculate_qsads2(search_id: vec2<i32>) -> vec4<u32> {
var s = vec4(0u);
for (var dy = 0; dy < 8; dy++) {
let row = (search_id.y + dy) * 6;
let a0 = search_buffer[row + search_id.x];
let a1 = search_buffer[row + search_id.x + 1];
let a2 = search_buffer[row + search_id.x + 2];
s += qsad(a0, a1, pixels[dy][0]);
s += qsad(a1, a2, pixels[dy][1]);
}
return s;
}
@compute @workgroup_size(64)
fn search_pass(
@builtin(workgroup_id) group_id: vec3<u32>,
@builtin(local_invocation_index) local_index: u32,
) {
let li = i32(local_index);
let search_id = vec2(li & 3, (li >> 2u) & 15);
let lane_block = ((li >> 1u) & 1) | (((li >> 5u) & 1) << 1u);
let group = vec2<i32>(group_id.xy);
let px = (group << vec2(4u)) + search_id * vec2(4, 1);
if local_index == 0u {
scene_changed = u32(is_scene_changed());
}
if workgroupUniformLoad(&scene_changed) != 0u {
if (search_id.y & 7) == 0 && (search_id.x & 1) == 0 {
store_flow(px >> vec2(3u), vec2(0));
}
return;
}
let use_prediction = params.level != params.level_count - 1u;
let packed = load_packed(luma_in, px);
let sad_4blocks = sad(packed, load_packed(luma_previous, px));
let of_group = group << vec2(1u);
let pixel_group = group << vec2(4u);
for (var by = 0; by < 2; by++) {
for (var bx = 0; bx < 2; bx++) {
let block = vec2(bx, by);
var current = vec2(0);
if use_prediction {
current = load_flow(of_group + block);
}
if lane_block == by * 2 + bx {
pixels[search_id.y & 7][search_id.x & 1] = packed;
}
// LoadSearchBuffer
let base = pixel_group + block * 8 + current - vec2(8, 8);
for (var id = li; id < 144; id += 64) {
search_buffer[id] = load_packed(luma_previous, vec2(base.x + (id % 6) * 4, base.y + id / 6));
}
if local_index == 0u {
atomicStore(&wave_min, 0xffffffffu);
atomicStore(&wave_sum, 0u);
}
workgroupBarrier();
let q = calculate_qsads2(search_id);
// PrepareSadMap
let sx = search_id.x;
let sy = search_id.y;
sad_map[0][sy][sx] = (q.x << 16u) | encode_search_coord(vec2(sx * 4 + 0, sy));
sad_map[1][sy][sx] = (q.y << 16u) | encode_search_coord(vec2(sx * 4 + 1, sy));
sad_map[2][sy][sx] = (q.z << 16u) | encode_search_coord(vec2(sx * 4 + 2, sy));
sad_map[3][sy][sx] = (q.w << 16u) | encode_search_coord(vec2(sx * 4 + 3, sy));
workgroupBarrier();
// SadMapMinReduction256 and BlockSad64 (FFX_LOCAL_SEARCH_FALLBACK)
let min01 = min(sad_map[0][sy][sx], sad_map[1][sy][sx]);
let min23 = min(sad_map[2][sy][sx], sad_map[3][sy][sx]);
atomicMin(&wave_min, min(min01, min23));
atomicAdd(&wave_sum, select(0u, sad_4blocks, lane_block == bx + by * 2));
workgroupBarrier();
let min_sad = atomicLoad(&wave_min);
let block_sad_sum = atomicLoad(&wave_sum);
var v = current + decode_search_coord(min_sad);
if params.level == 0u && block_sad_sum <= (min_sad >> 16u) {
v = vec2(0);
}
if local_index == 0u {
store_flow(of_group + block, v);
}
// The next block reuses the shared buffers and counters.
workgroupBarrier();
}
}
}
// ffx_opticalflow_filter_optical_flow_v5.h: the vector of the 3x3 nearest to all the others.
@compute @workgroup_size(16, 4)
fn filter_flow(@builtin(global_invocation_id) gid: vec3<u32>) {
let p = vec2<i32>(gid.xy);
var mv: array<vec2<i32>, 9>;
var idx = 0;
for (var xx = -1; xx < 2; xx++) {
for (var yy = -1; yy < 2; yy++) {
mv[idx] = load_flow(p + vec2(xx, yy));
idx++;
}
}
var ret = 0xffffffffu;
for (var i = 0; i < 9; i++) {
var tmp = 0u;
for (var j = 0; j < 9; j++) {
let delta = mv[i] - mv[j];
tmp = u32(delta.x * delta.x) + (u32(delta.y * delta.y) + tmp);
}
ret = min((tmp << 4u) | u32(i), ret);
}
store_flow(p, mv[ret & 0xfu]);
}
// ffx_opticalflow_scale_optical_flow_advanced_v5.h: the next level's vectors, each the
// best of its 4 nearest at this level.
var<workgroup> nearest_vectors: array<array<array<vec2<i32>, 4>, 4>, 4>;
var<workgroup> local_region: array<array<array<u32, 4>, 4>, 4>;
var<workgroup> sads: array<array<array<u32, 4>, 4>, 4>;
@compute @workgroup_size(4, 4, 4)
fn scale_pass(
@builtin(global_invocation_id) gid: vec3<u32>,
@builtin(local_invocation_id) lid: vec3<u32>,
@builtin(local_invocation_index) local_index: u32,
) {
if local_index == 0u {
scene_changed = u32(is_scene_changed());
}
if workgroupUniformLoad(&scene_changed) != 0u {
store_flow(vec2<i32>(gid.xy), vec2(0));
return;
}
let x_offset = i32(lid.z % 2u) - 1 + i32(gid.x % 2u);
let y_offset = i32(lid.z / 2u) - 1 + i32(gid.y % 2u);
let src = vec2(i32(gid.x / 2u) + x_offset, i32(gid.y / 2u) + y_offset);
let nearest = load_flow(src);
nearest_vectors[lid.z][lid.y][lid.x] = nearest * 2;
let max_y = 4u;
for (var n = lid.z; n < max_y; n += 4u) {
let luma_pos = vec2(i32(gid.x) * 4, i32(gid.y * max_y + n));
local_region[n][lid.y][lid.x] = load_packed(luma_in, luma_pos);
}
workgroupBarrier();
var s = 0u;
for (var n = 0u; n < max_y; n++) {
let luma_pos = vec2(i32(gid.x) * 4, i32(gid.y * max_y + n)) + nearest;
s += sad(local_region[n][lid.y][lid.x], load_packed(luma_previous, luma_pos));
}
sads[lid.z][lid.y][lid.x] = s;
workgroupBarrier();
if lid.z == 0u {
var best_sad = 0xffffffffu;
var best = 0u;
for (var n = 0u; n < 4u; n++) {
if sads[n][lid.y][lid.x] < best_sad {
best_sad = sads[n][lid.y][lid.x];
best = n;
}
}
store_flow(vec2<i32>(gid.xy), nearest_vectors[best][lid.y][lid.x]);
}
}
-542
View File
@@ -1,542 +0,0 @@
//! HDR output (Horizon setting, off by default): the frame renders exactly as
//! without it, into an 8-bit target in vanilla's gamma space, and one pass
//! (`hdr.wgsl`) writes it to an HDR10 or scRGB swapchain at the player's paper
//! white, expanding the world's highlights towards their peak brightness. The
//! world is copied aside before the hand and HUD so only it is expanded.
/// The swapchain HDR output presents to.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Output {
/// HDR10: 10-bit BT.2020 with the PQ curve, the display's own signal.
Pq,
/// scRGB: linear 16-bit float, BT.709 primaries, 1.0 = 80 nits.
ScRgb,
}
impl Output {
pub fn name(self) -> &'static str {
match self {
Self::Pq => "HDR10 (PQ)",
Self::ScRgb => "scRGB",
}
}
pub fn format(self) -> wgpu::TextureFormat {
match self {
Self::Pq => wgpu::TextureFormat::Rgb10a2Unorm,
Self::ScRgb => wgpu::TextureFormat::Rgba16Float,
}
}
pub fn color_space(self) -> wgpu::SurfaceColorSpace {
match self {
Self::Pq => wgpu::SurfaceColorSpace::Bt2100Pq,
Self::ScRgb => wgpu::SurfaceColorSpace::ExtendedSrgbLinear,
}
}
fn space(self) -> wgpu::SurfaceColorSpaces {
match self {
Self::Pq => wgpu::SurfaceColorSpaces::BT2100_PQ,
Self::ScRgb => wgpu::SurfaceColorSpaces::EXTENDED_SRGB_LINEAR,
}
}
}
/// The HDR output `caps` can present: HDR10 where offered, else scRGB.
/// `HORIZON_HDR_OUTPUT=pq` or `scrgb` allows only that one.
pub fn output(caps: &wgpu::SurfaceCapabilities) -> Option<Output> {
pick(caps, std::env::var("HORIZON_HDR_OUTPUT").ok().as_deref())
}
fn pick(caps: &wgpu::SurfaceCapabilities, only: Option<&str>) -> Option<Output> {
[(Output::Pq, "pq"), (Output::ScRgb, "scrgb")]
.into_iter()
.filter(|(_, name)| only.is_none_or(|o| o == *name))
.map(|(output, _)| output)
.find(|o| caps.color_spaces(o.format()).contains(o.space()))
}
struct Targets {
size: [u32; 2],
frame: wgpu::Texture,
world: wgpu::Texture,
group: wgpu::BindGroup,
}
/// How one tier of light sources (`mesher::hdr_tier`) shines: `share` of the headroom for
/// its brightest pixels, lifted from brightness `start` (none) to `full` (all of it).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Tier {
pub share: f32,
pub start: f32,
pub full: f32,
}
/// Low, incandescent, bright and very bright.
pub const TIERS: [Tier; 4] = [
Tier {
share: 0.2,
start: 0.08,
full: 0.09,
},
Tier {
share: 0.5,
start: 0.14,
full: 0.38,
},
Tier {
share: 0.6,
start: 0.14,
full: 0.38,
},
Tier {
share: 1.0,
start: 0.14,
full: 0.38,
},
];
pub struct Hdr {
layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
/// Zeroes the frame's alpha once the world is kept (`keep_world`): what draws after,
/// the hand, HUD and menus, raises it, so HDR output knows where they cover the world.
clear_alpha: wgpu::RenderPipeline,
/// Scales the frame's alpha down to 1/255 where the hand drew (`mark_hand`), so HDR
/// output keeps the hand at the world's brightness.
hand_mark: wgpu::RenderPipeline,
params: wgpu::Buffer,
/// The same pass drawing HDR10 for a screenshot (`capture`), with its own parameters,
/// so it can differ from the swapchain's in one frame.
capture_pipeline: wgpu::RenderPipeline,
capture_params: wgpu::Buffer,
pub output: Output,
/// The frame's format: what every other pipeline draws in.
format: wgpu::TextureFormat,
targets: Option<Targets>,
/// `HORIZON_HDR_DEBUG=1`: grey what isn't expanded, tint what is magenta.
debug: bool,
/// Paper white and peak brightness, in nits.
pub paper_white: f32,
pub peak: f32,
/// The display's black level, in nits: shadows are lifted onto it (`hdr.wgsl`).
pub black: f32,
pub tiers: [Tier; 4],
/// The HUD and menus' brightness, as a share of paper white (0.25..=1).
pub ui: f32,
}
impl Hdr {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, output: Output) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon HDR"),
source: wgpu::ShaderSource::Wgsl(include_str!("../hdr.wgsl").into()),
});
let texture = |binding| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon HDR bindings"),
entries: &[
texture(0),
texture(1),
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon HDR"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline_for = |format| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon HDR"),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_hdr"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_hdr"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let alpha_pass = |label, blend| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&device.create_pipeline_layout(&Default::default())),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_hdr"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_clear_alpha"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend,
write_mask: wgpu::ColorWrites::ALPHA,
})],
}),
multiview_mask: None,
cache: None,
})
};
let clear_alpha = alpha_pass("Horizon HDR UI mask", None);
// Alpha times the blend constant (1/255): the hand's 1 becomes 1/255, the world's 0
// stays 0.
let scale_alpha = wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::Zero,
dst_factor: wgpu::BlendFactor::Constant,
operation: wgpu::BlendOperation::Add,
};
let hand_mark = alpha_pass(
"Horizon HDR hand mark",
Some(wgpu::BlendState {
color: scale_alpha,
alpha: scale_alpha,
}),
);
let params = || {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon HDR parameters"),
size: 80,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
};
Self {
layout,
pipeline: pipeline_for(output.format()),
clear_alpha,
hand_mark,
params: params(),
capture_pipeline: pipeline_for(Output::Pq.format()),
capture_params: params(),
output,
format,
targets: None,
debug: std::env::var_os("HORIZON_HDR_DEBUG").is_some_and(|v| v == "1"),
paper_white: 200.0,
peak: 1000.0,
black: 0.0,
tiers: TIERS,
ui: 1.0,
}
}
/// The 8-bit frame every pass draws into this frame, sized like the window.
pub fn frame(&mut self, device: &wgpu::Device, size: [u32; 2]) -> wgpu::Texture {
if self.targets.as_ref().is_none_or(|t| t.size != size) {
let texture = |label, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0].max(1),
height: size[1].max(1),
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.format,
usage: usage | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
};
let frame = texture(
"Horizon HDR frame",
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
let world = texture("Horizon HDR world", wgpu::TextureUsages::COPY_DST);
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon HDR bindings"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view(&frame)),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&view(&world)),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.params.as_entire_binding(),
},
],
});
self.targets = Some(Targets {
size,
frame,
world,
group,
});
}
self.targets.as_ref().unwrap().frame.clone()
}
/// Keeps the world as drawn so far, before the hand and HUD cover it, then zeroes the
/// frame's alpha: the world's marks live on in the copy, and whatever draws from here
/// on raises the alpha where it covers the world.
pub fn keep_world(&self, encoder: &mut wgpu::CommandEncoder) {
let Some(t) = &self.targets else {
return;
};
encoder.copy_texture_to_texture(
t.frame.as_image_copy(),
t.world.as_image_copy(),
t.frame.size(),
);
let view = t.frame.create_view(&Default::default());
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon HDR UI mask"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.clear_alpha);
pass.draw(0..3, 0..1);
}
/// After the hand: its pixels' alpha goes down to 1/255, below anything the HUD and
/// menus leave, so HDR output tells the hand (the world's brightness, never lifted)
/// from the UI (UI Brightness).
pub fn mark_hand(&self, encoder: &mut wgpu::CommandEncoder) {
let Some(t) = &self.targets else {
return;
};
let view = t.frame.create_view(&Default::default());
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon HDR hand mark"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&self.hand_mark);
let a = 1.0 / 255.0;
pass.set_blend_constant(wgpu::Color {
r: a,
g: a,
b: a,
a,
});
pass.draw(0..3, 0..1);
}
/// Writes the finished frame to the swapchain image `target`.
pub fn present(
&self,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::Texture,
world: bool,
) {
let Some(t) = &self.targets else {
return;
};
queue.write_buffer(
&self.params,
0,
bytemuck::cast_slice(&self.params(world, self.output == Output::Pq)),
);
Self::draw(encoder, &self.pipeline, &t.group, target);
}
/// The frame `present` writes, as HDR10 (BT.2020, PQ, 10 bits a channel) whatever
/// the swapchain is, in a texture of its own for a screenshot (`Rgb10a2Unorm`).
pub fn capture(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
world: bool,
) -> Option<wgpu::Texture> {
let t = self.targets.as_ref()?;
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon HDR screenshot"),
size: t.frame.size(),
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: Output::Pq.format(),
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
let group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon HDR screenshot bindings"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&view(&t.frame)),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::TextureView(&view(&t.world)),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.capture_params.as_entire_binding(),
},
],
});
queue.write_buffer(
&self.capture_params,
0,
bytemuck::cast_slice(&self.params(world, true)),
);
Self::draw(encoder, &self.capture_pipeline, &group, &texture);
Some(texture)
}
/// hdr.wgsl's `Params`.
fn params(&self, world: bool, pq: bool) -> [f32; 20] {
let paper = self.paper_white.max(1.0);
let mut params = [0.0; 20];
params[..5].copy_from_slice(&[
paper / 80.0,
(self.peak / paper).max(1.0),
f32::from(u8::from(world)),
f32::from(u8::from(self.debug)),
f32::from(u8::from(pq)),
]);
params[5] = self.black.clamp(0.0, paper);
params[6] = self.ui.clamp(0.25, 1.0);
for (i, t) in self.tiers.iter().enumerate() {
params[8 + i] = t.share;
params[12 + i] = t.start;
params[16 + i] = t.full;
}
params
}
fn draw(
encoder: &mut wgpu::CommandEncoder,
pipeline: &wgpu::RenderPipeline,
group: &wgpu::BindGroup,
target: &wgpu::Texture,
) {
let view = target.create_view(&Default::default());
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon HDR"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(pipeline);
pass.set_bind_group(0, group, &[]);
pass.draw(0..3, 0..1);
}
}
#[cfg(test)]
mod tests {
use super::{Output, pick};
use wgpu::{SurfaceColorSpaces as S, TextureFormat as F};
#[test]
fn hdr_shaders_validate() {
let entity = crate::overlay::wgsl_constants() + include_str!("../entity.wgsl");
for source in [
include_str!("../hdr.wgsl"),
include_str!("../terrain.wgsl"),
&entity,
] {
let module = naga::front::wgsl::parse_str(source).unwrap();
naga::valid::Validator::new(
naga::valid::ValidationFlags::all(),
naga::valid::Capabilities::all(),
)
.validate(&module)
.unwrap();
}
}
fn caps(offered: &[(F, S)]) -> wgpu::SurfaceCapabilities {
wgpu::SurfaceCapabilities {
format_capabilities: offered
.iter()
.map(|&(format, color_spaces)| wgpu::SurfaceFormatCapabilities {
format,
color_spaces,
})
.collect(),
..Default::default()
}
}
#[test]
fn hdr10_first_then_scrgb() {
let both = caps(&[
(F::Bgra8UnormSrgb, S::SRGB),
(F::Rgb10a2Unorm, S::BT2100_PQ | S::BT2100_HLG),
(F::Rgba16Float, S::EXTENDED_SRGB_LINEAR),
]);
assert_eq!(pick(&both, None), Some(Output::Pq));
assert_eq!(pick(&both, Some("scrgb")), Some(Output::ScRgb));
let scrgb = caps(&[(F::Rgba16Float, S::EXTENDED_SRGB_LINEAR)]);
assert_eq!(pick(&scrgb, None), Some(Output::ScRgb));
assert_eq!(pick(&scrgb, Some("pq")), None);
assert_eq!(pick(&caps(&[(F::Bgra8UnormSrgb, S::SRGB)]), None), None);
}
}
-540
View File
@@ -1,540 +0,0 @@
//! Far meshes share the terrain arena and passes, with their actual bounds
//! rather than the 16³ boxes used by the near-section residency walk.
use super::{Frustum, Renderer, SectionGpu};
use crate::{
fast_hash::{FxHashMap, FxHashSet},
lod::{MAX_LEVEL, TileKey},
mesher::SectionMesh,
};
use glam::{DVec3, Vec3};
use std::time::{Duration, Instant};
/// Finished tile meshes not uploaded yet, the tiles they replace (removed
/// once every mesh is in) and the columns they leave out.
#[derive(Default)]
pub(super) struct Pending {
meshes: FxHashMap<TileKey, SectionMesh>,
removed: FxHashSet<TileKey>,
cutout: Option<FxHashSet<(i32, i32)>>,
}
impl Pending {
/// Takes in the next job, with the same result as applying both in
/// turn: newer meshes replace waiting ones, tiles meshed again are not
/// removed, and tiles removed now drop their waiting meshes.
fn add(
&mut self,
meshes: Vec<(TileKey, SectionMesh)>,
removed: Vec<TileKey>,
cutout: Option<FxHashSet<(i32, i32)>>,
) {
for (key, mesh) in meshes {
self.removed.remove(&key);
self.meshes.insert(key, mesh);
}
for key in removed {
self.meshes.remove(&key);
self.removed.insert(key);
}
if cutout.is_some() {
self.cutout = cutout;
}
}
}
pub(super) struct Tile {
pub mesh: SectionGpu,
bounds: Bounds,
/// When it began to fade in; none while the rest of its job uploads.
shown: Option<Instant>,
/// When its replacements began to fade in; it goes once they have.
dying: Option<Instant>,
/// Dying with nothing to replace it (out of range): it fades out.
alone: bool,
/// Its mesh before near chunks took some of its columns, drawn in its
/// place until they have faded in (from the job's end, the instant), so
/// no hole shows through them.
previous: Option<(SectionGpu, Option<Instant>)>,
}
/// How long a tile takes to fade in over the ones it replaces.
pub(super) const FADE: Duration = Duration::from_millis(600);
/// A tile or section fading in: 0 drawn whole, else 1 + `level` * 129 +
/// `shown`, `shown` 1 to 63 sixty-fourths of `FADE` (`fade_out_code`: 65 to
/// 128, fading out). Chunk by chunk (columns of its own grid, wider for
/// coarse tiles: 2^`level` blocks), each starting in turn over the first half
/// and fading over the second, as a fine ordered pattern fixed to the terrain
/// (terrain.wgsl's `faded`). It is drawn a hair toward the camera, the newest
/// most, over the solid tiles it replaces, which stay until it is whole
/// (`upload_lods`): no pixel fought over, no hole. None: nothing to draw yet.
pub(super) fn fade_code(shown: Option<Instant>, level: u8, now: Instant) -> Option<u32> {
let faded = now.saturating_duration_since(shown?).as_secs_f32() / FADE.as_secs_f32();
let shown = (faded * 64.0) as u32 + 1;
Some(if shown >= 64 {
0
} else {
1 + u32::from(level) * 129 + shown
})
}
/// A section past the render distance that far terrain is coming in under:
/// whole, a fading-out code at its start (terrain.wgsl's `fade_depth` draws
/// leaving sections in front of far terrain).
pub(super) const HELD: u32 = 1 + 64;
/// `fade_code` for one leaving since `since`, chunk by chunk as it came, over
/// what stays behind it; once `FADE` has passed it draws nothing.
pub(super) fn fade_out_code(since: Instant, level: u8, now: Instant) -> u32 {
let faded = now.saturating_duration_since(since).as_secs_f32() / FADE.as_secs_f32();
1 + u32::from(level) * 129 + 64 + ((faded * 64.0) as u32 + 1).min(64)
}
#[derive(Clone, Copy)]
struct Bounds {
min: Vec3,
max: Vec3,
}
impl Bounds {
fn mesh(mesh: &SectionMesh) -> Option<Self> {
let mut positions = mesh
.solid
.iter()
.chain(&mesh.translucent)
.map(|v| Vec3::from(v.pos));
let first = positions.next()?;
let mut bounds = Self {
min: first,
max: first,
};
for pos in positions {
bounds.min = bounds.min.min(pos);
bounds.max = bounds.max.max(pos);
}
Some(bounds)
}
/// In view: the plan alone decides which tiles are in range (a circle),
/// so a tile leaving it fades out (`upload_lods`). Cut here at the range,
/// tiles popped out as the player moved, before the plan dropped them.
fn visible(self, origin: DVec3, frustum: &Frustum) -> Option<u64> {
let min = origin + self.min.as_dvec3();
let max = origin + self.max.as_dvec3();
if !frustum.intersects(min.as_vec3(), max.as_vec3()) {
return None;
}
Some(((min + max) * 0.5).length_squared().to_bits())
}
}
/// A tile's instance: like a section's, with the UV step of merged faces.
/// A fading tile's step is negated past its `fade_code`, which the shaders
/// read back as the whole part (they take the step as `fract(abs(w))`).
pub(super) fn instance(origin: [f32; 3], fade: u32) -> [f32; 4] {
let step = 1.0 / crate::mesher::TILED_UV_STEPS;
[
origin[0],
origin[1],
origin[2],
if fade == 0 {
step
} else {
-(fade as f32 + step)
},
]
}
pub(super) struct Visible {
pub key: TileKey,
pub distance: u64,
pub origin: [f32; 3],
pub fade: u32,
/// Replaced, standing until its replacements are whole: its water goes
/// after theirs (`Renderer::render`'s water tiers), so depth leaves it only
/// where they have none yet.
pub old: bool,
}
impl Tile {
/// The mesh drawn this frame: the previous one while it stands in.
pub fn drawn(&self) -> &SectionGpu {
self.previous.as_ref().map_or(&self.mesh, |(mesh, _)| mesh)
}
pub fn drawn_mut(&mut self) -> &mut SectionGpu {
match &mut self.previous {
Some((mesh, _)) => mesh,
None => &mut self.mesh,
}
}
pub fn visible(
&self,
key: TileKey,
camera: DVec3,
frustum: &Frustum,
now: Instant,
) -> Option<Visible> {
let fade = match self.dying {
Some(since) if self.alone => fade_out_code(since, key.level, now),
_ => fade_code(self.shown, key.level, now)?,
};
let origin = DVec3::from(key.origin().map(f64::from)) - camera;
Some(Visible {
key,
distance: self.bounds.visible(origin, frustum)?,
origin: origin.as_vec3().to_array(),
fade,
old: self.dying.is_some() || self.previous.is_some(),
})
}
}
impl Renderer {
/// A tile meshed again (finer detail) takes its place at once, but for
/// one meshed around near chunks or finer tiles that are new (`keep`):
/// its old mesh stands in while they fade in. A new one waits for the rest of its job
/// (`upload_lods`), then fades in.
pub fn upload_lod(&mut self, key: TileKey, mesh: &SectionMesh, keep: bool) {
let (shown, previous) = match self.lods.remove(&key) {
Some(old) if old.dying.is_none() => match old.previous {
Some(previous) => {
self.release_mesh(old.mesh);
(old.shown, Some(previous))
}
None if keep => (old.shown, Some((old.mesh, None))),
None => {
self.release_mesh(old.mesh);
(old.shown, None)
}
},
Some(old) => {
self.release_tile(old);
(None, None)
}
None => (None, None),
};
match Bounds::mesh(mesh).zip(self.upload_mesh(mesh)) {
Some((bounds, mesh)) => {
self.lods.insert(
key,
Tile {
mesh,
bounds,
shown,
dying: None,
alone: false,
previous,
},
);
}
None => {
if let Some((previous, _)) = previous {
self.release_mesh(previous);
}
}
}
}
fn release_tile(&mut self, tile: Tile) {
self.release_mesh(tile.mesh);
if let Some((previous, _)) = tile.previous {
self.release_mesh(previous);
}
}
pub fn remove_lod(&mut self, key: TileKey) {
if let Some(tile) = self.lods.remove(&key) {
self.release_tile(tile);
}
}
pub fn clear_lods(&mut self) {
self.lod_pending = None;
// No far terrain left to fade out over.
for (key, since) in std::mem::take(&mut self.lod_leaving) {
if self
.sections
.find(key)
.is_some_and(|s| s.leaving == Some(since))
{
self.release_section(key);
}
}
for (_, tile) in std::mem::take(&mut self.lods) {
self.release_tile(tile);
}
self.set_lod_cutout(Default::default());
}
/// Queues a finished mesh job (`Lod::update`, `Lod::removed`,
/// `Lod::take_cutout`) for `upload_lods`, joining one still uploading
/// (`Pending::add`).
pub fn queue_lods(
&mut self,
meshes: Vec<(TileKey, SectionMesh)>,
removed: Vec<TileKey>,
cutout: Option<FxHashSet<(i32, i32)>>,
) {
if meshes.is_empty() && removed.is_empty() && cutout.is_none() {
return;
}
self.lod_pending
.get_or_insert_default()
.add(meshes, removed, cutout);
}
/// Uploads queued tile meshes for about `budget` (at least one), then,
/// once all are in, fades them in over the tiles they replace.
pub fn upload_lods(&mut self, budget: Duration) {
let start = Instant::now();
self.release_left(start);
let faded: Vec<_> = self
.lods
.iter()
.filter(|(_, tile)| tile.dying.is_some_and(|d| start - d >= FADE))
.map(|(&key, _)| key)
.collect();
for key in faded {
self.remove_lod(key);
}
let stood_in: Vec<_> = self
.lods
.values_mut()
.filter_map(|tile| match tile.previous {
Some((_, Some(since))) if start - since >= FADE => tile.previous.take(),
_ => None,
})
.collect();
for (previous, _) in stood_in {
self.release_mesh(previous);
}
// The columns near chunks take in this job, and the tiles holding the
// job's new finer ones: a tile meshed again around them keeps its
// old mesh until they are in, so no hole shows through them.
let mut around_new = FxHashSet::default();
let new = self
.lod_pending
.iter()
.flat_map(|pending| pending.meshes.keys())
.filter(|key| !self.lods.contains_key(key))
.chain(
self.lods
.iter()
.filter(|(_, tile)| tile.shown.is_none())
.map(|(key, _)| key),
);
for &key in new {
let mut key = key;
while key.level < MAX_LEVEL && around_new.insert(key.parent()) {
key = key.parent();
}
}
let taken: Vec<_> = self
.lod_pending
.iter()
.flat_map(|pending| pending.cutout.iter().flatten())
.filter(|column| !self.lod_cutout.contains(column))
.copied()
.collect();
while let Some(pending) = &mut self.lod_pending {
let Some(&key) = pending.meshes.keys().next() else {
let pending = self.lod_pending.take().expect("pending tiles");
// A tile fades in over the ones it replaces. One over nothing
// shows whole: its hidden chunks would open holes to the sky
// or the sea bed (dark patches, as far terrain first loads).
let replaced: FxHashSet<TileKey> = pending
.removed
.iter()
.copied()
.filter(|key| self.lods.contains_key(key))
.collect();
let mut above_replaced = FxHashSet::default();
for &key in &replaced {
let mut key = key;
while key.level < MAX_LEVEL && above_replaced.insert(key.parent()) {
key = key.parent();
}
}
let over_replaced = |key: TileKey| {
let mut ancestor = key;
replaced.contains(&key)
|| above_replaced.contains(&key)
|| (key.level..MAX_LEVEL).any(|_| {
ancestor = ancestor.parent();
replaced.contains(&ancestor)
})
};
// A removed tile no new tile overlaps, and no near chunk takes
// a column of, leaves the plan (out of range): it fades out.
// Over near chunks fading in it stays whole: two patterns
// fading at once left holes between them.
// Two tiles overlap when one is the other or its ancestor:
// `kept` holds the new tiles and the near chunks' columns
// (level 0), `above` their ancestors.
let mut kept: FxHashSet<TileKey> = self
.lods
.iter()
.filter(|(_, tile)| tile.shown.is_none())
.map(|(&key, _)| key)
.collect();
let cut = pending.cutout.as_ref().unwrap_or(&self.lod_cutout);
kept.extend(cut.iter().map(|&(x, z)| TileKey { x, z, level: 0 }));
let mut above = FxHashSet::default();
for &key in &kept {
let mut key = key;
while key.level < MAX_LEVEL && above.insert(key.parent()) {
key = key.parent();
}
}
let alone = |key: TileKey| {
let mut ancestor = key;
!kept.contains(&key)
&& !above.contains(&key)
&& !(key.level..MAX_LEVEL).any(|_| {
ancestor = ancestor.parent();
kept.contains(&ancestor)
})
};
let whole = start.checked_sub(FADE).unwrap_or(start);
for (&key, tile) in &mut self.lods {
if tile.shown.is_none() {
tile.shown = Some(if over_replaced(key) { start } else { whole });
}
if let Some((_, since)) = &mut tile.previous {
since.get_or_insert(start);
}
}
for key in pending.removed {
let alone = alone(key);
if let Some(tile) = self.lods.get_mut(&key)
&& tile.dying.is_none()
{
tile.dying = Some(start);
tile.alone = alone;
}
}
if let Some(cutout) = pending.cutout {
self.set_lod_cutout(cutout);
}
return;
};
let mesh = pending.meshes.remove(&key).expect("pending tile");
let [x, _, z] = key.origin();
let size = key.size();
let keep = around_new.contains(&key)
|| taken.iter().any(|&(cx, cz)| {
(x..x + size).contains(&(cx * 16)) && (z..z + size).contains(&(cz * 16))
});
self.upload_lod(key, &mesh, keep);
if start.elapsed() >= budget {
return;
}
}
}
/// The chunk columns the resident tiles now leave out (`Lod::take_cutout`).
/// Removed sections they no longer leave out are released.
pub fn set_lod_cutout(&mut self, cutout: crate::fast_hash::FxHashSet<(i32, i32)>) {
self.lod_cutout = cutout;
let released: Vec<_> = self
.lod_retiring
.iter()
.copied()
.filter(|key| !self.lod_cutout.contains(&(key.0, key.2)))
.collect();
for key in released {
self.lod_retiring.remove(&key);
self.leave_section(key);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mesher::TerrainVertex;
#[test]
fn tiles_fade_in_on_their_own_grid() {
let start = Instant::now();
let at = |ms| start + Duration::from_millis(ms);
// terrain.wgsl's `faded` reads the level and sixty-fourths back.
let decode = |code: u32| ((code - 1) / 129, (code - 1) % 129);
assert_eq!(fade_code(None, 0, at(0)), None, "waits for its job");
assert_eq!(fade_code(Some(start), 3, at(0)).map(decode), Some((3, 1)));
let mut last = 0;
for ms in [0, 100, 300, 500, 590] {
let (level, shown) = decode(fade_code(Some(start), 10, at(ms)).unwrap());
assert_eq!(level, 10);
assert!(shown > last && shown < 64, "{shown} at {ms} ms");
last = shown;
}
assert_eq!(fade_code(Some(start), 10, at(600)), Some(0), "whole");
// Fading out: 65 to 128, then nothing drawn (128) until released.
let mut last = 64;
for ms in [0, 100, 300, 500, 590] {
let (level, out) = decode(fade_out_code(start, 3, at(ms)));
assert_eq!(level, 3);
assert!(out > last && out < 128, "{out} at {ms} ms");
last = out;
}
assert_eq!(decode(fade_out_code(start, 3, at(700))), (3, 128));
// A section's largest code keeps its UV step exact (terrain_uv).
let w = 129.0f32 + 1.0 / 32768.0;
assert_eq!(w.fract(), 1.0 / 32768.0);
}
#[test]
fn joined_jobs_apply_as_if_in_turn() {
let key = |x| TileKey { x, z: 0, level: 0 };
let mut pending = Pending::default();
// The first job meshes 1 and 2 and retires 3 and 4.
pending.add(
vec![
(key(1), SectionMesh::default()),
(key(2), SectionMesh::default()),
],
vec![key(3), key(4)],
Some([(0, 0)].into_iter().collect()),
);
// The second meshes 3 again and retires 2.
pending.add(vec![(key(3), SectionMesh::default())], vec![key(2)], None);
let mut meshes: Vec<_> = pending.meshes.keys().map(|k| k.x).collect();
meshes.sort_unstable();
let mut removed: Vec<_> = pending.removed.iter().map(|k| k.x).collect();
removed.sort_unstable();
assert_eq!((meshes, removed), (vec![1, 3], vec![2, 4]));
assert!(pending.cutout.is_some_and(|c| c.contains(&(0, 0))));
}
#[test]
fn large_tile_bounds_include_water_and_do_not_cull_by_origin() {
let vertex = |pos| TerrainVertex::tiled(pos, [0.0; 2], 0, 0, 0);
let mesh = SectionMesh {
solid: vec![vertex([0.0, -64.0, 0.0]), vertex([1024.0, 100.0, 1024.0])],
translucent: vec![vertex([512.0, 120.0, 512.0])],
..Default::default()
};
let bounds = Bounds::mesh(&mesh).unwrap();
assert_eq!(bounds.min, Vec3::new(0.0, -64.0, 0.0));
assert_eq!(bounds.max, Vec3::new(1024.0, 120.0, 1024.0));
let view = Frustum {
planes: super::super::frustum(
super::super::world_projection(70.0, 16.0 / 9.0, 8192.0)
* crate::camera::view_matrix(0.0, 0.0),
),
};
// The tile origin is far behind, but its far edge reaches the camera.
// Negative world origins therefore remain visible.
assert!(
bounds
.visible(DVec3::new(-1000.0, -80.0, -512.0), &view)
.is_some()
);
// Wholly behind the camera: out of view.
assert!(
bounds
.visible(DVec3::new(-512.0, -80.0, -2000.0), &view)
.is_none()
);
assert!(Bounds::mesh(&SectionMesh::default()).is_none());
}
}
@@ -1,213 +0,0 @@
//! Screenshots of a swapchain that cannot be copied from. OpenGL's surfaces
//! offer `RENDER_ATTACHMENT` only, so a frame whose pixels are read back
//! (the screenshot key, a world's icon) is drawn into a texture that can be,
//! then drawn onto the swapchain image as a fullscreen triangle.
/// The texture a frame to read back is drawn into, and the pass that puts it
/// on the swapchain afterwards.
#[derive(Default)]
pub struct Readback {
texture: Option<wgpu::Texture>,
blitter: Option<(wgpu::TextureFormat, wgpu::util::TextureBlitter)>,
/// A frame drew into `texture` and still has to reach the swapchain.
drawn: bool,
}
impl Readback {
/// The texture this frame draws into instead of the swapchain image
/// `surface`: `None` unless the frame is read back (`screenshot`) and the
/// image cannot be copied from.
pub fn target(
&mut self,
device: &wgpu::Device,
surface: &wgpu::Texture,
screenshot: bool,
) -> Option<wgpu::Texture> {
if !screenshot || surface.usage().contains(wgpu::TextureUsages::COPY_SRC) {
return None;
}
let format = surface.format().remove_srgb_suffix();
if self
.texture
.as_ref()
.is_none_or(|t| t.size() != surface.size() || t.format() != format)
{
self.texture = Some(device.create_texture(&wgpu::TextureDescriptor {
label: Some("Horizon screenshot frame"),
size: surface.size(),
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT
| wgpu::TextureUsages::COPY_SRC
| wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
}));
}
self.drawn = true;
self.texture.clone()
}
/// Draws the frame `target` gave onto the swapchain image `surface`; nothing
/// when this frame drew straight into it.
pub fn present(
&mut self,
device: &wgpu::Device,
encoder: &mut wgpu::CommandEncoder,
surface: &wgpu::Texture,
) {
if !std::mem::take(&mut self.drawn) {
return;
}
let Some(texture) = &self.texture else {
return;
};
// The frame's passes write the swapchain through its non-sRGB view
// (`view_formats`), so the copy goes there unconverted too.
let format = surface.format().remove_srgb_suffix();
if self.blitter.as_ref().is_none_or(|b| b.0 != format) {
self.blitter = Some((format, wgpu::util::TextureBlitter::new(device, format)));
}
let target = surface.create_view(&wgpu::TextureViewDescriptor {
format: Some(format),
..Default::default()
});
let source = texture.create_view(&Default::default());
if let Some((_, blitter)) = &self.blitter {
blitter.copy(device, encoder, &source, &target);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
fn texture(device: &wgpu::Device, usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d {
width: 70,
height: 3,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Bgra8Unorm,
usage,
view_formats: &[],
})
}
fn clear(encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, color: wgpu::Color) {
let view = texture.create_view(&Default::default());
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(color),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
}
fn read(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
buffer.map_async(wgpu::MapMode::Read, .., |r| r.unwrap());
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
buffer.get_mapped_range(..).unwrap().to_vec()
}
/// The last pixel of the last row of a 70x3 frame read back by `copy_frame`.
fn last_pixel(device: &wgpu::Device, buffer: &wgpu::Buffer) -> Vec<u8> {
let pixels = read(device, buffer);
let row = 70usize * 4;
let last = row.next_multiple_of(256) * 2 + row - 4;
pixels[last..last + 4].to_vec()
}
/// The renderer's screenshot path on a surface like OpenGL's (#3510): the
/// frame is drawn into `target`, read back with `copy_frame` and drawn on
/// the swapchain, with no validation error (the copy used to need the
/// swapchain's missing `COPY_SRC`), and the swapchain shows the frame.
#[test]
fn screenshot_of_a_surface_without_copy_src() {
let Some((device, queue)) = device() else {
return;
};
// Sampled only so the test can look at what reached it.
let surface = texture(
&device,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
);
let check = texture(
&device,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
let blitter = wgpu::util::TextureBlitter::new(&device, wgpu::TextureFormat::Bgra8Unorm);
let mut readback = Readback::default();
let colors = [
(1.0, [0, 0, 255, 255]),
// A second screenshot reuses the texture.
(0.0, [255, 0, 0, 255]),
];
for (r, bgra) in colors {
let color = wgpu::Color {
r,
g: 0.0,
b: 1.0 - r,
a: 1.0,
};
let scope = device.push_error_scope(wgpu::ErrorFilter::Validation);
let mut encoder = device.create_command_encoder(&Default::default());
let frame = readback
.target(&device, &surface, true)
.unwrap_or_else(|| surface.clone());
clear(&mut encoder, &frame, color);
let buffer = crate::gfx::copy_frame(&device, &mut encoder, &frame, [70, 3]);
readback.present(&device, &mut encoder, &surface);
queue.submit([encoder.finish()]);
if let Some(error) = pollster::block_on(scope.pop()) {
panic!("{error}");
}
assert_eq!(last_pixel(&device, &buffer), bgra);
let mut encoder = device.create_command_encoder(&Default::default());
let view = |t: &wgpu::Texture| t.create_view(&Default::default());
blitter.copy(&device, &mut encoder, &view(&surface), &view(&check));
let buffer = crate::gfx::copy_frame(&device, &mut encoder, &check, [70, 3]);
queue.submit([encoder.finish()]);
assert_eq!(last_pixel(&device, &buffer), bgra);
}
assert!(!readback.drawn);
}
/// A surface that can be copied from, or a frame nobody reads back,
/// draws straight into the swapchain image.
#[test]
fn frames_draw_straight_to_a_readable_surface() {
let Some((device, _)) = device() else {
return;
};
let mut readback = Readback::default();
let readable = texture(
&device,
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
);
assert!(readback.target(&device, &readable, true).is_none());
let surface = texture(&device, wgpu::TextureUsages::RENDER_ATTACHMENT);
assert!(readback.target(&device, &surface, false).is_none());
assert!(readback.texture.is_none() && !readback.drawn);
}
}
@@ -1,131 +0,0 @@
//! The sunrise/sunset fan (`SkyRenderer.renderSunriseAndSunset`) as the sky
//! shader tests it. The fan's 16 triangles depend only on the sunrise alpha
//! and the horizon the sun is on, so their vertices are built here once a
//! frame instead of in every sky pixel (#3143: with the per-pixel build, four
//! `sin`/`cos` per triangle, the sky pass took 10.2 ms at dawn at 1080p on an
//! Intel UHD 730 against 0.6 ms by day; now 1.8 ms).
//!
//! Möller-Trumbore from the camera reduces to triple products: with apex A
//! and rim vertices r0, r1, a ray d hits at barycentrics proportional to
//! (`[d, r0, r1]`, `[A, d, r1]`, `[A, r0, d]`), each a dot of d with a
//! constant normal, and their sum S is the negated determinant. A hit needs
//! S on the side of `[A, r0, r1]`, so only the triangles whose rim normals'
//! dots change sign there are tested in full.
use glam::Vec3;
pub const TRIANGLES: usize = 16;
/// Per triangle: xyz `r0 × r1` (its dot with a ray is the apex's weight
/// times S), w `[A, r0, r1]` (its sign is S's where the hit lies ahead).
/// Then per rim vertex: xyz `r × A`.
pub fn normals(alpha: f32, sun: Vec3) -> [[f32; 4]; 2 * TRIANGLES] {
let (apex, rim) = vertices(alpha, sun);
let mut out = [[0.0; 4]; 2 * TRIANGLES];
for i in 0..TRIANGLES {
let (r0, r1) = (rim[i], rim[(i + 1) % TRIANGLES]);
out[i] = r0.cross(r1).extend(apex.dot(r0.cross(r1))).to_array();
out[TRIANGLES + i] = r0.cross(apex).extend(0.0).to_array();
}
out
}
/// The fan's apex and rim in camera space, as vanilla builds them: the
/// fan turned to the horizon the sun sets on (or rises from), its rim
/// tilted by the alpha.
fn vertices(alpha: f32, sun: Vec3) -> (Vec3, [Vec3; TRIANGLES]) {
// sin(sunAngle) < 0 flips the fan to the other horizon; sun.z = -sin(sunAngle).
let flip = if -sun.z < 0.0 { 180f32 } else { 0.0 };
let (s, c) = (flip + 90.0).to_radians().sin_cos();
let rotate_x90 = |v: Vec3| Vec3::new(v.x, -v.z, v.y);
let apex = rotate_x90(Vec3::new(-100.0 * s, 100.0 * c, 0.0));
let rim = std::array::from_fn(|i| {
let a = i as f32 * std::f32::consts::TAU / TRIANGLES as f32;
let l = Vec3::new(a.sin() * 120.0, a.cos() * 120.0, -a.cos() * 40.0 * alpha);
rotate_x90(Vec3::new(l.x * c - l.y * s, l.x * s + l.y * c, l.z))
});
(apex, rim)
}
#[cfg(test)]
mod tests {
use super::*;
/// terrain.wgsl's `sunrise_weight` over the normals.
fn weight(normals: &[[f32; 4]; 2 * TRIANGLES], d: Vec3) -> f32 {
let n = |i: usize| Vec3::from_slice(&normals[i][..3]);
let mut best = 0.0f32;
let mut k0 = d.dot(n(TRIANGLES));
for i in 0..TRIANGLES {
let k1 = d.dot(n(TRIANGLES + (i + 1) % TRIANGLES));
let w = normals[i][3];
if k0 * w <= 0.0 && k1 * w >= 0.0 {
let apex = d.dot(n(i));
let s = apex + k1 - k0;
if s.abs() >= 1e-6
&& s * w > 0.0
&& apex * s >= 0.0
&& k1 * s >= 0.0
&& k0 * s <= 0.0
{
best = best.max(apex / s);
}
}
k0 = k1;
}
best
}
/// The shader's former per-pixel Möller-Trumbore over the same vertices.
fn reference(alpha: f32, sun: Vec3, d: Vec3) -> f32 {
let (apex, rim) = vertices(alpha, sun);
let mut best = 0.0f32;
for i in 0..TRIANGLES {
let e1 = rim[i] - apex;
let e2 = rim[(i + 1) % TRIANGLES] - apex;
let pv = d.cross(e2);
let det = e1.dot(pv);
if det.abs() < 1e-6 {
continue;
}
let tv = -apex;
let u = tv.dot(pv) / det;
let qv = tv.cross(e1);
let v = d.dot(qv) / det;
let t = e2.dot(qv) / det;
if u >= 0.0 && v >= 0.0 && u + v <= 1.0 && t > 0.0 {
best = best.max(1.0 - u - v);
}
}
best
}
#[test]
fn normals_weigh_every_ray_as_the_per_pixel_fan_did() {
let mut hits = 0;
for (alpha, sun_z) in [(1.0f32, -0.2f32), (0.6, 0.3), (0.05, -0.9), (0.9, 0.05)] {
let sun = Vec3::new(0.0, (1.0 - sun_z * sun_z).sqrt(), sun_z);
let normals = normals(alpha, sun);
for yaw in 0..180 {
for pitch in -45..=45 {
let (yaw, pitch) = (
(yaw as f32 * 2.0).to_radians(),
(pitch as f32 * 2.0).to_radians(),
);
let d = Vec3::new(
yaw.cos() * pitch.cos(),
pitch.sin(),
yaw.sin() * pitch.cos(),
);
let (got, want) = (weight(&normals, d), reference(alpha, sun, d));
assert!(
(got - want).abs() < 1e-4,
"{alpha} {sun_z} {d}: {got} vs {want}"
);
hits += usize::from(want > 0.0);
}
}
}
// The fan covers part of the sky, not none of it.
assert!(hits > 1000, "{hits}");
}
}
@@ -1,133 +0,0 @@
//! The views a frame is drawn from. A flat screen has one; a headset has
//! one per eye. Every view shares the frame's camera position, so the
//! camera-relative world (section origins, entity offsets) is built once and
//! only each view's rotation and lens differ.
use glam::Mat4;
/// The most views one frame draws.
const MAX_VIEWS: usize = 2;
/// One eye's view of the camera-relative world.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct View {
/// Camera-relative world to eye: a rotation, plus the eye's offset from
/// the camera on a headset.
pub view: Mat4,
/// Reversed-Z perspective: the near plane at depth 1, far at 0.
pub projection: Mat4,
/// Width over height of the image this view fills.
pub aspect: f32,
/// `tan(fov_y / 2)`, for shaders rebuilding view rays from NDC.
pub tan_half_fov: f32,
}
impl View {
/// The flat-screen view: vanilla's camera rotation and a symmetric
/// vertical field of view.
pub fn screen(yaw: f32, pitch: f32, fov_degrees: f32, aspect: f32, far: f32) -> Self {
Self {
view: crate::camera::view_matrix(yaw, pitch),
projection: super::world_projection(fov_degrees, aspect, far),
aspect,
tan_half_fov: (fov_degrees.to_radians() / 2.0).tan(),
}
}
/// Clip space from the camera-relative world, with `pose` (view bobbing,
/// nausea spin) between the lens and the rotation.
pub fn view_proj(&self, pose: Mat4) -> Mat4 {
self.projection * pose * self.view
}
}
/// Every view of a frame, and the one geometry is culled with.
#[derive(Clone, Copy, Debug)]
pub struct ViewSet {
views: [View; MAX_VIEWS],
len: usize,
cull: View,
}
impl ViewSet {
/// A frame drawn from `view` alone, culled with it.
pub fn single(view: View) -> Self {
Self {
views: [view; MAX_VIEWS],
len: 1,
cull: view,
}
}
/// The view the HUD, hand and screen-space effects follow.
pub fn primary(&self) -> &View {
&self.views[0]
}
pub fn views(&self) -> &[View] {
&self.views[..self.len]
}
/// The view whose frustum covers every other view's.
pub fn cull(&self) -> &View {
&self.cull
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The formulas `Renderer` used before views existed, kept to pin the
/// screen view to them bit for bit.
fn legacy_view_proj(fov: f32, yaw: f32, pitch: f32, pose: Mat4, aspect: f32, far: f32) -> Mat4 {
super::super::world_projection(fov, aspect, far)
* pose
* crate::camera::view_matrix(yaw, pitch)
}
fn poses() -> [Mat4; 3] {
[
Mat4::IDENTITY,
Mat4::from_translation(glam::Vec3::new(0.013, -0.027, 0.0))
* Mat4::from_rotation_z(0.021),
Mat4::from_rotation_y(0.4) * Mat4::from_scale(glam::Vec3::new(1.1, 0.9, 1.0)),
]
}
#[test]
fn the_screen_view_matches_the_legacy_projection_bit_for_bit() {
for (fov, yaw, pitch, aspect, far) in [
(70.0, 0.0, 0.0, 16.0 / 9.0, 512.0),
(110.0, -137.25, 61.5, 21.0 / 9.0, 8192.0),
(30.0, 359.9, -90.0, 4.0 / 3.0, 96.0),
(82.333, 12.5, 7.75, 1.0, 1024.0),
] {
let view = View::screen(yaw, pitch, fov, aspect, far);
for pose in poses() {
let old = legacy_view_proj(fov, yaw, pitch, pose, aspect, far);
let new = view.view_proj(pose);
assert_eq!(
old.to_cols_array().map(f32::to_bits),
new.to_cols_array().map(f32::to_bits),
"fov {fov} yaw {yaw} pitch {pitch}"
);
}
assert_eq!(view.view, crate::camera::view_matrix(yaw, pitch));
assert_eq!(
view.tan_half_fov.to_bits(),
(fov.to_radians() / 2.0).tan().to_bits()
);
assert_eq!(view.aspect.to_bits(), aspect.to_bits());
}
}
#[test]
fn a_single_view_set_draws_and_culls_with_its_view() {
let view = View::screen(45.0, 10.0, 70.0, 16.0 / 9.0, 512.0);
let set = ViewSet::single(view);
assert_eq!(set.views(), &[view]);
assert_eq!(*set.primary(), view);
assert_eq!(*set.cull(), view);
}
}
@@ -1,564 +0,0 @@
//! Resolution scale, FXAA and TAA (Horizon settings): the world renders into its
//! own target at the scaled size, then one full-screen pass copies or
//! anti-aliases it onto the screen, under the hand and HUD. With none on,
//! the world renders straight to the screen.
//!
//! TAA jitters the world's projection by a sub-pixel offset each frame and blends
//! the frame into a history reprojected through the depth buffer: its motion
//! vectors are the camera's, so what moves on its own leans on the neighbourhood
//! clamp alone.
use glam::{DMat4, DVec3, Mat4, Vec2};
/// The TAA history format: 8 bits would band as frames accumulate.
const HISTORY_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
struct WorldTarget {
size: [u32; 2],
color: wgpu::TextureView,
depth: wgpu::TextureView,
group: wgpu::BindGroup,
taa: Option<History>,
}
/// TAA's two history textures at the output size (the world's, times the upscale), written
/// in turn: `resolve[i]` writes `history[i]` from the world and `history[1 - i]`; `show[i]`
/// copies `history[i]` to the screen.
struct History {
size: [u32; 2],
history: [wgpu::TextureView; 2],
resolve: [wgpu::BindGroup; 2],
show: [wgpu::BindGroup; 2],
}
/// `world_post.wgsl`'s `Taa`.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct TaaUniform {
/// This frame's unjittered clip space to the previous frame's.
reproject: [[f32; 4]; 4],
/// xy: this frame's jitter in clip space; z: 1 when the history is unusable.
jitter: [f32; 4],
}
/// TAA's GPU resources, absent when the device cannot compile the shader
/// (the OpenGL backend's naga GLSL emitter does not support `textureLoad`
/// from depth textures).
struct TaaResources {
layout: wgpu::BindGroupLayout,
pipeline: wgpu::RenderPipeline,
uniform: wgpu::Buffer,
}
pub struct Post {
layout: wgpu::BindGroupLayout,
sampler: wgpu::Sampler,
copy: wgpu::RenderPipeline,
fxaa: wgpu::RenderPipeline,
format: wgpu::TextureFormat,
/// World resolution relative to the window (0.5..=2.0).
pub scale: f32,
pub antialias: bool,
pub taa: bool,
/// Output pixels per rendered pixel while TAA is on (1: native): the world renders
/// this much smaller and TAA rebuilds it at the resolution scale's size.
pub upscale: f32,
/// TAA runs this frame (`jitter`): not on the title screen or under a shader pack.
taa_on: bool,
target: Option<WorldTarget>,
taa_resources: Option<TaaResources>,
/// Frames jittered so far (the Halton index), and which history the next resolve writes.
taa_frame: u32,
/// The last TAA frame's unjittered `view_proj` and camera, `None` once a frame ran without it.
taa_previous: Option<(DMat4, DVec3)>,
taa_this_frame: TaaUniform,
}
impl Post {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self {
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Horizon post"),
source: wgpu::ShaderSource::Wgsl(include_str!("../world_post.wgsl").into()),
});
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon post bindings"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let texture = |binding, sample_type| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Texture {
sample_type,
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
};
let float = wgpu::TextureSampleType::Float { filterable: true };
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon post"),
bind_group_layouts: &[Some(&layout)],
..Default::default()
});
let pipeline = |entry: &str, layout: &wgpu::PipelineLayout, format| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon post"),
layout: Some(layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_post"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
// The OpenGL backend's GLSL translator does not support textureLoad
// from depth textures: on devices running through OpenGL (such as older
// Intel GPUs on Linux), TAA cannot compile its pipeline.
let taa_resources = {
let taa_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("Horizon TAA bindings"),
entries: &[
texture(0, float),
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
texture(2, float),
texture(3, wgpu::TextureSampleType::Depth),
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: wgpu::ShaderStages::FRAGMENT,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let taa_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("Horizon TAA"),
bind_group_layouts: &[Some(&taa_layout)],
..Default::default()
});
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
let internal = device.push_error_scope(wgpu::ErrorFilter::Internal);
let taa_pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Horizon TAA"),
layout: Some(&taa_pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some("vs_post"),
compilation_options: Default::default(),
buffers: &[],
},
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some("fs_taa"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: HISTORY_FORMAT,
blend: None,
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let internal = pollster::block_on(internal.pop());
match internal.or(pollster::block_on(validation.pop())) {
None => {
let uniform = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("Horizon TAA"),
size: std::mem::size_of::<TaaUniform>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
Some(TaaResources {
layout: taa_layout,
pipeline: taa_pipeline,
uniform,
})
}
Some(e) => {
log::warn!("Horizon renderer: temporal anti-aliasing unavailable ({e})");
None
}
}
};
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("Horizon post"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
Self {
copy: pipeline("fs_copy", &pipeline_layout, format),
fxaa: pipeline("fs_fxaa", &pipeline_layout, format),
layout,
sampler,
format,
scale: 1.0,
antialias: false,
taa: false,
upscale: 1.0,
taa_on: false,
target: None,
taa_resources,
taa_frame: 0,
taa_previous: None,
taa_this_frame: bytemuck::Zeroable::zeroed(),
}
}
/// Whether TAA is supported on this GPU/backend.
pub fn supports_taa(&self) -> bool {
self.taa_resources.is_some()
}
/// The world's rendered size and the size it is shown at (TAA's history).
fn sizes(&self, window: [u32; 2]) -> ([u32; 2], [u32; 2]) {
let output = window.map(|v| ((v as f32 * self.scale).round() as u32).clamp(1, 8192));
let upscale = if self.taa_on { self.upscale } else { 1.0 };
(
output.map(|v| ((v as f32 / upscale).round() as u32).max(1)),
output,
)
}
/// TAA's sub-pixel jitter this frame, as a clip-space matrix to multiply into the
/// world's projection (identity while `on` is false); `view_proj` is the unjittered
/// projection, relative to `camera`. Call it before `prepare`, once per frame.
pub fn jitter(&mut self, window: [u32; 2], on: bool, view_proj: Mat4, camera: DVec3) -> Mat4 {
self.taa_on = on && self.taa && self.taa_resources.is_some();
if !self.taa_on {
self.taa_previous = None;
return Mat4::IDENTITY;
}
self.taa_frame = self.taa_frame.wrapping_add(1);
let (size, _) = self.sizes(window);
// Halton (2, 3) over 8 frames per output pixel (FSR's count), in rendered
// pixels around the centre.
let phases = (8.0 * self.upscale * self.upscale).ceil() as u32;
let i = self.taa_frame % phases + 1;
let offset = Vec2::new(halton(i, 2), halton(i, 3)) - 0.5;
let jitter = offset * 2.0 / Vec2::new(size[0] as f32, size[1] as f32);
let current = view_proj.as_dmat4();
let (reproject, reset) = match self.taa_previous {
Some((previous, previous_camera)) => (
reprojection(previous, previous_camera, current, camera),
0.0,
),
None => (DMat4::IDENTITY, 1.0),
};
self.taa_previous = Some((current, camera));
self.taa_this_frame = TaaUniform {
reproject: reproject.as_mat4().to_cols_array_2d(),
jitter: [jitter.x, jitter.y, reset, 0.0],
};
Mat4::from_translation(jitter.extend(0.0))
}
/// The world's colour and depth targets this frame, or `None` to draw
/// it straight to the screen.
/// `always`: a target even at scale 1 without anti-aliasing (a shader pack reads it).
pub fn prepare(
&mut self,
device: &wgpu::Device,
window: [u32; 2],
always: bool,
) -> Option<(wgpu::TextureView, wgpu::TextureView)> {
if self.scale == 1.0 && !self.antialias && !self.taa_on && !always {
self.target = None;
return None;
}
let (size, output) = self.sizes(window);
let history_size = self.taa_on.then_some(output);
if self
.target
.as_ref()
.is_none_or(|t| t.size != size || t.taa.as_ref().map(|h| h.size) != history_size)
{
let make_tex = |label, size: [u32; 2], format, usage| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d {
width: size[0],
height: size[1],
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
};
let sampled =
wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING;
let color = make_tex("Scaled world", size, self.format, sampled)
.create_view(&Default::default());
// TEXTURE_BINDING: occlusion culling and TAA read it.
let depth = make_tex(
"Scaled world depth",
size,
wgpu::TextureFormat::Depth32Float,
sampled,
)
.create_view(&Default::default());
let group = self.bind(device, &color);
let taa = history_size.and_then(|output| {
let res = self.taa_resources.as_ref()?;
let history = [0, 1].map(|_| {
make_tex("TAA history", output, HISTORY_FORMAT, sampled)
.create_view(&Default::default())
});
let resolve = [0, 1].map(|i| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon TAA"),
layout: &res.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&color),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
wgpu::BindGroupEntry {
binding: 2,
resource: wgpu::BindingResource::TextureView(&history[1 - i]),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::TextureView(&depth),
},
wgpu::BindGroupEntry {
binding: 4,
resource: res.uniform.as_entire_binding(),
},
],
})
});
let show = [0, 1].map(|i| self.bind(device, &history[i]));
Some(History {
size: output,
history,
resolve,
show,
})
});
// New textures: no history yet.
self.taa_this_frame.jitter[2] = 1.0;
self.target = Some(WorldTarget {
size,
color,
depth,
group,
taa,
});
}
self.target
.as_ref()
.map(|t| (t.color.clone(), t.depth.clone()))
}
/// The size of the world's own target, when it has one.
pub fn size(&self) -> Option<[u32; 2]> {
self.target.as_ref().map(|t| t.size)
}
/// Bindings that copy (or anti-alias) `view` onto the screen in `finish_with`.
pub fn bind(&self, device: &wgpu::Device, view: &wgpu::TextureView) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("Horizon post"),
layout: &self.layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(view),
},
wgpu::BindGroupEntry {
binding: 1,
resource: wgpu::BindingResource::Sampler(&self.sampler),
},
],
})
}
/// Draw the scaled world onto `screen`, through TAA when this frame's `jitter` had it on.
pub fn finish(
&self,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
screen: &wgpu::TextureView,
) {
let Some(target) = &self.target else { return };
let Some(taa) = target.taa.as_ref().filter(|_| self.taa_previous.is_some()) else {
self.finish_with(encoder, screen, &target.group);
return;
};
let Some(res) = &self.taa_resources else {
self.finish_with(encoder, screen, &target.group);
return;
};
let i = (self.taa_frame % 2) as usize;
queue.write_buffer(&res.uniform, 0, bytemuck::bytes_of(&self.taa_this_frame));
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: &taa.history[i],
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon TAA"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(&res.pipeline);
pass.set_bind_group(0, &taa.resolve[i], &[]);
pass.draw(0..3, 0..1);
drop(pass);
self.finish_with(encoder, screen, &taa.show[i]);
}
/// Draw what `group` binds (`bind`) onto `screen`.
pub fn finish_with(
&self,
encoder: &mut wgpu::CommandEncoder,
screen: &wgpu::TextureView,
group: &wgpu::BindGroup,
) {
let attachments = [Some(wgpu::RenderPassColorAttachment {
view: screen,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::BLACK),
store: wgpu::StoreOp::Store,
},
})];
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Horizon post"),
color_attachments: &attachments,
..Default::default()
});
pass.set_pipeline(if self.antialias {
&self.fxaa
} else {
&self.copy
});
pass.set_bind_group(0, group, &[]);
pass.draw(0..3, 0..1);
}
}
/// This frame's clip space to the previous frame's, for camera-relative projections:
/// a point `camera - previous_camera` further from the previous camera than from this one.
fn reprojection(previous: DMat4, previous_camera: DVec3, current: DMat4, camera: DVec3) -> DMat4 {
previous * DMat4::from_translation(camera - previous_camera) * current.inverse()
}
/// The radical inverse of `i` in `base`: a low-discrepancy sequence in 0..1.
fn halton(mut i: u32, base: u32) -> f32 {
let (mut f, mut r) = (1.0, 0.0);
while i > 0 {
f /= base as f32;
r += f * (i % base) as f32;
i /= base;
}
r
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reprojection_finds_where_a_block_was_last_frame() {
let projection = DMat4::perspective_rh(1.2, 16.0 / 9.0, 1024.0, 0.05);
let previous = projection * DMat4::from_rotation_y(0.3);
let current = projection * DMat4::from_rotation_y(0.35);
let (previous_camera, camera) = (DVec3::new(10.0, 64.0, 5.0), DVec3::new(10.5, 64.2, 4.0));
let block = DVec3::new(14.0, 66.0, -8.0);
let clip = |m: DMat4, eye: DVec3| m * (block - eye).extend(1.0);
let now = clip(current, camera);
let then = reprojection(previous, previous_camera, current, camera) * (now / now.w);
let expected = clip(previous, previous_camera);
assert!((then.truncate() / then.w - expected.truncate() / expected.w).length() < 1e-9);
}
#[test]
fn jitter_stays_inside_the_pixel() {
for i in 1..=8 {
let (x, y) = (halton(i, 2), halton(i, 3));
assert!((0.0..1.0).contains(&x) && (0.0..1.0).contains(&y));
}
assert_eq!(
[halton(1, 2), halton(2, 2), halton(3, 2)],
[0.5, 0.25, 0.75]
);
}
fn test_device() -> Option<(wgpu::Device, wgpu::Queue)> {
let instance =
wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle().with_env());
let adapter = pollster::block_on(instance.request_adapter(&Default::default())).ok()?;
pollster::block_on(adapter.request_device(&Default::default())).ok()
}
#[test]
fn world_post_pipelines_compile_or_fall_back() {
let Some((device, _)) = test_device() else {
return;
};
let post = Post::new(&device, wgpu::TextureFormat::Rgba8Unorm);
// Copy and FXAA pipelines always compile; TAA compiles if supported by backend.
let _ = post.supports_taa();
}
}
-147
View File
@@ -1,147 +0,0 @@
// Horizon's HDR output pass: the frame, drawn as without HDR in vanilla's gamma
// space, decoded to linear light at the paper white and written to the swapchain:
// HDR10 (BT.2020, PQ) or scRGB (1.0 = 80 nits). Bright pixels of light sources that still show the
// world as it was before the hand and HUD are expanded towards the peak.
@group(0) @binding(0) var frame: texture_2d<f32>;
@group(0) @binding(1) var world: texture_2d<f32>;
struct Params {
// Paper white in scRGB units (nits / 80).
paper: f32,
// Peak brightness relative to paper white; 1 expands nothing.
peak: f32,
// 1 when this frame drew a world.
world: f32,
// 1 greys what isn't expanded and tints what is (HORIZON_HDR_DEBUG=1).
debug: f32,
// 1 for an HDR10 swapchain, 0 for scRGB.
pq: f32,
// The display's black level in nits; 0 leaves the picture as it is.
black: f32,
// The HUD and menus' brightness as a share of paper white.
ui: f32,
// Per tier, low to very bright (hdr.rs `Tier`): the share of the headroom
// the brightest pixels get, and the brightness where the lift starts and
// where it is full.
share: vec4<f32>,
start: vec4<f32>,
full: vec4<f32>,
};
@group(0) @binding(2) var<uniform> params: Params;
// Light sources are lifted evenly rather than by a highlight curve: vanilla's
// textures were drawn for SDR, so a curve on their brightest pixels blows out
// near-white spots (glowstone) and leaves the rest (lava, a jack o'lantern's
// face) nearly as it was. Each tier's pixels brighter than its `full` get its
// `share` of the headroom, dimmer ones less down to none at its `start`
// (lava's crust, a lantern's metal), and no channel goes past the peak.
// Brightness is the mean of luminance and the brightest channel, so saturated
// light counts as bright.
// Whether `c` still shows the world pixel `w`: the same, or darkened evenly
// across its channels, as the vignette and other screen-wide tints darken it.
// The hand, HUD and text replace pixels instead, so they never pass. The
// channels are held to one factor, the ratio of their sums, so a channel at 0
// stays 0; a step of 8-bit rounding is allowed on each.
fn shows_world(c: vec3<f32>, w: vec3<f32>) -> bool {
if all(c == w) {
return true;
}
let f = (c.r + c.g + c.b) / max(w.r + w.g + w.b, 1.0 / 255.0);
return f <= 1.01 && f > 0.5 && all(abs(c - f * w) <= 0.03 * w + 1.0 / 255.0);
}
// Linear BT.709 to BT.2020 (ITU-R BT.2087), columns first.
const BT709_TO_BT2020 = mat3x3<f32>(
vec3(0.6274, 0.0691, 0.0164),
vec3(0.3293, 0.9195, 0.0880),
vec3(0.0433, 0.0114, 0.8956),
);
// SMPTE ST 2084: nits (up to 10000) to the PQ signal.
fn pq(nits: vec3<f32>) -> vec3<f32> {
let y = pow(clamp(nits / 10000.0, vec3(0.0), vec3(1.0)), vec3(0.1593017578125));
return pow((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), vec3(78.84375));
}
// ST 2084's inverse: the PQ signal to nits.
fn pq_nits(e: vec3<f32>) -> vec3<f32> {
let p = pow(clamp(e, vec3(0.0), vec3(1.0)), vec3(1.0 / 78.84375));
let y = max(p - 0.8359375, vec3(0.0)) / (18.8515625 - 18.6875 * p);
return 10000.0 * pow(y, vec3(1.0 / 0.1593017578125));
}
// ITU-R BT.2390's black level lift (its EETF without the knee) on the PQ signal
// `e`: black moves up to the display's black level, the peak stays, and the lift
// fades out by the fourth power on the way up, so only the shadows move. A display
// that can't go darker than its black level would crush everything below it.
fn lift_black(e: vec3<f32>) -> vec3<f32> {
let top = pq(vec3(params.peak * params.paper * 80.0)).x;
let n = min(e / top, vec3(1.0));
return e + pq(vec3(params.black)).x * pow(vec3(1.0) - n, vec3(4.0));
}
@vertex fn vs_hdr(@builtin(vertex_index) i: u32) -> @builtin(position) vec4<f32> {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
// Hdr::keep_world: once the world is kept, the frame's alpha starts at 0 again.
@fragment fn fs_clear_alpha() -> @location(0) vec4<f32> {
return vec4(0.0);
}
@fragment fn fs_hdr(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let at = vec2<i32>(pos.xy);
let f = textureLoad(frame, at, 0);
let c = f.rgb;
// What covers the world here (Hdr::keep_world): nothing at 0, the hand at
// 1/255 (Hdr::mark_hand: drawn at the world's brightness), else the HUD or a
// menu, by how much.
let covered = f.a > 0.0;
let ui = select(f.a, 0.0, f.a < 1.5 / 255.0);
// Gamma 2.2, as SDR displays and the compositors' SDR paths decode it.
var light = pow(max(c, vec3(0.0)), vec3(2.2));
let w = textureLoad(world, at, 0);
// The world's alpha is below 0.75 on light sources, the sun and the moon
// (terrain.wgsl, the celestial pipeline): only those shine, by the tier it
// holds, the lower the brighter, and only where nothing was drawn over them
// since: grey text over the white sun still looks like the sun darkened, but
// it raised the frame's alpha.
var lifted = false;
if params.world > 0.5 && params.peak > 1.0 && w.a < 0.75 && !covered
&& shows_world(c, w.rgb) {
// Brightness of the world pixel, before the vignette darkens the frame
// toward its edges: a light source shines the same anywhere on screen.
let wl = pow(max(w.rgb, vec3(0.0)), vec3(2.2));
let y = 0.5 * (dot(wl, vec3(0.2126, 0.7152, 0.0722)) + max(wl.r, max(wl.g, wl.b)));
let tier = u32(clamp(round(4.0 - 4.0 * w.a / 0.7), 1.0, 4.0)) - 1u;
let lift = smoothstep(params.start[tier], params.full[tier], y);
if lift > 0.0 {
let top = max(light.r, max(light.g, light.b));
let gain = min(1.0 + (params.peak - 1.0) * params.share[tier] * lift, params.peak / max(top, 1e-4));
light *= max(gain, 1.0);
lifted = true;
}
}
// HORIZON_HDR_DEBUG=1: what isn't lifted turns grey, what is keeps its
// colour with a magenta tint, so a lift shows on any colour.
if params.debug > 0.5 && params.world > 0.5 {
if lifted {
light *= vec3(1.0, 0.6, 1.0);
} else {
light = vec3(dot(light, vec3(0.2126, 0.7152, 0.0722)));
}
}
// The HUD and menus at their own brightness, by how much they cover.
light *= mix(1.0, params.ui, ui);
let scrgb = light * params.paper;
if params.pq > 0.5 {
let e = pq(BT709_TO_BT2020 * scrgb * 80.0);
return vec4(select(e, lift_black(e), params.black > 0.0), 1.0);
}
if params.black > 0.0 {
return vec4(pq_nits(lift_black(pq(scrgb * 80.0))) / 80.0, 1.0);
}
return vec4(scrgb, 1.0);
}
@@ -1,153 +0,0 @@
//! `JigsawBlockEntity`: the jigsaw block's name, target, pool, joint, final
//! state and priorities, with its save format (`saveAdditional` /
//! `loadAdditional`).
use crate::structure_block::parse_identifier;
use horizon_client_core::nbt_value::{number, string, text};
use horizon_world::nbt::Tag;
/// `JigsawBlockEntity.EMPTY_ID` and `Pools.EMPTY`.
pub const EMPTY_ID: &str = "minecraft:empty";
/// `JigsawBlockEntity.JointType`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum JointType {
Rollable,
Aligned,
}
impl JointType {
pub const ALL: [Self; 2] = [Self::Rollable, Self::Aligned];
pub fn serialized_name(self) -> &'static str {
match self {
Self::Rollable => "rollable",
Self::Aligned => "aligned",
}
}
pub fn of_serialized_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|j| j.serialized_name() == name)
}
/// `JointType.getTranslatedName`'s lang key.
pub fn label_key(self) -> String {
format!("jigsaw_block.joint.{}", self.serialized_name())
}
/// `StructureTemplate.getDefaultJointType`: the joint of a block whose
/// front faces `front` (the first word of its `orientation` value).
pub fn default_for_front(front: &str) -> Self {
if is_vertical_front(front) {
Self::Rollable
} else {
Self::Aligned
}
}
}
/// `JigsawBlock.getFrontFacing(state)` from the `orientation` value
/// (`down_east`, `north_up`...): its front is the part before the `_`.
pub fn front_of_orientation(orientation: &str) -> &str {
orientation.split('_').next().unwrap_or(orientation)
}
pub fn is_vertical_front(front: &str) -> bool {
matches!(front, "up" | "down")
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct JigsawBlock {
pub name: String,
pub target: String,
pub pool: String,
pub joint: JointType,
pub final_state: String,
pub placement_priority: i32,
pub selection_priority: i32,
}
impl Default for JigsawBlock {
fn default() -> Self {
Self {
name: EMPTY_ID.into(),
target: EMPTY_ID.into(),
pool: EMPTY_ID.into(),
joint: JointType::Rollable,
final_state: "minecraft:air".into(),
placement_priority: 0,
selection_priority: 0,
}
}
}
impl JigsawBlock {
/// `saveAdditional` (also `getUpdateTag`, which is `saveCustomOnly`).
pub fn save(&self) -> Vec<(&'static str, Tag)> {
vec![
("name", string(&self.name)),
("target", string(&self.target)),
("pool", string(&self.pool)),
("final_state", string(&self.final_state)),
("joint", string(self.joint.serialized_name())),
("placement_priority", Tag::Int(self.placement_priority)),
("selection_priority", Tag::Int(self.selection_priority)),
]
}
/// `loadAdditional`. A missing joint takes `default_joint`
/// (`StructureTemplate.getDefaultJointType` of the block's state).
pub fn load(tag: &Tag, default_joint: JointType) -> Self {
let id = |key: &str| {
text(tag.get(key))
.and_then(|s| parse_identifier(&s))
.unwrap_or_else(|| EMPTY_ID.into())
};
Self {
name: id("name"),
target: id("target"),
pool: id("pool"),
final_state: text(tag.get("final_state")).unwrap_or_else(|| "minecraft:air".into()),
joint: text(tag.get("joint"))
.and_then(|j| JointType::of_serialized_name(&j))
.unwrap_or(default_joint),
placement_priority: number(tag.get("placement_priority")).unwrap_or(0) as i32,
selection_priority: number(tag.get("selection_priority")).unwrap_or(0) as i32,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saves_and_loads_like_jigsaw_block_entity() {
let block = JigsawBlock {
name: "minecraft:bottom".into(),
target: "test:top".into(),
pool: "minecraft:village/plains/houses".into(),
joint: JointType::Aligned,
final_state: "minecraft:stone[x=1]".into(),
placement_priority: 4,
selection_priority: -1,
};
let tag = Tag::compound(block.save());
assert_eq!(text(tag.get("joint")).as_deref(), Some("aligned"));
assert_eq!(JigsawBlock::load(&tag, JointType::Rollable), block);
}
#[test]
fn load_defaults_like_vanilla() {
let tag = Tag::compound(vec![
("name", string("Bad Name")),
("target", string("door")),
]);
let block = JigsawBlock::load(&tag, JointType::Aligned);
assert_eq!(block.name, EMPTY_ID);
assert_eq!(block.target, "minecraft:door");
assert_eq!(block.pool, EMPTY_ID);
assert_eq!(block.final_state, "minecraft:air");
assert_eq!(block.joint, JointType::Aligned);
assert_eq!(JointType::default_for_front("up"), JointType::Rollable);
assert_eq!(
JointType::default_for_front(front_of_orientation("north_up")),
JointType::Aligned
);
}
}
@@ -1,707 +0,0 @@
//! LevelLoadingScreen: "Loading terrain..." over the chunk status map and
//! the server's load progress while a world opens or a portal is crossed.
use crate::{
hud::{HudAtlas, HudBatch},
text::Text,
};
/// `Minecraft.doWorldLoad`: `max(5, 3) + ChunkLevel.RADIUS_AROUND_FULL_CHUNK + 1`.
pub const STATUS_RADIUS: i32 = 8;
/// `LevelLoadProgressTracker.EXPECTED_PLAYER_CHUNKS`: the 7x7 chunks
/// `PrepareSpawnTask` waits for around the player.
const PLAYER_CHUNKS: usize = 49;
/// `LevelLoadProgressTracker.PREPARE_SERVER_WEIGHT`.
const PREPARE_WEIGHT: usize = 10;
/// `ChunkStatus`, as far as the chunk status map tells them apart.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Empty,
StructureStarts,
StructureReferences,
Biomes,
Terrain,
Features,
InitializeLight,
Light,
Spawn,
Full,
}
impl Status {
/// `LevelLoadingScreen.COLORS` (RGB).
pub fn color(self) -> u32 {
match self {
Self::Empty => 0x545454,
Self::StructureStarts => 0x999999,
Self::StructureReferences => 0x5F6191,
Self::Biomes => 0x80B252,
Self::Terrain => 0x303572,
Self::Features => 0x21C600,
Self::InitializeLight => 0xCCCCCC,
Self::Light => 0xFFE0A0,
Self::Spawn => 0xF26060,
Self::Full => 0xFFFFFF,
}
}
}
/// `LevelLoadingScreen.Reason`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
NetherPortal,
EndPortal,
Other,
}
/// `LevelLoadTracker.CLIENT_WAIT_TIMEOUT_MS`.
pub const CLIENT_WAIT_TIMEOUT_MS: u64 = 30_000;
/// `LevelLoadTracker.LEVEL_LOAD_CLOSE_DELAY_MS`: how long a new world's loading
/// screen stays once the level is ready.
pub const LEVEL_LOAD_CLOSE_DELAY_MS: u64 = 500;
/// `ClientPacketListener.determineLevelLoadingReason`.
pub fn reason_for_respawn(player_died: bool, dimension: &str, old_dimension: &str) -> Reason {
const NETHER: &str = "minecraft:the_nether";
const END: &str = "minecraft:the_end";
if player_died {
Reason::Other
} else if dimension == NETHER || old_dimension == NETHER {
Reason::NetherPortal
} else if dimension == END || old_dimension == END {
Reason::EndPortal
} else {
Reason::Other
}
}
/// `LevelLoadTracker.ClientState`, with the times in milliseconds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum ClientState {
/// `WaitingForServer`: until the loading start game event.
WaitingForServer { timeout_after: u64 },
/// `WaitingForPlayerChunk`: until the section around the player is shown.
WaitingForPlayerChunk {
player_section_ready: bool,
timeout_after: u64,
},
/// `ClientLevelReady`.
Ready { ready_at: u64 },
}
/// What `WaitingForPlayerChunk.isReady` asks of the player.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PlayerCheck {
/// `ClientLevel.isOutsideBuildHeight(camera y)`.
pub outside_build_height: bool,
pub spectator: bool,
pub alive: bool,
}
/// The client half of `LevelLoadTracker`: what the loading screen waits for
/// after a login or a respawn, and the screen it is shown on.
#[derive(Clone, Copy, Debug)]
pub struct LevelLoadTracker {
state: Option<ClientState>,
close_delay_ms: u64,
/// `LevelLoadingScreen.reason`.
pub reason: Reason,
}
impl LevelLoadTracker {
pub fn new(close_delay_ms: u64) -> Self {
Self {
state: None,
close_delay_ms,
reason: Reason::Other,
}
}
/// `startClientLoad`, for the screen `reason` (`startWaitingForNewLevel`).
pub fn start_client_load(&mut self, now: u64, reason: Reason) {
self.state = Some(ClientState::WaitingForServer {
timeout_after: now + CLIENT_WAIT_TIMEOUT_MS,
});
self.reason = reason;
}
/// The tracker's work is over and the screen has closed
/// (`ClientPacketListener.tick` drops it once the level is ready).
pub fn finish(&mut self) {
self.state = None;
}
/// A load is under way, so its screen is up.
pub fn is_active(&self) -> bool {
self.state.is_some()
}
/// `loadingPacketsReceived`: `LEVEL_CHUNKS_LOAD_START` came.
pub fn loading_packets_received(&mut self) {
if let Some(ClientState::WaitingForServer { timeout_after }) = self.state {
self.state = Some(ClientState::WaitingForPlayerChunk {
player_section_ready: false,
timeout_after,
});
}
}
/// `getPlayerCompiledSectionCallback` is not null: the renderer is to say
/// when the player's section is shown.
pub fn wants_player_section(&self) -> bool {
matches!(self.state, Some(ClientState::WaitingForPlayerChunk { .. }))
}
/// The callback: the player's section is compiled and visible.
pub fn player_section_ready(&mut self) {
if let Some(ClientState::WaitingForPlayerChunk {
player_section_ready,
..
}) = &mut self.state
{
*player_section_ready = true;
}
}
/// `tickClientLoad`.
pub fn tick_client_load(&mut self, now: u64, player: PlayerCheck) {
if let Some(ClientState::WaitingForPlayerChunk {
player_section_ready,
timeout_after,
}) = self.state
{
let ready = if now > timeout_after {
log::warn!(
"Timed out while waiting for the client to load chunks, letting the player into the world anyway"
);
true
} else if !player.outside_build_height && !player.spectator && player.alive {
player_section_ready
} else {
true
};
if ready {
self.state = Some(ClientState::Ready { ready_at: now });
}
}
}
/// `isLevelReady`.
pub fn is_level_ready(&self, now: u64) -> bool {
matches!(self.state, Some(ClientState::Ready { ready_at }) if now >= ready_at + self.close_delay_ms)
}
}
/// `LevelLoadListener.Stage`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Stage {
StartServer,
PrepareGlobalSpawn,
LoadInitialChunks,
LoadPlayerChunks,
}
/// `LevelLoadProgressTracker` (with `includePlayerChunks`).
#[derive(Debug, Default)]
struct ProgressTracker {
total_weight: usize,
finalized_weight: usize,
segment_weight: usize,
segment_fraction: f32,
progress: f32,
}
impl ProgressTracker {
fn tracks(stage: Stage) -> bool {
matches!(stage, Stage::LoadInitialChunks | Stage::LoadPlayerChunks)
}
fn begin_segment(&mut self, weight: usize) {
self.segment_weight = weight;
self.segment_fraction = 0.0;
self.update_progress();
}
fn finish_segment(&mut self) {
self.finalized_weight += self.segment_weight;
self.segment_weight = 0;
self.update_progress();
}
fn update_progress(&mut self) {
self.progress = if self.total_weight == 0 {
0.0
} else {
(self.finalized_weight as f32 + self.segment_fraction * self.segment_weight as f32)
/ self.total_weight as f32
};
}
fn start(&mut self, stage: Stage, total_chunks: usize) {
match stage {
Stage::LoadInitialChunks => {
self.total_weight = PREPARE_WEIGHT + total_chunks + PLAYER_CHUNKS;
self.begin_segment(PREPARE_WEIGHT);
self.finish_segment();
self.begin_segment(total_chunks);
}
Stage::LoadPlayerChunks => self.begin_segment(PLAYER_CHUNKS),
_ => {}
}
}
fn update(&mut self, stage: Stage, current: usize, total: usize) {
if Self::tracks(stage) {
self.segment_fraction = if total == 0 {
0.0
} else {
current as f32 / total as f32
};
self.update_progress();
}
}
fn finish(&mut self, stage: Stage) {
if Self::tracks(stage) {
self.finish_segment();
}
}
}
/// The integrated server's side of `LevelLoadTracker`: what its
/// `LevelLoadListener` reported (`serverProgress`, `hasProgress`) and the
/// chunk status map around the load focus (`ChunkLoadStatusView`), which the
/// server thread writes and the window's loading screen reads.
#[derive(Debug, Default)]
pub struct ServerLoadView {
tracker: std::sync::Mutex<ProgressTracker>,
/// `serverStage != null`.
has_progress: std::sync::atomic::AtomicBool,
/// `statusView.get(x, z)` for x and z in `0..=2 * STATUS_RADIUS`.
cells: std::sync::Mutex<Vec<Option<Status>>>,
}
impl ServerLoadView {
/// `LevelLoadListener.start`.
pub fn start(&self, stage: Stage, total_chunks: usize) {
Self::lock(&self.tracker).start(stage, total_chunks);
// `serverStage = stage`, whatever the stage.
self.has_progress
.store(true, std::sync::atomic::Ordering::Relaxed);
}
/// `LevelLoadListener.update`.
pub fn update(&self, stage: Stage, current: usize, total: usize) {
Self::lock(&self.tracker).update(stage, current, total);
}
/// `LevelLoadListener.finish`.
pub fn finish(&self, stage: Stage) {
Self::lock(&self.tracker).finish(stage);
}
/// `LevelLoadTracker.hasProgress`.
pub fn has_progress(&self) -> bool {
self.has_progress.load(std::sync::atomic::Ordering::Relaxed)
}
/// `LevelLoadTracker.serverProgress`.
pub fn server_progress(&self) -> f32 {
Self::lock(&self.tracker).progress
}
/// The map `ChunkLoadStatusView.get` reads, replaced as a whole.
pub fn set_status(&self, cells: Vec<Option<Status>>) {
*Self::lock(&self.cells) = cells;
}
/// `ChunkLoadStatusView.get`.
pub fn status(&self, x: i32, z: i32) -> Option<Status> {
let diameter = (STATUS_RADIUS * 2 + 1) as usize;
let (x, z) = (usize::try_from(x).ok()?, usize::try_from(z).ok()?);
if x >= diameter || z >= diameter {
return None;
}
Self::lock(&self.cells)
.get(x * diameter + z)
.copied()
.flatten()
}
fn lock<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
}
/// `LevelLoadProgressTracker.get` once the server is prepared, with `ready`
/// of the player's 49 chunks loaded (no forced chunks to load first).
pub fn progress(ready: usize) -> f32 {
let total = PREPARE_WEIGHT + PLAYER_CHUNKS;
(PREPARE_WEIGHT + ready.min(PLAYER_CHUNKS)) as f32 / total as f32
}
/// `LevelLoadingScreen.tick`: the bar eases a fifth of the way each tick.
pub fn smooth(smoothed: f32, progress: f32) -> f32 {
smoothed + (progress - smoothed) * 0.2
}
/// `ARGB.opaque` as the batch's RGBA.
fn opaque(rgb: u32) -> u32 {
0xFF00_0000 | (rgb & 0xFF) << 16 | (rgb & 0xFF00) | (rgb >> 16 & 0xFF)
}
/// `LevelLoadingScreen.extractRenderState` over its background: the text,
/// the progress bar and the chunk map, `status(x, z)` for x and z in
/// `0..=2 * STATUS_RADIUS` from the map's north-west corner.
pub fn draw(
batch: &mut HudBatch,
atlas: &HudAtlas,
status: Option<&dyn Fn(i32, i32) -> Option<Status>>,
progress: Option<f32>,
) {
let (x_center, y_center) = ((batch.width as i32) / 2, (batch.height as i32) / 2);
let text_top = match status {
Some(status) => {
// extractChunksForRendering(size 2, margin 0).
let diameter = STATUS_RADIUS * 2 + 1;
let start = (x_center - diameter, y_center - diameter);
for x in 0..diameter {
for z in 0..diameter {
let color = opaque(status(x, z).map_or(0, Status::color));
let (cx, cy) = (start.0 + x * 2, start.1 + z * 2);
batch.fill(atlas, cx as f32, cy as f32, 2.0, 2.0, color);
}
}
y_center - STATUS_RADIUS * 2 - 9 * 3
}
None => y_center - 50,
};
let text = Text::translate("multiplayer.downloadingTerrain", &[]);
let tw = atlas.font.width_text(&text) as i32;
batch.text_styled(
atlas,
&text,
(x_center - tw / 2) as f32,
text_top as f32,
u32::MAX,
true,
);
if let Some(progress) = progress {
// drawProgressBar(xCenter - 100, textTop + 12, 200, 2).
let (left, top) = ((x_center - 100) as f32, (text_top + 9 + 3) as f32);
batch.fill(atlas, left, top, 200.0, 2.0, opaque(0));
let done = (progress * 200.0).round();
batch.fill(atlas, left, top, done, 2.0, opaque(0x00FF00));
}
}
/// The startup loading screen: the stage's line and a progress bar, centred
/// like `LevelLoadingScreen`'s text and bar.
pub fn draw_progress(batch: &mut HudBatch, atlas: &HudAtlas, line: &str, progress: f32) {
let (x_center, y_center) = ((batch.width as i32) / 2, (batch.height as i32) / 2);
let text_top = y_center - 50;
let text = Text::literal(line);
let tw = atlas.font.width_text(&text) as i32;
batch.text_styled(
atlas,
&text,
(x_center - tw / 2) as f32,
text_top as f32,
u32::MAX,
true,
);
let (left, top) = ((x_center - 100) as f32, (text_top + 9 + 3) as f32);
batch.fill(atlas, left, top, 200.0, 2.0, opaque(0));
let done = (progress.clamp(0.0, 1.0) * 200.0).round();
batch.fill(atlas, left, top, done, 2.0, opaque(0x00FF00));
}
/// `ConnectScreen`'s Cancel button corner on a GUI `w` x `h`:
/// (width / 2 - 100, height / 4 + 120 + 12), 200 x 20.
pub fn connect_cancel(w: f32, h: f32) -> (f32, f32) {
((w / 2.0).trunc() - 100.0, (h / 4.0).trunc() + 132.0)
}
/// `ConnectScreen.extractRenderState` over the menu background: the status
/// centred at (width / 2, height / 2 - 50) and, while the connection can
/// still be cancelled, Cancel.
pub fn draw_connecting(
batch: &mut HudBatch,
atlas: &HudAtlas,
status: &Text,
cursor: (f32, f32),
cancel: bool,
) {
let (w, h) = (batch.width, batch.height);
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
let tw = atlas.font.width_text(status);
let (x, y) = (((w - tw) / 2.0).trunc(), (h / 2.0).trunc() - 50.0);
batch.text_styled(atlas, status, x, y, u32::MAX, true);
if cancel {
let (x, y) = connect_cancel(w, h);
let hover = crate::ui::hovered(cursor, x, y, 200.0, 20.0);
let label = Text::translate("gui.cancel", &[]);
crate::ui::button(batch, atlas, x, y, 200.0, 20.0, &label, true, hover);
}
}
/// `FileFixerProgressScreen`'s Cancel button corner on a GUI `w` x `h`:
/// ((width - 200) / 2, height / 2 + 100), 200 x 20.
pub fn file_fixer_cancel(w: f32, h: f32) -> (f32, f32) {
(((w as i32 - 200) / 2) as f32, (h as i32 / 2 + 100) as f32)
}
/// `GuiGraphicsExtractor.centeredText` with the screen's grey (`-6250336`) or white.
fn centered_line(
batch: &mut HudBatch,
atlas: &HudAtlas,
text: &Text,
x_center: i32,
y: i32,
color: u32,
) {
let tw = atlas.font.width_text(text) as i32;
batch.text_styled(
atlas,
text,
(x_center - tw / 2) as f32,
y as f32,
color,
true,
);
}
/// `FileFixerProgressScreen.extractProgressBar`.
fn file_fixer_bar(batch: &mut HudBatch, atlas: &HudAtlas, x_center: i32, y: i32, progress: f32) {
let left = x_center - 100;
batch.fill(atlas, left as f32, y as f32, 200.0, 2.0, opaque(0));
batch.fill(
atlas,
left as f32,
y as f32,
(progress * 200.0).round(),
2.0,
opaque(0x00FF00),
);
}
/// `FileFixerProgressScreen.extractRenderState` (with `extractProgress`,
/// `extractProgressBar`, `extractFileStats`, `extractFileFixerCount`,
/// `extractTypeText`, `extractTypeProgress` and `extractScanning`) over the menu background: the
/// title, then either the scanning line or the running fixer's bar, the
/// totals, the stage, the type's label and its bar and percentage; and
/// Cancel, inactive once pressed.
pub fn draw_file_fixer(
batch: &mut HudBatch,
atlas: &HudAtlas,
progress: &horizon_world::datafix::progress::UpgradeProgress,
cursor: (f32, f32),
) {
const GREY: u32 = 0xFFA0_A0A0;
let (w, h) = (batch.width, batch.height);
crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false);
let (x_center, y_center) = ((w as i32) / 2, (h as i32) / 2);
let text_top = y_center - 50;
centered_line(
batch,
atlas,
&Text::translate("upgradeWorld.title", &[]),
x_center,
text_top,
u32::MAX,
);
let total = progress.total_file_fix_stats();
if total.total_operations() > 0 {
let of_type = progress.type_file_fix_stats();
let running = progress.running_file_fixer_stats();
let mut y = text_top + 9 + 3;
file_fixer_bar(batch, atlas, x_center, y, running.progress());
y += 7;
// extractFileStats
let converted = Text::tr(
"upgradeWorld.info.converted",
&[&total.finished_operations()],
);
centered_line(batch, atlas, &converted, x_center, y, GREY);
let sum = Text::tr("upgradeWorld.info.total", &[&total.total_operations()]);
centered_line(batch, atlas, &sum, x_center, y + 9 + 3, GREY);
y += 9 * 2 + 6;
// extractFileFixerCount
let stage = Text::tr(
"upgradeWorld.info.file_fix_stage",
&[&running.finished_operations(), &running.total_operations()],
);
centered_line(batch, atlas, &stage, x_center, y, GREY);
y += 9 + 30 - 5;
// extractTypeText
if let Some(ty) = progress.upgrade_type() {
let label = Text::translate(&ty.label_key(), &[]);
centered_line(batch, atlas, &label, x_center, y, GREY);
}
y += 9 + 3;
file_fixer_bar(batch, atlas, x_center, y, of_type.progress());
y += 7;
// extractTypeProgress: Mth.floor(progress * 100)
let percent = (of_type.progress() * 100.0).floor() as i32;
let text = Text::tr("upgradeWorld.progress.percentage", &[&percent]);
centered_line(batch, atlas, &text, x_center, y, GREY);
} else {
// extractScanning
let scanning = Text::translate("upgradeWorld.info.scanning", &[]);
centered_line(batch, atlas, &scanning, x_center, text_top + 9 + 3, GREY);
}
let (x, y) = file_fixer_cancel(w, h);
let active = !progress.is_canceled();
let hover = crate::ui::hovered(cursor, x, y, 200.0, 20.0);
let label = Text::translate("gui.cancel", &[]);
crate::ui::button(batch, atlas, x, y, 200.0, 20.0, &label, active, hover);
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn progress_weighs_the_prepared_server_and_the_player_chunks() {
assert_eq!(progress(0), 10.0 / 59.0);
assert_eq!(progress(49), 1.0);
assert_eq!(progress(100), 1.0);
let eased = smooth(0.0, 1.0);
assert_eq!(eased, 0.2);
assert!((smooth(eased, 1.0) - 0.36).abs() < 1e-6);
}
#[test]
fn file_fixer_cancel_sits_below_the_centre() {
assert_eq!(file_fixer_cancel(427.0, 240.0), (113.0, 220.0));
assert_eq!(file_fixer_cancel(426.0, 241.0), (113.0, 220.0));
}
#[test]
fn colours_are_opaque_rgba() {
assert_eq!(opaque(Status::Full.color()), u32::MAX);
assert_eq!(opaque(0), 0xFF00_0000);
assert_eq!(opaque(0x00FF00), crate::hud::rgba(0, 255, 0, 255));
assert_eq!(
opaque(Status::Biomes.color()),
crate::hud::rgba(0x80, 0xB2, 0x52, 255)
);
}
}
#[cfg(test)]
mod tracker_tests {
use super::*;
const ALIVE: PlayerCheck = PlayerCheck {
outside_build_height: false,
spectator: false,
alive: true,
};
#[test]
fn server_progress_follows_the_listener_like_the_progress_tracker() {
let view = ServerLoadView::default();
assert!(!view.has_progress() && view.server_progress() == 0.0);
// A stage the tracker ignores still counts as progress being made.
view.start(Stage::StartServer, 0);
assert!(view.has_progress() && view.server_progress() == 0.0);
// prepareLevels with no forced chunks: the 10 of preparing, of 59.
view.start(Stage::LoadInitialChunks, 0);
view.finish(Stage::LoadInitialChunks);
assert_eq!(view.server_progress(), 10.0 / 59.0);
// PrepareSpawnTask: the 49 player chunks.
view.start(Stage::LoadPlayerChunks, 49);
view.update(Stage::LoadPlayerChunks, 20, 49);
assert_eq!(view.server_progress(), (10.0 + 20.0) / 59.0);
assert_eq!(view.server_progress(), progress(20));
view.update(Stage::LoadPlayerChunks, 49, 49);
view.finish(Stage::LoadPlayerChunks);
assert_eq!(view.server_progress(), 1.0);
}
#[test]
fn the_status_map_is_read_from_the_north_west_corner() {
let view = ServerLoadView::default();
assert_eq!(view.status(0, 0), None);
let diameter = (STATUS_RADIUS * 2 + 1) as usize;
let mut cells = vec![None; diameter * diameter];
cells[3 * diameter + 5] = Some(Status::Full);
view.set_status(cells);
assert_eq!(view.status(3, 5), Some(Status::Full));
assert_eq!(view.status(5, 3), None);
assert_eq!(view.status(-1, 0), None);
assert_eq!(view.status(diameter as i32, 0), None);
}
#[test]
fn the_load_waits_for_the_server_then_the_players_section() {
let mut tracker = LevelLoadTracker::new(0);
assert!(!tracker.is_active());
tracker.start_client_load(1_000, Reason::NetherPortal);
assert!(tracker.is_active() && tracker.reason == Reason::NetherPortal);
// Nothing is asked of the renderer before the start event, and a
// section shown early counts for nothing.
assert!(!tracker.wants_player_section());
tracker.player_section_ready();
tracker.tick_client_load(1_050, ALIVE);
assert!(!tracker.is_level_ready(1_050));
tracker.loading_packets_received();
assert!(tracker.wants_player_section());
tracker.tick_client_load(1_100, ALIVE);
assert!(!tracker.is_level_ready(1_100));
tracker.player_section_ready();
tracker.tick_client_load(1_150, ALIVE);
assert!(tracker.is_level_ready(1_150));
tracker.finish();
assert!(!tracker.is_active() && !tracker.is_level_ready(2_000));
}
#[test]
fn a_player_who_cannot_see_the_section_does_not_wait_for_it() {
for player in [
PlayerCheck {
outside_build_height: true,
..ALIVE
},
PlayerCheck {
spectator: true,
..ALIVE
},
PlayerCheck {
alive: false,
..ALIVE
},
] {
let mut tracker = LevelLoadTracker::new(0);
tracker.start_client_load(0, Reason::Other);
tracker.loading_packets_received();
tracker.tick_client_load(10, player);
assert!(tracker.is_level_ready(10));
}
}
#[test]
fn the_wait_times_out_after_thirty_seconds_but_only_once_the_server_has_started() {
let mut tracker = LevelLoadTracker::new(0);
tracker.start_client_load(0, Reason::Other);
tracker.tick_client_load(CLIENT_WAIT_TIMEOUT_MS + 1, ALIVE);
assert!(!tracker.is_level_ready(CLIENT_WAIT_TIMEOUT_MS + 1));
tracker.loading_packets_received();
tracker.tick_client_load(CLIENT_WAIT_TIMEOUT_MS, ALIVE);
assert!(!tracker.is_level_ready(CLIENT_WAIT_TIMEOUT_MS));
tracker.tick_client_load(CLIENT_WAIT_TIMEOUT_MS + 1, ALIVE);
assert!(tracker.is_level_ready(CLIENT_WAIT_TIMEOUT_MS + 1));
}
#[test]
fn a_new_worlds_screen_stays_for_the_close_delay() {
let mut tracker = LevelLoadTracker::new(LEVEL_LOAD_CLOSE_DELAY_MS);
tracker.start_client_load(0, Reason::Other);
tracker.loading_packets_received();
tracker.player_section_ready();
tracker.tick_client_load(100, ALIVE);
assert!(!tracker.is_level_ready(599));
assert!(tracker.is_level_ready(600));
}
#[test]
fn a_respawn_names_its_screen_by_the_dimensions() {
let (overworld, nether, end) = (
"minecraft:overworld",
"minecraft:the_nether",
"minecraft:the_end",
);
assert_eq!(
reason_for_respawn(false, nether, overworld),
Reason::NetherPortal
);
assert_eq!(
reason_for_respawn(false, overworld, nether),
Reason::NetherPortal
);
assert_eq!(reason_for_respawn(false, end, overworld), Reason::EndPortal);
assert_eq!(reason_for_respawn(false, end, nether), Reason::NetherPortal);
assert_eq!(
reason_for_respawn(false, overworld, overworld),
Reason::Other
);
// A death never shows a portal.
assert_eq!(reason_for_respawn(true, nether, overworld), Reason::Other);
}
}
-125
View File
@@ -1,125 +0,0 @@
//! The client's world data, rendering and screens: chunks, meshing, light, streaming, the renderer,
//! the HUD, menus and settings. Gameplay (horizon-client) builds on it; nothing here reaches gameplay.
#![forbid(unsafe_code)]
pub mod assets;
pub mod atlas_sources;
pub mod audio;
pub mod auth;
pub mod bidi;
pub mod biome;
pub mod block_entities;
pub mod block_entity_anim;
pub mod block_entity_render;
pub mod border_render;
pub mod breaking;
pub mod brewing;
pub mod camera;
pub mod chat;
pub mod chunk;
pub mod chunk_map;
pub mod clouds;
pub mod collisions;
pub mod command_block;
pub mod containers;
pub mod crash;
pub mod datapack;
pub mod dynamic_light;
pub mod effects;
pub mod environment;
pub mod extras;
pub mod fast_hash;
pub mod fog;
pub mod font;
pub mod gfx;
pub mod graphics;
pub mod graphics_style;
pub mod graphics_ui;
pub mod hud;
pub mod hud_layout;
pub mod hud_overlays;
pub mod inventory_effects;
pub mod java_text;
pub mod jigsaw_block;
pub mod level_loading;
pub mod light;
pub mod lod;
pub mod logging;
pub mod menu_blur;
pub mod mesher;
pub mod minimap;
pub mod mipmap;
pub mod mod_list;
pub mod model_library;
pub mod models;
pub mod multiline_edit;
pub mod options_file;
pub mod options_fixes;
pub mod options_ui;
pub mod overlay;
pub mod pack_screen;
pub mod packs;
pub mod par;
pub mod particles;
pub mod poi_sections;
pub mod post_chain;
pub mod potent_sulfur;
pub mod providers;
pub mod screen_draw;
pub mod screen_effects;
pub mod sculk;
pub mod section_mask;
pub mod settings;
pub mod shader_pack_list;
pub mod signs;
pub mod skins;
pub mod sound_engine;
pub mod sound_events;
pub mod sound_preview;
pub mod spans;
pub mod split_layout;
mod sprite_cache;
pub mod sprites;
pub mod streaming;
pub mod structure_block;
pub mod tab_list;
pub mod telemetry;
pub mod test_block;
pub mod test_instance_block;
pub mod testgen;
pub mod title_edition;
pub mod trims;
pub mod ui;
pub mod vault;
pub mod weather;
pub mod widgets;
pub mod world;
pub mod worldborder;
pub mod zip;
pub use horizon_client_core::Result;
pub use horizon_client_core::block_entity_nbt;
pub use horizon_client_core::bossbar;
pub use horizon_client_core::component;
pub use horizon_client_core::fastutil_order;
pub use horizon_client_core::gamerules;
pub use horizon_client_core::lang;
pub use horizon_client_core::nbt_path;
pub use horizon_client_core::scoreboard;
pub use horizon_client_core::snbt;
pub use horizon_client_core::text;
pub use horizon_client_input::clipboard;
pub use horizon_client_input::gamepad;
pub use horizon_client_input::input;
pub use horizon_client_input::interaction_input;
pub use horizon_client_input::key_names;
pub use horizon_client_input::keybinds;
pub use horizon_client_input::keymapping;
pub use horizon_client_input::mouse;
pub use horizon_client_input::window;
pub use horizon_command as command;
pub use horizon_items::blocks;
pub use horizon_items::bundle;
pub use horizon_items::cooldowns;
pub use horizon_items::enchant;
pub use horizon_items::item_data;
pub use horizon_items::items;
pub use horizon_items::random_sequences;
@@ -1,356 +0,0 @@
//! Decorated far-terrain chunks kept on disk, beside a dimension's save, so a
//! world opened again shows them without generating them again. One append-only
//! file per 32x32 chunk region; a file written by another build, block registry
//! or format is cleared on first use.
use super::{Column, Span, Surface};
use crate::fast_hash::FxHashMap;
use horizon_world::registry::BlockStateId;
use std::{
fs::{File, OpenOptions},
io::{Read, Seek, SeekFrom, Write},
path::PathBuf,
sync::{Arc, Mutex},
};
const MAGIC: &[u8; 4] = b"HLOD";
const FORMAT: u32 = 1;
const HEADER: u64 = 16;
/// A record: chunk x and z, then the deflated columns' length.
const RECORD: u64 = 12;
/// Columns of a chunk are a few kilobytes deflated; anything larger is damage.
const MAX_RECORD: u32 = 1 << 22;
type Columns = Arc<[Column; 256]>;
struct Region {
file: File,
/// Each chunk's latest record: the offset of its deflated columns, and
/// their length.
index: FxHashMap<(i32, i32), (u64, u32)>,
}
pub struct DiskCache {
dir: PathBuf,
key: u64,
// ponytail: one lock for every region, with file reads under it; per-region
// locks if the sampling threads ever wait on it.
regions: Mutex<FxHashMap<(i32, i32), Option<Region>>>,
}
impl DiskCache {
/// `key`: what the cached columns depend on (`build_key`); files with
/// another are cleared.
pub fn new(dir: PathBuf, key: u64) -> Self {
Self {
dir,
key,
regions: Mutex::default(),
}
}
pub fn get(&self, x: i32, z: i32) -> Option<Columns> {
let mut regions = self.regions.lock().ok()?;
let region = self.region(&mut regions, x, z, false)?;
let &(offset, len) = region.index.get(&(x, z))?;
let mut bytes = vec![0; len as usize];
region.file.seek(SeekFrom::Start(offset)).ok()?;
region.file.read_exact(&mut bytes).ok()?;
drop(regions);
decode(&bytes).map(Arc::new)
}
fn contains(&self, x: i32, z: i32) -> bool {
let Ok(mut regions) = self.regions.lock() else {
return false;
};
self.region(&mut regions, x, z, false)
.is_some_and(|region| region.index.contains_key(&(x, z)))
}
/// Writes a chunk not cached yet. One already cached stays as it is: the
/// build key clears stale ones, and a generation batch hands back
/// neighbours cached before, which appended again grew the files each
/// session.
pub fn put(&self, x: i32, z: i32, columns: &[Column; 256]) {
if self.contains(x, z) {
return;
}
let bytes = encode(columns);
let Ok(mut regions) = self.regions.lock() else {
return;
};
let Some(region) = self.region(&mut regions, x, z, true) else {
return;
};
// Another sampler's thread may have written it while this one encoded.
if region.index.contains_key(&(x, z)) {
return;
}
let mut record = Vec::with_capacity(RECORD as usize + bytes.len());
record.extend_from_slice(&x.to_le_bytes());
record.extend_from_slice(&z.to_le_bytes());
record.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
record.extend_from_slice(&bytes);
let Ok(end) = region.file.seek(SeekFrom::End(0)) else {
return;
};
// One write, so a crash leaves at most a torn last record, which
// the next open cuts off.
if region.file.write_all(&record).is_ok() {
region
.index
.insert((x, z), (end + RECORD, bytes.len() as u32));
}
}
fn region<'a>(
&self,
regions: &'a mut FxHashMap<(i32, i32), Option<Region>>,
x: i32,
z: i32,
create: bool,
) -> Option<&'a mut Region> {
let at = (x >> 5, z >> 5);
if create && matches!(regions.get(&at), Some(None)) {
regions.remove(&at);
}
regions
.entry(at)
.or_insert_with(|| self.open(at, create))
.as_mut()
}
fn open(&self, (rx, rz): (i32, i32), create: bool) -> Option<Region> {
let path = self.dir.join(format!("r.{rx}.{rz}.hlod"));
if !create && !path.exists() {
return None;
}
if create {
std::fs::create_dir_all(&self.dir).ok()?;
}
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(create)
.truncate(false)
.open(&path)
.ok()?;
let mut header = [0; HEADER as usize];
let current = file.read_exact(&mut header).is_ok()
&& header[..4] == *MAGIC
&& header[4..8] == FORMAT.to_le_bytes()
&& header[8..] == self.key.to_le_bytes();
let mut index = FxHashMap::default();
if current {
let size = file.metadata().ok()?.len();
let mut at = HEADER;
let mut record = [0; RECORD as usize];
while at + RECORD <= size {
file.seek(SeekFrom::Start(at)).ok()?;
file.read_exact(&mut record).ok()?;
let field = |i: usize| u32::from_le_bytes(record[i..i + 4].try_into().unwrap());
let len = field(8);
if len > MAX_RECORD || at + RECORD + u64::from(len) > size {
break;
}
index.insert((field(0) as i32, field(4) as i32), (at + RECORD, len));
at += RECORD + u64::from(len);
}
if at < size {
file.set_len(at).ok()?;
}
} else {
file.set_len(0).ok()?;
file.seek(SeekFrom::Start(0)).ok()?;
let mut header = Vec::with_capacity(HEADER as usize);
header.extend_from_slice(MAGIC);
header.extend_from_slice(&FORMAT.to_le_bytes());
header.extend_from_slice(&self.key.to_le_bytes());
file.write_all(&header).ok()?;
}
Some(Region { file, index })
}
}
/// What cached columns depend on: this build (its commit, or for a local
/// build the executable's own time, so a rebuilt generator starts afresh),
/// the block states and the biomes.
pub fn build_key(states: usize, biomes: usize) -> u64 {
use std::hash::{Hash, Hasher};
let mut hasher = std::hash::DefaultHasher::new();
FORMAT.hash(&mut hasher);
env!("CARGO_PKG_VERSION").hash(&mut hasher);
match option_env!("HORIZON_COMMIT") {
Some(commit) => commit.hash(&mut hasher),
None => std::env::current_exe()
.and_then(|exe| exe.metadata()?.modified())
.ok()
.hash(&mut hasher),
}
states.hash(&mut hasher);
biomes.hash(&mut hasher);
hasher.finish()
}
fn encode(columns: &[Column; 256]) -> Vec<u8> {
let mut out = Vec::new();
for column in columns {
match column.surface {
None => out.push(0),
Some(s) => {
out.push(1 + u8::from(s.water.is_some()));
out.extend_from_slice(&s.height.to_le_bytes());
out.extend_from_slice(&s.state.0.to_le_bytes());
out.extend_from_slice(&s.biome.to_le_bytes());
if let Some((height, state)) = s.water {
out.extend_from_slice(&height.to_le_bytes());
out.extend_from_slice(&state.0.to_le_bytes());
}
}
}
out.extend_from_slice(&(column.spans.len() as u16).to_le_bytes());
for span in &column.spans {
out.extend_from_slice(&span.min.to_le_bytes());
out.extend_from_slice(&span.max.to_le_bytes());
out.extend_from_slice(&span.state.0.to_le_bytes());
out.extend_from_slice(&span.biome.to_le_bytes());
out.extend_from_slice(&span.light.to_le_bytes());
}
}
let mut deflate =
flate2::write::DeflateEncoder::new(Vec::new(), flate2::Compression::default());
// Writing to a Vec cannot fail.
deflate.write_all(&out).unwrap();
deflate.finish().unwrap()
}
fn decode(bytes: &[u8]) -> Option<[Column; 256]> {
let mut raw = Vec::new();
flate2::read::DeflateDecoder::new(bytes)
.take(u64::from(MAX_RECORD) * 8)
.read_to_end(&mut raw)
.ok()?;
let mut at = 0;
let mut take = |n: usize| {
let field = raw.get(at..at + n)?;
at += n;
Some(field)
};
let mut columns: [Column; 256] = std::array::from_fn(|_| Column::default());
for column in &mut columns {
let i32_ = |b: &[u8]| i32::from_le_bytes(b.try_into().unwrap());
let u32_ = |b: &[u8]| u32::from_le_bytes(b.try_into().unwrap());
let u16_ = |b: &[u8]| u16::from_le_bytes(b.try_into().unwrap());
let i16_ = |b: &[u8]| i16::from_le_bytes(b.try_into().unwrap());
let tag = take(1)?[0];
if tag > 2 {
return None;
}
if tag > 0 {
let height = i32_(take(4)?);
let state = BlockStateId(u32_(take(4)?));
let biome = u16_(take(2)?);
let water = if tag == 2 {
Some((i32_(take(4)?), BlockStateId(u32_(take(4)?))))
} else {
None
};
column.surface = Some(Surface {
height,
state,
water,
biome,
});
}
let count = u16_(take(2)?);
column.spans.reserve(count.into());
for _ in 0..count {
let span = Span {
min: i16_(take(2)?),
max: i16_(take(2)?),
state: BlockStateId(u32_(take(4)?)),
biome: u16_(take(2)?),
light: u16_(take(2)?),
};
if span.min >= span.max {
return None;
}
column.spans.push(span);
}
}
(at == raw.len()).then_some(columns)
}
#[cfg(test)]
mod tests {
use super::*;
fn columns(seed: u32) -> [Column; 256] {
std::array::from_fn(|i| {
let i = i as u32 + seed;
Column {
surface: (!i.is_multiple_of(3)).then(|| Surface {
height: 60 + (i % 7) as i32,
state: BlockStateId(i),
water: (i.is_multiple_of(2)).then_some((63, BlockStateId(9))),
biome: (i % 5) as u16,
}),
spans: (0..i % 4)
.map(|n| Span {
min: (n * 10) as i16 - 64,
max: (n * 10 + 4) as i16 - 64,
state: BlockStateId(n + i),
biome: 2,
light: 240,
})
.collect(),
}
})
}
#[test]
fn chunks_survive_reopening_and_a_torn_last_record() {
let dir = std::env::temp_dir().join(format!("horizon-lod-cache-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let cache = DiskCache::new(dir.clone(), 7);
assert!(cache.get(3, -40).is_none(), "nothing cached yet");
cache.put(3, -40, &columns(0));
cache.put(4, -40, &columns(1));
let path = dir.join("r.0.-2.hlod");
let size = std::fs::metadata(&path).unwrap().len();
// A chunk cached already is not appended again.
cache.put(3, -40, &columns(2));
assert_eq!(*cache.get(3, -40).unwrap(), columns(0));
assert_eq!(std::fs::metadata(&path).unwrap().len(), size);
drop(cache);
let file = OpenOptions::new().write(true).open(&path).unwrap();
file.set_len(size + 7).unwrap();
drop(file);
let cache = DiskCache::new(dir.clone(), 7);
assert_eq!(*cache.get(3, -40).unwrap(), columns(0));
assert_eq!(*cache.get(4, -40).unwrap(), columns(1));
assert_eq!(
std::fs::metadata(&path).unwrap().len(),
size,
"torn tail cut"
);
drop(cache);
// Another build's files are cleared, not read.
let cache = DiskCache::new(dir.clone(), 8);
assert!(cache.get(3, -40).is_none());
cache.put(5, -40, &columns(3));
assert!(cache.get(4, -40).is_none());
assert_eq!(*cache.get(5, -40).unwrap(), columns(3));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn damaged_records_read_as_missing() {
let bytes = encode(&columns(0));
assert_eq!(decode(&bytes).unwrap(), columns(0));
assert!(decode(&bytes[..bytes.len() / 2]).is_none());
assert!(decode(b"not deflate").is_none());
}
}
@@ -1,780 +0,0 @@
//! `MultiLineEditBox` over `MultilineTextField` (and `AbstractTextAreaWidget`'s
//! frame and scroll bar): a text area that wraps its text to the box, with a
//! caret and selection that move by line, a character limit, a line limit and
//! a scroll bar. Indices count characters, as `EditBox`'s do.
use crate::{
clipboard::{Clipboard, EditShortcut, filter_text},
font::Font,
hud::{HudAtlas, HudBatch, rgba},
text::Style,
ui::{self, Scroll, java_whitespace},
};
use std::time::Instant;
use winit::keyboard::KeyCode;
/// `AbstractTextAreaWidget.INNER_PADDING`.
const PADDING: f32 = 4.0;
/// `Font.lineHeight`.
const LINE: f32 = 9.0;
/// `AbstractScrollArea.defaultSettings((int) (9.0 / 2.0))`'s scroll rate.
const SCROLL_RATE: f32 = 4.0;
/// `StringSplitter.splitLines(value, width, Style.EMPTY, false, ..)`: each
/// line's `[begin, end)`. A line ends at a `\n`, or once a character overflows
/// the width (never the first visible one) at the last space so far, or before
/// that character; the `\n` or space at the end is skipped.
pub fn split_ranges(font: &Font, chars: &[char], width: f32) -> Vec<(usize, usize)> {
let max_width = width.max(1.0);
let style = Style::default();
let mut out = Vec::new();
let mut start = 0;
while start < chars.len() {
let (mut line_width, mut had_visible, mut last_space) = (0.0f32, false, None);
let mut line_break = None;
for (i, &c) in chars.iter().enumerate().skip(start) {
if c == '\n' {
line_break = Some(i);
break;
}
if c == ' ' {
last_space = Some(i);
}
let advance = font.advance(c, &style);
line_width += advance;
if !had_visible || line_width <= max_width {
had_visible |= advance != 0.0;
} else {
line_break = Some(last_space.unwrap_or(i));
break;
}
}
let Some(at) = line_break else {
out.push((start, chars.len()));
break;
};
out.push((start, at));
start = if matches!(chars[at], '\n' | ' ') {
at + 1
} else {
at
};
}
out
}
/// `MultiLineEditBox` with its `MultilineTextField`.
pub struct MultiLineEdit {
chars: Vec<char>,
cursor: usize,
select_cursor: usize,
selecting: bool,
/// `characterLimit` (`MultilineTextField.NO_LIMIT` is `None`).
character_limit: Option<usize>,
line_limit: Option<usize>,
/// `displayLines`.
lines: Vec<(usize, usize)>,
pub x: f32,
pub y: f32,
pub width: f32,
pub height: f32,
pub focused: bool,
focused_at: Instant,
pub scroll: Scroll,
}
impl MultiLineEdit {
pub fn new(font: &Font, x: f32, y: f32, width: f32, height: f32) -> Self {
let mut edit = Self {
chars: Vec::new(),
cursor: 0,
select_cursor: 0,
selecting: false,
character_limit: None,
line_limit: None,
lines: Vec::new(),
x,
y,
width,
height,
focused: false,
focused_at: Instant::now(),
scroll: Scroll::default(),
};
edit.reflow(font);
edit
}
/// `AbstractTextAreaWidget.totalInnerPadding`.
fn text_width(&self) -> f32 {
self.width - 2.0 * PADDING
}
pub fn set_character_limit(&mut self, limit: usize) {
self.character_limit = Some(limit);
}
pub fn set_line_limit(&mut self, limit: usize) {
self.line_limit = Some(limit);
}
pub fn value(&self) -> String {
self.chars.iter().collect()
}
pub fn cursor(&self) -> usize {
self.cursor
}
pub fn line_count(&self) -> usize {
self.lines.len()
}
pub fn lines(&self) -> &[(usize, usize)] {
&self.lines
}
pub fn has_selection(&self) -> bool {
self.select_cursor != self.cursor
}
/// `getSelected`.
fn selected(&self) -> (usize, usize) {
(
self.select_cursor.min(self.cursor),
self.select_cursor.max(self.cursor),
)
}
pub fn selected_text(&self) -> String {
let (begin, end) = self.selected();
self.chars[begin..end].iter().collect()
}
/// `setValue(value, false)`: kept as it was when the text has more lines
/// than the limit allows.
pub fn set_value(&mut self, font: &Font, value: &str) {
let mut chars: Vec<char> = value.chars().collect();
if let Some(limit) = self.character_limit {
chars.truncate(limit);
}
if !self.overflows_line_limit(font, &chars) {
self.chars = chars;
self.cursor = self.chars.len();
self.select_cursor = self.cursor;
self.on_value_change(font);
}
}
/// `overflowsLineLimit`.
fn overflows_line_limit(&self, font: &Font, value: &[char]) -> bool {
let Some(limit) = self.line_limit else {
return false;
};
let lines = split_ranges(font, value, self.text_width()).len();
// `StringUtil.endsWithNewLine`.
lines + usize::from(value.last().is_some_and(|c| matches!(c, '\n' | '\r'))) > limit
}
/// `insertText`.
pub fn insert_text(&mut self, font: &Font, input: &str) {
if input.is_empty() && !self.has_selection() {
return;
}
let mut text: Vec<char> = filter_text(input, true).chars().collect();
if let Some(limit) = self.character_limit {
text.truncate(limit.saturating_sub(self.chars.len()));
}
let (begin, end) = self.selected();
let mut value = self.chars[..begin].to_vec();
value.extend_from_slice(&text);
value.extend_from_slice(&self.chars[end..]);
if !self.overflows_line_limit(font, &value) {
self.chars = value;
self.cursor = begin + text.len();
self.select_cursor = self.cursor;
self.on_value_change(font);
}
}
/// `deleteText`.
pub fn delete_text(&mut self, font: &Font, dir: isize) {
if !self.has_selection() {
self.select_cursor = self.cursor.saturating_add_signed(dir).min(self.chars.len());
}
self.insert_text(font, "");
}
/// `onValueChange`: the lines again, and the cursor in view.
fn on_value_change(&mut self, font: &Font) {
self.reflow(font);
self.scroll_to_cursor();
}
/// `reflowDisplayLines`.
fn reflow(&mut self, font: &Font) {
self.lines = if self.chars.is_empty() {
vec![(0, 0)]
} else {
let mut lines = split_ranges(font, &self.chars, self.text_width());
if self.chars.last() == Some(&'\n') {
lines.push((self.chars.len(), self.chars.len()));
}
lines
};
}
/// `getLineAtCursor`: -1 when no line holds the cursor.
fn line_at_cursor(&self) -> isize {
self.lines
.iter()
.position(|&(begin, end)| self.cursor >= begin && self.cursor <= end)
.map_or(-1, |i| i as isize)
}
/// `getLineView`: the index clamped to the lines.
fn line_view(&self, index: isize) -> (usize, usize) {
self.lines[index.clamp(0, self.lines.len() as isize - 1) as usize]
}
/// `getCursorLineView(offset)`.
fn cursor_line_view(&self, offset: isize) -> (usize, usize) {
match self.line_at_cursor() {
-1 => *self.lines.last().expect("a text field has a line"),
line => self.line_view(line + offset),
}
}
/// `AbstractScrollArea.contentHeight` of the text area.
fn content_height(&self) -> f32 {
LINE * self.lines.len() as f32 + 2.0 * PADDING
}
/// `setScrollAmount`.
fn set_scroll(&mut self, amount: f32) {
self.scroll.amount = amount;
self.scroll.clamp(0.0, self.height, self.content_height());
}
/// `MultiLineEditBox.scrollToCursor`, the text field's cursor listener.
fn scroll_to_cursor(&mut self) {
let mut amount = self.scroll.amount;
let first = self.line_view((amount / LINE) as isize);
let line = self.line_at_cursor() as f32;
if self.cursor <= first.0 {
amount = line * LINE;
} else {
let last = self.line_view(((amount + self.height) / LINE) as isize - 1);
if self.cursor > last.1 {
amount = line * LINE - self.height + LINE + 2.0 * PADDING;
}
}
self.set_scroll(amount);
}
/// `seekCursor` to `cursor`, then the cursor listener.
fn seek_cursor(&mut self, cursor: usize) {
self.cursor = cursor.min(self.chars.len());
self.scroll_to_cursor();
if !self.selecting {
self.select_cursor = self.cursor;
}
}
/// `seekCursorLine`.
fn seek_cursor_line(&mut self, font: &Font, offset: isize) {
if offset == 0 {
return;
}
let (begin, _) = self.cursor_line_view(0);
let before: String = self.chars[begin..self.cursor].iter().collect();
let old_left = font.width(&before) + 2.0;
let (begin, end) = self.cursor_line_view(offset);
let line: String = self.chars[begin..end].iter().collect();
self.seek_cursor(begin + font.fit(&line, old_left));
}
/// `seekCursorToPoint`: `x` and `y` from the top left of the text.
fn seek_cursor_to_point(&mut self, font: &Font, x: f32, y: f32) {
let left = x.floor();
let top = (y / LINE).floor() as isize;
let (begin, end) = self.line_view(top);
let line: String = self.chars[begin..end].iter().collect();
self.seek_cursor(begin + font.fit(&line, left));
}
/// `getPreviousWord`: where the word starts and ends.
fn previous_word(&self) -> (usize, usize) {
if self.chars.is_empty() {
return (0, 0);
}
let mut start = self.cursor.min(self.chars.len() - 1);
while start > 0 && java_whitespace(self.chars[start - 1]) {
start -= 1;
}
while start > 0 && !java_whitespace(self.chars[start - 1]) {
start -= 1;
}
(start, self.word_end(start))
}
/// `getNextWord`.
fn next_word(&self) -> (usize, usize) {
if self.chars.is_empty() {
return (0, 0);
}
let mut start = self.cursor.min(self.chars.len() - 1);
while start < self.chars.len() && !java_whitespace(self.chars[start]) {
start += 1;
}
while start < self.chars.len() && java_whitespace(self.chars[start]) {
start += 1;
}
(start, self.word_end(start))
}
fn word_end(&self, from: usize) -> usize {
let mut end = from;
while end < self.chars.len() && !java_whitespace(self.chars[end]) {
end += 1;
}
end
}
/// `selectWordAtCursor`.
fn select_word_at_cursor(&mut self) {
let (begin, end) = self.previous_word();
self.seek_cursor(begin);
self.selecting = true;
self.seek_cursor(end);
}
/// `MultilineTextField.keyPressed` for the keys that are not shortcuts.
/// True when the key was used.
pub fn key(&mut self, font: &Font, key: KeyCode, ctrl: bool, shift: bool) -> bool {
self.selecting = shift;
match key {
KeyCode::Backspace if ctrl => {
let (begin, _) = self.previous_word();
self.delete_text(font, begin as isize - self.cursor as isize);
}
KeyCode::Backspace => self.delete_text(font, -1),
KeyCode::Enter | KeyCode::NumpadEnter => self.insert_text(font, "\n"),
KeyCode::Delete if ctrl => {
let (begin, _) = self.next_word();
self.delete_text(font, begin as isize - self.cursor as isize);
}
KeyCode::Delete => self.delete_text(font, 1),
KeyCode::Home if ctrl => self.seek_cursor(0),
KeyCode::Home => self.seek_cursor(self.cursor_line_view(0).0),
KeyCode::PageUp => self.seek_cursor(0),
KeyCode::End if ctrl => self.seek_cursor(self.chars.len()),
KeyCode::End => self.seek_cursor(self.cursor_line_view(0).1),
KeyCode::PageDown => self.seek_cursor(self.chars.len()),
KeyCode::ArrowRight if ctrl => self.seek_cursor(self.next_word().0),
KeyCode::ArrowRight => self.seek_cursor(self.cursor + 1),
KeyCode::ArrowLeft if ctrl => self.seek_cursor(self.previous_word().0),
KeyCode::ArrowLeft => self.seek_cursor(self.cursor.saturating_sub(1)),
KeyCode::ArrowDown => {
if !ctrl {
self.seek_cursor_line(font, 1);
}
}
KeyCode::ArrowUp => {
if !ctrl {
self.seek_cursor_line(font, -1);
}
}
_ => return false,
}
true
}
/// Ctrl+A/C/V/X. True when the value changed.
pub fn shortcut(
&mut self,
font: &Font,
shortcut: EditShortcut,
clipboard: &mut dyn Clipboard,
) -> bool {
let before = self.chars.len();
match shortcut {
EditShortcut::SelectAll => {
self.cursor = self.chars.len();
self.select_cursor = 0;
}
EditShortcut::Copy => clipboard.set(&self.selected_text()),
EditShortcut::Paste => self.insert_text(font, &clipboard.get()),
EditShortcut::Cut => {
clipboard.set(&self.selected_text());
self.insert_text(font, "");
}
}
self.focused_at = Instant::now();
self.chars.len() != before
}
/// `AbstractWidget.isMouseOver`: the box and its scroll bar.
pub fn hovered(&self, (x, y): (f32, f32)) -> bool {
x >= self.x && y >= self.y && x < self.x + self.width + 6.0 && y < self.y + self.height
}
/// `AbstractTextAreaWidget.mouseClicked`: a press on the scroll bar
/// holds it, else `onClick` places the cursor (`double`: selects the word).
pub fn click(&mut self, font: &Font, cursor: (f32, f32), shift: bool, double: bool) {
let bar = self.x + self.width;
if self.scroll.press(
cursor,
bar,
self.y,
self.y + self.height,
self.content_height(),
) {
return;
}
if double {
self.select_word_at_cursor();
} else {
self.selecting = shift;
self.seek_screen(font, cursor);
}
}
/// `onDrag`: the selection follows the pointer, or the held scroll bar does.
pub fn drag(&mut self, font: &Font, cursor: (f32, f32), shift: bool) {
if self.scroll.held() {
self.scroll.drag(
cursor.1,
self.y,
self.y + self.height,
self.content_height(),
);
return;
}
self.selecting = true;
self.seek_screen(font, cursor);
self.selecting = shift;
}
/// `onRelease`.
pub fn release(&mut self) {
self.scroll.release();
}
/// `mouseScrolled`.
pub fn wheel(&mut self, delta: f32) {
let amount = self.scroll.amount - delta * SCROLL_RATE;
self.set_scroll(amount);
}
/// `seekCursorScreen`.
fn seek_screen(&mut self, font: &Font, (x, y): (f32, f32)) {
let mouse_x = x - self.x - PADDING;
let mouse_y = y - self.y - PADDING + self.scroll.amount;
self.seek_cursor_to_point(font, mouse_x, mouse_y);
}
/// `setFocused`: the caret starts to blink.
pub fn set_focused(&mut self, focused: bool) {
if focused && !self.focused {
self.focused_at = Instant::now();
}
self.focused = focused;
}
/// `AbstractTextAreaWidget.withinContentAreaTopBottom`.
fn within(&self, top: f32, bottom: f32) -> bool {
bottom - self.scroll.amount >= self.y && top - self.scroll.amount <= self.y + self.height
}
/// `extractWidgetRenderState`: the frame, the text under a scissor, the
/// scroll bar and the character count.
pub fn draw(&self, batch: &mut HudBatch, atlas: &HudAtlas) {
crate::widgets::target_as(
[self.x, self.y, self.width, self.height],
crate::widgets::Kind::Field,
);
let sprite = if self.focused {
"gui/sprites/widget/text_field_highlighted"
} else {
"gui/sprites/widget/text_field"
};
ui::nine_slice(
batch,
atlas,
sprite,
self.x,
self.y,
self.width,
self.height,
u32::MAX,
);
let start = batch.vertices.len();
self.draw_contents(batch, atlas);
batch.clip_since(
start,
self.x + 1.0,
self.y + 1.0,
self.x + self.width - 1.0,
self.y + self.height - 1.0,
);
ui::scrollbar(
batch,
atlas,
self.x + self.width,
self.y,
self.y + self.height,
self.content_height(),
self.scroll.amount,
);
if let Some(limit) = self.character_limit {
let count = crate::lang::tr(
"gui.multiLineEditBox.character_limit",
&[&self.chars.len(), &limit],
);
let width = atlas.font.width(&count);
batch.text(
atlas,
&count,
self.x + self.width - width,
self.y + self.height + 4.0,
rgba(160, 160, 160, 255),
true,
);
}
}
/// `MultiLineEditBox.extractContents` (the placeholder is empty).
fn draw_contents(&self, batch: &mut HudBatch, atlas: &HudAtlas) {
if self.chars.is_empty() && !self.focused {
return;
}
let font = &atlas.font;
let text_color = rgba(224, 224, 224, 255);
let cursor_color = rgba(208, 208, 208, 255);
let slice =
|begin: usize, end: usize| -> String { self.chars[begin..end].iter().collect() };
let show_cursor =
self.focused && (self.focused_at.elapsed().as_millis() / 300).is_multiple_of(2);
let needs_valid_cursor_pos = self.focused;
let insert_cursor = self.cursor < self.chars.len();
let (inner_left, mut draw_top) = (self.x + PADDING, self.y + PADDING - self.scroll.amount);
let (mut cursor_x, mut cursor_y) = (0.0f32, 0.0f32);
let mut has_drawn_cursor = false;
// The content is translated by the scroll amount; `within` compares
// untranslated tops, so it is given the line's top before the shift.
let shift = self.scroll.amount;
for &(begin, end) in &self.lines {
let within = self.within(draw_top + shift, draw_top + shift + LINE);
if !has_drawn_cursor
&& (needs_valid_cursor_pos || show_cursor)
&& insert_cursor
&& self.cursor >= begin
&& self.cursor <= end
{
let before = slice(begin, self.cursor);
let right = inner_left + font.width(&before);
(cursor_x, cursor_y) = (right, draw_top);
if within {
let after = slice(self.cursor, end);
batch.text(atlas, &before, inner_left, draw_top, text_color, true);
batch.text(atlas, &after, right, draw_top, text_color, true);
if show_cursor {
batch.fill(atlas, cursor_x, cursor_y - 1.0, 1.0, 11.0, cursor_color);
}
}
has_drawn_cursor = true;
} else {
let line = slice(begin, end);
if within {
batch.text(atlas, &line, inner_left, draw_top, text_color, true);
}
if (needs_valid_cursor_pos || show_cursor) && !insert_cursor {
cursor_x = inner_left + font.width(&line);
cursor_y = draw_top;
}
}
draw_top += LINE;
}
if show_cursor && !insert_cursor && self.within(cursor_y + shift, cursor_y + shift + LINE) {
batch.text(atlas, "_", cursor_x, cursor_y, cursor_color, true);
}
if self.has_selection() {
let (sel_begin, sel_end) = self.selected();
let draw_x = inner_left;
let mut draw_top = self.y + PADDING - self.scroll.amount;
for &(begin, end) in &self.lines {
if sel_begin > end {
draw_top += LINE;
continue;
}
if begin > sel_end {
break;
}
if self.within(draw_top + shift, draw_top + shift + LINE) {
let draw_begin = font.width(&slice(begin, sel_begin.max(begin)));
let draw_end = if sel_end > end {
self.width - PADDING
} else {
font.width(&slice(begin, sel_end))
};
batch.text_highlight(
atlas,
(draw_x + draw_begin, draw_top, draw_end - draw_begin, LINE),
true,
);
}
draw_top += LINE;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::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-multiline-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,
},
)
}
/// A box whose text is `chars` characters wide and `lines` lines tall.
fn edit(font: &Font, chars: usize, lines: usize) -> MultiLineEdit {
let advance = font.advance('a', &Style::default());
MultiLineEdit::new(
font,
0.0,
0.0,
chars as f32 * advance + 8.0,
LINE * lines as f32 + 8.0,
)
}
#[test]
fn lines_break_at_newlines_and_at_the_last_space_that_fits() {
let font = font();
let split = |text: &str, chars: usize| {
let advance = font.advance('a', &Style::default());
let text: Vec<char> = text.chars().collect();
split_ranges(&font, &text, chars as f32 * advance)
};
assert_eq!(split("abcd efgh", 4), [(0, 4), (5, 9)]);
// No space to break at: before the character that overflows.
assert_eq!(split("abcdefgh", 4), [(0, 4), (4, 8)]);
assert_eq!(split("ab\ncd", 4), [(0, 2), (3, 5)]);
// A trailing newline starts no line here; the text field adds it.
assert_eq!(split("ab\n", 4), [(0, 2)]);
assert_eq!(split("", 4), []);
}
#[test]
fn a_trailing_newline_gets_an_empty_last_line() {
let font = font();
let mut edit = edit(&font, 8, 4);
assert_eq!(edit.lines(), [(0, 0)]);
edit.insert_text(&font, "ab\n");
assert_eq!(edit.lines(), [(0, 2), (3, 3)]);
assert_eq!(edit.cursor(), 3);
}
#[test]
fn the_character_limit_cuts_what_is_typed_and_set() {
let font = font();
let mut edit = edit(&font, 8, 4);
edit.set_character_limit(5);
edit.set_value(&font, "abcdefgh");
assert_eq!(edit.value(), "abcde");
edit.key(&font, KeyCode::Backspace, false, false);
edit.insert_text(&font, "wxyz");
assert_eq!(edit.value(), "abcdw");
}
#[test]
fn the_line_limit_refuses_an_edit_that_adds_a_line() {
let font = font();
let mut edit = edit(&font, 8, 4);
edit.set_line_limit(2);
edit.set_value(&font, "a\nb");
assert_eq!(edit.value(), "a\nb");
// A third line, by a newline or by wrapping, changes nothing.
edit.key(&font, KeyCode::Enter, false, false);
edit.insert_text(&font, "\nc");
assert_eq!(edit.value(), "a\nb");
edit.insert_text(&font, " abcdefghijkl");
assert_eq!(edit.value(), "a\nb");
// A value over the limit is not set at all.
edit.set_value(&font, "1\n2\n3");
assert_eq!(edit.value(), "a\nb");
// A trailing newline counts as a line.
edit.set_value(&font, "a\n");
edit.insert_text(&font, "\n");
assert_eq!(edit.value(), "a\n");
}
#[test]
fn up_and_down_keep_the_column_and_home_and_end_stay_on_the_line() {
let font = font();
let mut edit = edit(&font, 8, 4);
edit.set_value(&font, "abcd\nef\nghij");
// From the end of `ghij` up to `ef`: the end of the shorter line.
edit.key(&font, KeyCode::ArrowUp, false, false);
assert_eq!(edit.cursor(), 7);
edit.key(&font, KeyCode::ArrowUp, false, false);
assert_eq!(edit.cursor(), 2);
edit.key(&font, KeyCode::Home, false, false);
assert_eq!(edit.cursor(), 0);
edit.key(&font, KeyCode::End, false, false);
assert_eq!(edit.cursor(), 4);
edit.key(&font, KeyCode::End, true, false);
assert_eq!(edit.cursor(), 12);
edit.key(&font, KeyCode::PageUp, false, false);
assert_eq!(edit.cursor(), 0);
}
#[test]
fn shift_selects_and_typing_replaces_the_selection() {
let font = font();
let mut edit = edit(&font, 8, 4);
edit.set_value(&font, "one two");
edit.key(&font, KeyCode::ArrowLeft, true, true);
assert_eq!(edit.selected_text(), "two");
edit.insert_text(&font, "2");
assert_eq!(edit.value(), "one 2");
edit.set_value(&font, "one two");
edit.key(&font, KeyCode::Backspace, true, false);
assert_eq!(edit.value(), "one ");
}
#[test]
fn the_box_scrolls_to_keep_the_cursor_in_view() {
let font = font();
let mut edit = edit(&font, 8, 2);
edit.set_value(&font, "1\n2\n3\n4\n5");
// Five lines in two lines' height: the end shows.
assert_eq!(edit.scroll.amount, 9.0 * 5.0 + 8.0 - edit.height);
edit.key(&font, KeyCode::PageUp, false, false);
assert_eq!(edit.scroll.amount, 0.0);
edit.wheel(-1.0);
assert_eq!(edit.scroll.amount, SCROLL_RATE);
}
#[test]
fn a_click_puts_the_cursor_on_the_line_and_character_under_it() {
let font = font();
let mut edit = edit(&font, 8, 4);
edit.set_value(&font, "abcd\nefgh");
let advance = font.advance('a', &Style::default());
// The second line, after two characters.
edit.click(
&font,
(4.0 + 2.0 * advance + 1.0, 4.0 + 9.0 + 1.0),
false,
false,
);
assert_eq!(edit.cursor(), 7);
// Shift extends the selection.
edit.click(&font, (4.0 + 1.0, 4.0 + 1.0), true, false);
assert_eq!(edit.selected_text(), "abcd\nef");
// A double click, after the plain click that starts it, selects the word.
edit.click(&font, (4.0 + 1.0, 4.0 + 1.0), false, false);
edit.click(&font, (4.0 + 1.0, 4.0 + 1.0), false, true);
assert_eq!(edit.selected_text(), "abcd");
}
}
File diff suppressed because it is too large. Load diff
@@ -1,124 +0,0 @@
// The built-in stand-ins for the vanilla post shaders a `post_effect` chain can
// name (`core/screenquad`, `post/rotscale`, `post/invert`, `post/blit`,
// `post/bits`, `post/color_convolve`, `post/box_blur`, `post/spiderclip`).
// Coordinates stay in the chain's own convention (v up from the bottom edge) and
// are flipped only where a texture is read.
// OutSize, InSize | BlurSize, menu blur radius.
@group(0) @binding(0) var<uniform> info: array<vec4<f32>, 2>;
// The vertex and fragment stage's uniform block, packed as std140.
@group(0) @binding(1) var<uniform> vs_cfg: array<vec4<f32>, 8>;
@group(0) @binding(2) var<uniform> fs_cfg: array<vec4<f32>, 8>;
@group(0) @binding(3) var in_tex: texture_2d<f32>;
@group(0) @binding(4) var in_smp: sampler;
@group(0) @binding(5) var blur_tex: texture_2d<f32>;
@group(0) @binding(6) var blur_smp: sampler;
struct Out {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) scaled: vec2<f32>,
}
fn vcf(i: u32) -> f32 {
return vs_cfg[i / 4u][i % 4u];
}
fn fcf(i: u32) -> f32 {
return fs_cfg[i / 4u][i % 4u];
}
fn read_in(uv: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(in_tex, in_smp, vec2(uv.x, 1.0 - uv.y), 0.0);
}
fn read_blur(uv: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(blur_tex, blur_smp, vec2(uv.x, 1.0 - uv.y), 0.0);
}
fn corner(i: u32) -> vec2<f32> {
return vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
}
@vertex fn vs_quad(@builtin(vertex_index) i: u32) -> Out {
let p = corner(i);
var out: Out;
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
out.uv = p;
out.scaled = p;
return out;
}
@vertex fn vs_rotscale(@builtin(vertex_index) i: u32) -> Out {
let p = corner(i);
var out: Out;
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
out.uv = p;
let radians = vcf(4u) * 0.0174532925;
let c = cos(radians);
let s = sin(radians);
let rotated = vec2(p.x * c - p.y * s, p.y * c + p.x * s);
out.scaled = rotated * vec2(vcf(0u), vcf(1u)) + vec2(vcf(2u), vcf(3u));
return out;
}
@fragment fn fs_invert(in: Out) -> @location(0) vec4<f32> {
let d = read_in(in.uv);
let mixed = mix(d, 1.0 - d, fcf(0u));
return vec4(mixed.rgb, 1.0);
}
@fragment fn fs_blit(in: Out) -> @location(0) vec4<f32> {
return read_in(in.uv) * vec4(fcf(0u), fcf(1u), fcf(2u), fcf(3u));
}
@fragment fn fs_bits(in: Out) -> @location(0) vec4<f32> {
let resolution = fcf(0u);
let mosaic_in = info[0].zw / fcf(1u);
let fract_pix = fract(in.uv * mosaic_in) / mosaic_in;
var base = read_in(in.uv - fract_pix);
let quantised = base.rgb - fract(base.rgb * resolution) / resolution;
let luma = dot(quantised, vec3(0.3, 0.59, 0.11));
let chroma = (quantised - luma) * 1.5;
return vec4(luma + chroma, 1.0);
}
@fragment fn fs_color_convolve(in: Out) -> @location(0) vec4<f32> {
let t = read_in(in.uv).rgb;
let red = dot(t, vec3(fcf(0u), fcf(1u), fcf(2u)));
let green = dot(t, vec3(fcf(4u), fcf(5u), fcf(6u)));
let blue = dot(t, vec3(fcf(8u), fcf(9u), fcf(10u)));
let rgb = vec3(red, green, blue);
let luma = dot(rgb, vec3(0.3, 0.59, 0.11));
return vec4((rgb - luma) * 1.8 + luma, 1.0);
}
@fragment fn fs_box_blur(in: Out) -> @location(0) vec4<f32> {
let step = (1.0 / info[0].zw) * vec2(fcf(0u), fcf(1u));
let configured = fcf(2u);
var radius = info[1].z;
if configured >= 0.5 {
radius = round(configured);
}
var blurred = vec4(0.0);
for (var a = -radius + 0.5; a <= radius; a += 2.0) {
blurred += read_in(in.uv + step * a);
}
blurred += read_in(in.uv + step * radius) / 2.0;
return blurred / (radius + 0.5);
}
@fragment fn fs_spiderclip(in: Out) -> @location(0) vec4<f32> {
let scaled_texel = read_in(in.scaled);
let blur_texel = read_blur(in.uv);
let scissor = vec4(fcf(0u), fcf(1u), fcf(2u), fcf(3u));
let vignette = vec4(fcf(4u), fcf(5u), fcf(6u), fcf(7u));
let s = in.scaled;
var o = scaled_texel;
if s.x < scissor.x { o = blur_texel; }
if s.y < scissor.y { o = blur_texel; }
if s.x > scissor.z { o = blur_texel; }
if s.y > scissor.w { o = blur_texel; }
if s.x < vignette.x { o = mix(blur_texel, o, (scissor.x - s.x) / (scissor.x - vignette.x)); }
if s.y < vignette.y { o = mix(blur_texel, o, (scissor.y - s.y) / (scissor.y - vignette.y)); }
if s.x > vignette.z { o = mix(blur_texel, o, (scissor.z - s.x) / (scissor.z - vignette.z)); }
if s.y > vignette.w { o = mix(blur_texel, o, (scissor.w - s.y) / (scissor.w - vignette.w)); }
return vec4(o.rgb, 1.0);
}
@@ -1,119 +0,0 @@
//! `PotentSulfurBlockEntity`'s reads of the level: where the noxious gas of a
//! potent sulfur block comes out, how far a geyser throws, and whether the gas
//! reaches a point. The client's particles and the server's nausea and
//! launches read the level the same way, through a [`ParticleLevel`].
use crate::{blocks::Fluid, collisions::SceneCollisions, particles::ParticleLevel};
use horizon_core::{
geometry::{Vec3, traverse_blocks},
position::BlockPos,
};
/// `PotentSulfurBlock.ALLOWED_WATER_BLOCKS_ABOVE`.
const ALLOWED_WATER_BLOCKS_ABOVE: i32 = 4;
/// `PotentSulfurBlockEntity.isGeyserPassableBlock`: air, water, or a block
/// with no collision shape.
pub fn is_geyser_passable_block(level: &ParticleLevel, pos: [i32; 3]) -> bool {
let state = level.world.block(pos[0], pos[1], pos[2]);
if level.facts.is_air(state) || &*level.facts.get(state).name == "minecraft:water" {
return true;
}
let mut scene = SceneCollisions {
world: level.world,
binding: level.collision,
subject: None,
};
match level.collision.collision_shape(&mut scene, state, pos) {
Ok(shape) => shape.is_empty(),
Err(_) => !level.facts.get(state).full_collision,
}
}
/// `PotentSulfurBlockEntity.isWater`: the block at `pos` holds a water source
/// (`FluidState.isSourceOfType`).
fn is_water_source(level: &ParticleLevel, pos: [i32; 3]) -> bool {
let (fluid, source) = level.fluid_source(pos);
fluid == Fluid::Water && source
}
/// `PotentSulfurBlockEntity.findNoxiousGasSourceBlock`: the first block above
/// the sulfur, within the water column's reach, that is not water-filled and
/// lets gas through; None when something solid or a deeper column stops it.
pub fn find_noxious_gas_source_block(level: &ParticleLevel, origin: [i32; 3]) -> Option<[i32; 3]> {
let max_y = origin[1] + ALLOWED_WATER_BLOCKS_ABOVE + 1;
let mut pos = [origin[0], origin[1] + 1, origin[2]];
while pos[1] <= max_y {
let state = level.world.block(pos[0], pos[1], pos[2]);
let is_water_block = &*level.facts.get(state).name == "minecraft:water";
if !is_water_source(level, pos)
|| (!is_water_block && !is_geyser_passable_block(level, pos))
{
if level.facts.is_air(state) || is_geyser_passable_block(level, pos) {
return Some(pos);
}
break;
}
pos[1] += 1;
}
None
}
/// `PotentSulfurBlockEntity.getUnobstructedBlockCount`: how many blocks from
/// `pos` up, at most six per water block, a geyser's push goes through.
pub fn unobstructed_block_count(level: &ParticleLevel, pos: [i32; 3], water_blocks: i32) -> i32 {
let geyser_force_height = 6 * water_blocks;
for i in 0..geyser_force_height {
if !is_geyser_passable_block(level, [pos[0], pos[1] + i, pos[2]]) {
return i;
}
}
geyser_force_height
}
/// `PotentSulfurBlockEntity.canBeReachedByNoxiousGas`: `pos` is in a block gas
/// can enter, within three blocks of the source block's centre, and above
/// water the source's water can be seen from.
pub fn can_be_reached_by_noxious_gas(
level: &ParticleLevel,
source_block: [i32; 3],
pos: [f64; 3],
) -> bool {
let block = ParticleLevel::block_at(pos);
if !is_geyser_passable_block(level, block) {
return false;
}
let center = source_block.map(|c| f64::from(c) + 0.5);
let distance_sqr =
(center[0] - pos[0]).powi(2) + (center[1] - pos[1]).powi(2) + (center[2] - pos[2]).powi(2);
if distance_sqr > 9.0 {
return false;
}
let below_source = [center[0], f64::from(source_block[1] - 1) + 0.5, center[2]];
let below_pos = [pos[0], pos[1] - 1.0, pos[2]];
is_water_source(level, ParticleLevel::block_at(below_pos))
&& have_line_of_sight(level, below_source, below_pos)
}
/// `PotentSulfurBlockEntity.haveLineOfSight`: a clip over collider shapes and
/// no fluids (as the mobs' line of sight does) finds no block between the
/// points.
fn have_line_of_sight(level: &ParticleLevel, a: [f64; 3], b: [f64; 3]) -> bool {
let (from, to) = (Vec3::new(a[0], a[1], a[2]), Vec3::new(b[0], b[1], b[2]));
let mut scene = SceneCollisions {
world: level.world,
binding: level.collision,
subject: None,
};
let hit = traverse_blocks(from, to, 512, |p: BlockPos| {
let state = level.world.block(p.x, p.y, p.z);
if level.facts.is_air(state) {
return None;
}
let shape = level
.collision
.collision_shape(&mut scene, state, [p.x, p.y, p.z])
.ok()?;
shape.clip(from, to, p).map(|_| ())
});
!matches!(hit, Ok(Some(())))
}
@@ -1,164 +0,0 @@
//! Sets of section indexes in a chunk column, a bit per section.
//!
//! Vanilla's tallest level has 254 sections (`DimensionType.Y_SIZE / 16`), and
//! light data adds a section below and above it: 256 bits hold every layout a
//! dimension type allows.
/// Section indexes of one column, 0 being the lowest.
#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct SectionMask([u64; 4]);
impl SectionMask {
pub const CAPACITY: usize = 256;
pub const EMPTY: Self = Self([0; 4]);
pub const ALL: Self = Self([u64::MAX; 4]);
/// The indexes `0..n`.
pub const fn below(n: usize) -> Self {
let mut words = [0; 4];
let mut w = 0;
while w < 4 {
let bits = n.saturating_sub(w * 64);
words[w] = if bits >= 64 {
u64::MAX
} else {
(1 << bits) - 1
};
w += 1;
}
Self(words)
}
pub fn single(i: usize) -> Self {
let mut mask = Self::EMPTY;
mask.insert(i);
mask
}
#[inline]
pub fn contains(&self, i: usize) -> bool {
i < Self::CAPACITY && self.0[i >> 6] >> (i & 63) & 1 != 0
}
#[inline]
pub fn insert(&mut self, i: usize) {
self.0[i >> 6] |= 1 << (i & 63);
}
#[inline]
pub fn remove(&mut self, i: usize) {
self.0[i >> 6] &= !(1 << (i & 63));
}
pub fn is_empty(&self) -> bool {
self.0 == [0; 4]
}
pub fn len(&self) -> usize {
self.0.iter().map(|w| w.count_ones() as usize).sum()
}
/// The indexes from `i` up.
pub fn from(self, i: usize) -> Self {
self & !Self::below(i)
}
/// The indexes, lowest first.
pub fn iter(self) -> Indexes {
Indexes(self)
}
}
impl std::ops::BitOr for SectionMask {
type Output = Self;
fn bitor(self, other: Self) -> Self {
Self(std::array::from_fn(|w| self.0[w] | other.0[w]))
}
}
impl std::ops::BitOrAssign for SectionMask {
fn bitor_assign(&mut self, other: Self) {
*self = *self | other;
}
}
impl std::ops::BitAnd for SectionMask {
type Output = Self;
fn bitand(self, other: Self) -> Self {
Self(std::array::from_fn(|w| self.0[w] & other.0[w]))
}
}
impl std::ops::Not for SectionMask {
type Output = Self;
fn not(self) -> Self {
Self(self.0.map(|w| !w))
}
}
impl std::fmt::Debug for SectionMask {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_set().entries(self.iter()).finish()
}
}
impl FromIterator<usize> for SectionMask {
fn from_iter<I: IntoIterator<Item = usize>>(indexes: I) -> Self {
let mut mask = Self::EMPTY;
for i in indexes {
mask.insert(i);
}
mask
}
}
/// `SectionMask::iter`: the set's indexes in ascending order.
#[derive(Clone, Copy, Debug)]
pub struct Indexes(SectionMask);
impl Iterator for Indexes {
type Item = usize;
#[inline]
fn next(&mut self) -> Option<usize> {
let words = &mut (self.0).0;
let w = words.iter().position(|&w| w != 0)?;
let bit = words[w].trailing_zeros() as usize;
words[w] &= words[w] - 1;
Some(w * 64 + bit)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.0.len();
(len, Some(len))
}
}
impl ExactSizeIterator for Indexes {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sets_across_words() {
let mut mask = SectionMask::EMPTY;
for i in [0, 23, 63, 64, 130, 255] {
mask.insert(i);
}
assert_eq!(mask.iter().collect::<Vec<_>>(), [0, 23, 63, 64, 130, 255]);
assert_eq!(mask.len(), 6);
assert!(mask.contains(130) && !mask.contains(131) && !mask.contains(300));
mask.remove(64);
assert_eq!(mask.from(24).iter().collect::<Vec<_>>(), [63, 130, 255]);
assert_eq!(mask.from(256), SectionMask::EMPTY);
assert_eq!(mask.from(0), mask);
assert!(SectionMask::EMPTY.is_empty() && !mask.is_empty());
}
#[test]
fn below_counts_whole_and_partial_words() {
for n in [0, 1, 24, 63, 64, 65, 131, 254, 256] {
let mask = SectionMask::below(n);
assert_eq!(mask.len(), n);
assert_eq!(mask.iter().collect::<Vec<_>>(), (0..n).collect::<Vec<_>>());
}
assert_eq!(SectionMask::below(1000), SectionMask::ALL);
}
#[test]
fn operators() {
let a: SectionMask = [1, 70, 200].into_iter().collect();
let b: SectionMask = [70, 3].into_iter().collect();
assert_eq!((a | b).iter().collect::<Vec<_>>(), [1, 3, 70, 200]);
assert_eq!((a & b).iter().collect::<Vec<_>>(), [70]);
assert_eq!(
(!a & SectionMask::below(4)).iter().collect::<Vec<_>>(),
[0, 2, 3]
);
assert_eq!(format!("{a:?}"), "{1, 70, 200}");
}
}
@@ -1,179 +0,0 @@
//! `SoundPreviewHandler`: the sound a category volume slider plays while it
//! moves on the title screen's options (`Options.createSoundSliderOptionInstance`
//! calls `preview` when there is no level).
use crate::settings::SOUND_SOURCES;
use crate::sound_engine::{InstanceId, SoundEngine, SoundInstance, Sounds};
/// The sound `SoundPreviewHandler.preview` plays for a `SoundSource` index,
/// or `None` (`SoundEvents.EMPTY`) for master, music and voice.
pub fn preview_event(source: usize) -> Option<&'static str> {
Some(match *SOUND_SOURCES.get(source)? {
"record" => "minecraft:block.note_block.guitar",
"weather" => "minecraft:entity.lightning_bolt.thunder",
"block" => "minecraft:block.grass.place",
"hostile" => "minecraft:entity.zombie.ambient",
// SoundEvents.COW_SOUNDS.get(CowSoundVariants.SoundSet.CLASSIC).ambientSound()
"neutral" => "minecraft:entity.cow.ambient",
"player" => "minecraft:entity.generic.eat",
"ambient" => "minecraft:ambient.cave",
"ui" => "minecraft:ui.button.click",
_ => return None,
})
}
/// `SoundPreviewHandler`'s `activePreview` and `previousCategory`.
#[derive(Debug, Default)]
pub struct SoundPreview {
active: Option<InstanceId>,
previous: Option<usize>,
}
impl SoundPreview {
/// `SoundPreviewHandler.preview(soundManager, category, volume)`: stop the
/// preview of another category, then, unless the last preview still
/// plays, play this category's sound (`SimpleSoundInstance.forUI` at
/// pitch 1 and the slider's volume).
pub fn preview(&mut self, sounds: &mut impl Sounds, source: usize, volume: f32) {
self.stop_other_category_preview(sounds, source);
if !self.can_play_sound(sounds) {
return;
}
let Some(event) = preview_event(source) else {
return;
};
if let Some(old) = self.active.take() {
sounds.release(old);
}
let instance = SoundInstance::for_ui(event, 1.0, volume, SoundEngine::unseeded());
self.active = Some(sounds.play_instance(instance, true).0);
}
/// The preview playing now, if any.
pub fn active(&self) -> Option<InstanceId> {
self.active
}
/// `stopOtherCategoryPreview`.
fn stop_other_category_preview(&mut self, sounds: &mut impl Sounds, source: usize) {
if self.previous != Some(source) {
self.previous = Some(source);
if let Some(active) = self.active {
sounds.stop_instance(active);
}
}
}
/// `canPlaySound`: no preview yet, or the last one has finished.
fn can_play_sound(&self, sounds: &mut impl Sounds) -> bool {
self.active.is_none_or(|active| !sounds.is_active(active))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::sound_engine::{Bound, TickContext, UI, test_backend::Null};
use crate::sound_events::SoundRegistry;
fn engine() -> SoundEngine {
let mut registry = SoundRegistry::default();
registry.add_file(
"minecraft",
br#"{"entity.zombie.ambient": {"sounds": ["mob/zombie/say1"]},
"entity.cow.ambient": {"sounds": ["mob/cow/say1"]},
"ui.button.click": {"sounds": ["random/click"]}}"#,
&|_, _| true,
);
SoundEngine::new(registry)
}
fn source(name: &str) -> usize {
SOUND_SOURCES.iter().position(|s| *s == name).unwrap()
}
#[test]
fn each_category_previews_its_vanilla_sound() {
let expected = [
("master", None),
("music", None),
("record", Some("minecraft:block.note_block.guitar")),
("weather", Some("minecraft:entity.lightning_bolt.thunder")),
("block", Some("minecraft:block.grass.place")),
("hostile", Some("minecraft:entity.zombie.ambient")),
("neutral", Some("minecraft:entity.cow.ambient")),
("player", Some("minecraft:entity.generic.eat")),
("ambient", Some("minecraft:ambient.cave")),
("voice", None),
("ui", Some("minecraft:ui.button.click")),
];
for (name, event) in expected {
assert_eq!(preview_event(source(name)), event, "{name}");
}
}
fn slide(
preview: &mut SoundPreview,
engine: &mut SoundEngine,
backend: &mut Null,
name: &str,
volume: f32,
) {
preview.preview(&mut Bound { engine, backend }, source(name), volume);
}
/// Ticks enough for the engine to drop finished or stopped channels.
fn settle(engine: &mut SoundEngine, backend: &mut Null) {
for _ in 0..40 {
engine.tick(false, &TickContext::default(), backend);
}
}
#[test]
fn a_moving_slider_plays_one_preview_at_a_time_and_switching_stops_it() {
let (mut engine, mut backend) = (engine(), Null::default());
let mut preview = SoundPreview::default();
slide(&mut preview, &mut engine, &mut backend, "hostile", 0.4);
let first = preview
.active()
.expect("the hostile slider plays a preview");
let instance = engine.instance(first).unwrap();
assert_eq!(instance.identifier, "minecraft:entity.zombie.ambient");
assert_eq!(instance.source, UI);
assert_eq!((instance.volume, instance.pitch), (0.4, 1.0));
assert!(instance.relative);
assert!(engine.is_active(first));
// canPlaySound: still playing, so dragging further does not restart it.
slide(&mut preview, &mut engine, &mut backend, "hostile", 0.6);
assert_eq!(preview.active(), Some(first));
assert_eq!(engine.active_instances(), vec![first]);
// Once it has finished, the next move plays it again.
for stopped in backend.stopped.values_mut() {
*stopped = true;
}
settle(&mut engine, &mut backend);
assert!(!engine.is_active(first));
slide(&mut preview, &mut engine, &mut backend, "hostile", 0.6);
let second = preview.active().unwrap();
assert_ne!(second, first);
assert!(engine.is_active(second));
// Another category stops the playing preview (SoundManager.stop); the
// engine lets its channel go on the next ticks, then that category's
// own sound plays.
slide(&mut preview, &mut engine, &mut backend, "neutral", 1.0);
assert!(backend.stopped.values().all(|stopped| *stopped));
settle(&mut engine, &mut backend);
assert!(engine.active_instances().is_empty());
slide(&mut preview, &mut engine, &mut backend, "neutral", 1.0);
let third = preview.active().unwrap();
assert_eq!(
engine.instance(third).unwrap().identifier,
"minecraft:entity.cow.ambient"
);
// Master has no sound but still stops the other category's preview.
slide(&mut preview, &mut engine, &mut backend, "master", 1.0);
settle(&mut engine, &mut backend);
assert!(engine.active_instances().is_empty());
slide(&mut preview, &mut engine, &mut backend, "master", 1.0);
assert!(engine.active_instances().is_empty());
}
}
@@ -1,272 +0,0 @@
//! Splitscreen's layout, pure data tested without a window: where each player's view goes in
//! its window (`place`).
use winit::dpi::PhysicalSize;
/// Players at most: P1 and fifteen more.
pub const MAX_PLAYERS: usize = 16;
/// A player's view: its window (an index into the windows), its corner there and its size.
pub type View = (usize, [u32; 2], PhysicalSize<u32>);
/// Rows of five to sixteen players sharing a window, widest first (columns on a tall window): every
/// view stays near a screen's shape, where a full grid would leave a long thin one.
const ROWS: [&[u32]; MAX_PLAYERS - 4] = [
&[3, 2],
&[3, 3],
&[3, 2, 2],
&[3, 3, 2],
&[3, 3, 3],
&[4, 3, 3],
&[4, 4, 3],
&[4, 4, 4],
&[4, 3, 3, 3],
&[4, 4, 3, 3],
&[4, 4, 4, 3],
&[4, 4, 4, 4],
];
/// `order` made a whole order of `n` players: those it names (once, if there are), then the
/// others, P1 first.
pub fn ordered(order: &[usize], n: usize) -> Vec<usize> {
let mut out: Vec<usize> = Vec::with_capacity(n);
for &i in order {
if i < n && !out.contains(&i) {
out.push(i);
}
}
out.extend((0..n).filter(|i| !order.contains(i)));
out
}
/// `place` with the players sharing a window in `order` (`ordered`): the first left or on top.
/// The views are still by player.
pub fn place_ordered(
windows: &[usize],
order: &[usize],
sizes: &[PhysicalSize<u32>],
two: u8,
three: u8,
) -> Vec<View> {
let order = ordered(order, windows.len());
let in_order: Vec<usize> = order.iter().map(|&i| windows[i]).collect();
let placed = place(&in_order, sizes, two, three);
let mut views = placed.clone();
for (k, &i) in order.iter().enumerate() {
views[i] = placed[k];
}
views
}
/// Each player's view, given the window each is in and the windows' sizes. Players in one window
/// share it in the order they come: two take halves (`two`: 0 side by side when wider than
/// tall, 1 side by side, 2 top and bottom); three (`three`: 0 the first wide on top and two below,
/// 1 the first tall on the left and two on the right, 2 three columns); four its quarters; five
/// to sixteen in balanced rows (`ROWS`).
pub fn place(windows: &[usize], sizes: &[PhysicalSize<u32>], two: u8, three: u8) -> Vec<View> {
windows
.iter()
.enumerate()
.map(|(i, &window)| {
let here = windows.iter().filter(|&&w| w == window).count();
let slot = windows[..i].iter().filter(|&&w| w == window).count() as u32;
let size = sizes
.get(window)
.copied()
.unwrap_or(PhysicalSize::new(1, 1));
let (w, h) = (size.width, size.height);
let side_by_side = match two {
1 => true,
2 => false,
_ => w >= h,
};
// The view's cell as fractions of the window: (x0, x1, y0, y1) in halves or thirds.
let cell = |x0: u32, x1: u32, y0: u32, y1: u32, of: u32| {
[w * x0 / of, w * x1 / of, h * y0 / of, h * y1 / of]
};
let [x0, x1, y0, y1] = match (here, slot) {
(1, _) => cell(0, 1, 0, 1, 1),
(2, s) if side_by_side => cell(s, s + 1, 0, 2, 2),
(2, s) => cell(0, 2, s, s + 1, 2),
(3, s) => match (three, s) {
(2, s) => cell(s, s + 1, 0, 3, 3),
(1, 0) => cell(0, 1, 0, 2, 2),
(1, s) => cell(1, 2, s - 1, s, 2),
(_, 0) => cell(0, 2, 0, 1, 2),
(_, s) => cell(s - 1, s, 1, 2, 2),
},
(4, s) => cell(s % 2, s % 2 + 1, s / 2, s / 2 + 1, 2),
(n, s) => rows(n, s, w, h),
};
(
window,
[x0, y0],
PhysicalSize::new((x1 - x0).max(1), (y1 - y0).max(1)),
)
})
.collect()
}
/// Five to sixteen players: `slot`'s cell `[x0, x1, y0, y1]` in balanced rows (`ROWS`), or
/// in columns when the window is taller than wide.
fn rows(n: usize, slot: u32, w: u32, h: u32) -> [u32; 4] {
let counts = ROWS[n.clamp(5, MAX_PLAYERS) - 5];
let bands = counts.len() as u32;
let (mut band, mut k) = (0, slot);
while band + 1 < bands && k >= counts[band as usize] {
k -= counts[band as usize];
band += 1;
}
let across = counts[band as usize];
// Along: the long side, divided between a band's views; down: the bands.
let (along, down) = if w >= h { (w, h) } else { (h, w) };
let (a0, a1) = (along * k / across, along * (k + 1) / across);
let (d0, d1) = (down * band / bands, down * (band + 1) / bands);
if w >= h {
[a0, a1, d0, d1]
} else {
[d0, d1, a0, a1]
}
}
#[cfg(test)]
mod tests {
use super::*;
fn size(w: u32, h: u32) -> PhysicalSize<u32> {
PhysicalSize::new(w, h)
}
#[test]
fn players_on_one_screen_share_it() {
let wide = [size(1920, 1080)];
assert_eq!(
place(&[0, 0], &wide, 0, 0)[1],
(0, [960, 0], size(960, 1080))
);
assert_eq!(
place(&[0, 0], &wide, 2, 0)[1],
(0, [0, 540], size(1920, 540))
);
// Auto on a tall screen: top and bottom.
assert_eq!(place(&[0, 0], &[size(1080, 1920)], 0, 0)[1].1, [0, 960]);
assert_eq!(
place(&[0; 4], &wide, 0, 0)[3],
(0, [960, 540], size(960, 540))
);
}
#[test]
fn desk_and_couch() {
// P1 alone at the desk; P2 and P3 share the TV.
let screens = [size(3024, 1964), size(3840, 2160)];
let views = place(&[0, 1, 1], &screens, 0, 0);
assert_eq!(views[0], (0, [0, 0], size(3024, 1964)));
assert_eq!(views[1], (1, [0, 0], size(1920, 2160)));
assert_eq!(views[2], (1, [1920, 0], size(1920, 2160)));
}
#[test]
fn three_on_a_screen() {
let tv = [size(1920, 1080)];
// One wide on top, two below.
let top = place(&[0; 3], &tv, 0, 0);
assert_eq!(top[0], (0, [0, 0], size(1920, 540)));
assert_eq!(top[2], (0, [960, 540], size(960, 540)));
// One tall on the left, two stacked on the right.
let left = place(&[0; 3], &tv, 0, 1);
assert_eq!(left[0], (0, [0, 0], size(960, 1080)));
assert_eq!(left[2], (0, [960, 540], size(960, 540)));
// Three columns.
assert_eq!(
place(&[0; 3], &tv, 0, 2)[2],
(0, [1280, 0], size(640, 1080))
);
}
#[test]
fn two_windows_two_players_each() {
// P1 and P2 at the desk, P3 and P4 on the TV: halves in each window.
let screens = [size(3024, 1964), size(3840, 2160)];
let views = place(&[0, 0, 1, 1], &screens, 0, 0);
assert_eq!(views[1], (0, [1512, 0], size(1512, 1964)));
assert_eq!(views[2], (1, [0, 0], size(1920, 2160)));
assert_eq!(views[3], (1, [1920, 0], size(1920, 2160)));
}
#[test]
fn five_to_eight_in_rows_of_three_and_two() {
let tv = [size(1920, 1080)];
let eight = place(&[0; 8], &tv, 0, 0);
assert_eq!(eight[0], (0, [0, 0], size(640, 360)));
assert_eq!(eight[5], (0, [1280, 360], size(640, 360)));
assert_eq!(eight[7], (0, [960, 720], size(960, 360)));
let seven = place(&[0; 7], &tv, 0, 0);
assert_eq!(seven[3], (0, [0, 360], size(960, 360)));
// Every count tiles the window exactly: no gap, no overlap.
for n in 5..=MAX_PLAYERS {
for screen in [size(1920, 1080), size(1080, 1920), size(1711, 997)] {
let views = place(&vec![0; n], &[screen], 0, 0);
for (i, (_, [x, y], size)) in views.iter().enumerate() {
assert!(x + size.width <= screen.width && y + size.height <= screen.height);
for (_, [ox, oy], other) in &views[..i] {
assert!(
x + size.width <= *ox
|| ox + other.width <= *x
|| y + size.height <= *oy
|| oy + other.height <= *y,
"overlapping views for {n} in {screen:?}"
);
}
}
let area: u64 = views
.iter()
.map(|v| u64::from(v.2.width) * u64::from(v.2.height))
.sum();
assert_eq!(
area,
u64::from(screen.width) * u64::from(screen.height),
"{n} in {screen:?}"
);
}
}
// A tall window: columns.
let tall = place(&[0; 5], &[size(1080, 1920)], 0, 0);
assert_eq!(tall[0], (0, [0, 0], size(540, 640)));
assert_eq!(tall[4], (0, [540, 960], size(540, 960)));
}
#[test]
fn sixteen_players_form_a_four_by_four_grid() {
let views = place(&[0; 16], &[size(3840, 2160)], 0, 0);
for (i, view) in views.iter().enumerate() {
assert_eq!(
*view,
(
0,
[(i as u32 % 4) * 960, (i as u32 / 4) * 540],
size(960, 540)
)
);
}
}
#[test]
fn an_order_names_each_player_once_and_the_others_come_last() {
assert_eq!(ordered(&[], 3), [0, 1, 2]);
assert_eq!(ordered(&[2, 0], 3), [2, 0, 1]);
// Gone players and repeats are dropped.
assert_eq!(ordered(&[5, 1, 1], 3), [1, 0, 2]);
}
#[test]
fn players_sharing_a_window_fill_it_in_their_order() {
let wide = [size(2000, 1000)];
// P2 first: P2 on the left, P1 on the right.
let views = place_ordered(&[0, 0], &[1, 0], &wide, 0, 0);
assert_eq!(views[1].1, [0, 0]);
assert_eq!(views[0].1, [1000, 0]);
// P3 first of three: the wide view on top is P3's.
let views = place_ordered(&[0, 0, 0], &[2], &wide, 0, 0);
assert_eq!(views[2].2, size(2000, 500));
}
}
@@ -1,345 +0,0 @@
//! Decoded block sprites kept on disk between launches (M-11): reading and
//! decoding ~1300 small PNGs is most of `Sprites::load`. One file per resource
//! root, valid only while the `textures` trees still have the same paths,
//! sizes and modification times and the format version is the same; anything
//! else (missing, corrupt, stale, unwritable) means the normal decoding path.
use crate::mipmap::Strategy;
use std::{
collections::HashMap,
fs,
hash::{DefaultHasher, Hash, Hasher},
path::{Path, PathBuf},
};
const MAGIC: &[u8; 4] = b"HSPR";
/// Bump when `Decoded` or the decoding in `Sprites::decode` changes.
const VERSION: u32 = 1;
const FILE: &str = "horizon-sprites.cache";
/// What decoding one texture gives, before it takes a layer.
#[derive(Clone)]
pub(crate) struct Decoded {
pub side: u32,
pub frames: Vec<Vec<u8>>,
/// The `.mcmeta` `animation` value, as text.
pub animation: Option<String>,
pub strategy: Strategy,
pub alpha_cutoff_bias: f32,
pub has_transparent: bool,
pub opaque: bool,
pub translucent: bool,
}
pub(crate) struct SpriteCache {
path: PathBuf,
fingerprint: u64,
entries: HashMap<String, Decoded>,
dirty: bool,
}
/// Paths, sizes and modification times of every file under `assets/*/textures`,
/// summed so the directory order does not matter.
fn fingerprint(root: &Path) -> Option<u64> {
fn walk(dir: &Path, base: &Path, sum: &mut u64) -> Option<()> {
for entry in fs::read_dir(dir).ok()? {
let entry = entry.ok()?;
let meta = entry.metadata().ok()?;
if meta.is_dir() {
walk(&entry.path(), base, sum)?;
continue;
}
let mut hasher = DefaultHasher::new();
entry.path().strip_prefix(base).ok()?.hash(&mut hasher);
meta.len().hash(&mut hasher);
meta.modified().ok()?.hash(&mut hasher);
*sum = sum.wrapping_add(hasher.finish());
}
Some(())
}
let mut sum = 0;
for namespace in fs::read_dir(root.join("assets")).ok()? {
let textures = namespace.ok()?.path().join("textures");
if textures.is_dir() {
walk(&textures, root, &mut sum)?;
}
}
Some(sum)
}
impl SpriteCache {
/// The cache of `root`: its stored entries when still valid, else empty.
/// `None` when the textures cannot be fingerprinted (no caching then).
pub fn open(root: &Path) -> Option<Self> {
let fingerprint = fingerprint(root)?;
let path = root.join(FILE);
let entries = fs::read(&path)
.ok()
.and_then(|bytes| parse(&bytes, fingerprint))
.unwrap_or_default();
Some(Self {
path,
fingerprint,
entries,
dirty: false,
})
}
pub fn get(&self, name: &str) -> Option<&Decoded> {
self.entries.get(name)
}
pub fn insert(&mut self, name: &str, decoded: Decoded) {
self.entries.insert(name.to_owned(), decoded);
self.dirty = true;
}
/// Write new entries; a failure only costs the next launch the decoding.
pub fn save(&mut self) {
if !self.dirty {
return;
}
self.dirty = false;
let temporary = self
.path
.with_extension(format!("{}.tmp", std::process::id()));
if fs::write(&temporary, serialize(self.fingerprint, &self.entries)).is_ok()
&& fs::rename(&temporary, &self.path).is_err()
{
let _ = fs::remove_file(&temporary);
}
}
}
fn serialize(fingerprint: u64, entries: &HashMap<String, Decoded>) -> Vec<u8> {
let mut out = Vec::new();
out.extend_from_slice(MAGIC);
out.extend_from_slice(&VERSION.to_le_bytes());
out.extend_from_slice(&fingerprint.to_le_bytes());
out.extend_from_slice(&(entries.len() as u32).to_le_bytes());
for (name, d) in entries {
put_bytes(&mut out, name.as_bytes());
out.extend_from_slice(&d.side.to_le_bytes());
out.extend_from_slice(&(d.frames.len() as u32).to_le_bytes());
for frame in &d.frames {
put_bytes(&mut out, frame);
}
put_bytes(&mut out, d.animation.as_deref().unwrap_or("").as_bytes());
out.push(u8::from(d.animation.is_some()));
out.push(d.strategy as u8);
out.extend_from_slice(&d.alpha_cutoff_bias.to_bits().to_le_bytes());
out.push(
u8::from(d.has_transparent) | u8::from(d.opaque) << 1 | u8::from(d.translucent) << 2,
);
}
out
}
fn put_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
out.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
out.extend_from_slice(bytes);
}
struct Reader<'a>(&'a [u8]);
impl<'a> Reader<'a> {
fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let (head, tail) = self.0.split_at_checked(n)?;
self.0 = tail;
Some(head)
}
fn u32(&mut self) -> Option<u32> {
Some(u32::from_le_bytes(self.take(4)?.try_into().ok()?))
}
fn bytes(&mut self) -> Option<&'a [u8]> {
let n = self.u32()? as usize;
self.take(n)
}
}
fn parse(bytes: &[u8], fingerprint: u64) -> Option<HashMap<String, Decoded>> {
let mut r = Reader(bytes);
if r.take(4)? != MAGIC || r.u32()? != VERSION {
return None;
}
if u64::from_le_bytes(r.take(8)?.try_into().ok()?) != fingerprint {
return None;
}
let count = r.u32()?;
let mut entries = HashMap::new();
for _ in 0..count {
let name = String::from_utf8(r.bytes()?.to_vec()).ok()?;
let side = r.u32()?;
let frame_count = r.u32()?;
let mut frames = Vec::new();
for _ in 0..frame_count {
frames.push(r.bytes()?.to_vec());
}
let animation = String::from_utf8(r.bytes()?.to_vec()).ok()?;
let has_animation = r.take(1)?[0] != 0;
let strategy = match r.take(1)?[0] {
0 => Strategy::Auto,
1 => Strategy::Mean,
2 => Strategy::Cutout,
3 => Strategy::StrictCutout,
4 => Strategy::DarkCutout,
_ => return None,
};
let alpha_cutoff_bias = f32::from_bits(r.u32()?);
let flags = r.take(1)?[0];
let frame_len = (side as usize).checked_mul(side as usize)?.checked_mul(4)?;
if frames.is_empty() || frames.iter().any(|f| f.len() != frame_len) {
return None;
}
entries.insert(
name,
Decoded {
side,
frames,
animation: has_animation.then_some(animation),
strategy,
alpha_cutoff_bias,
has_transparent: flags & 1 != 0,
opaque: flags & 2 != 0,
translucent: flags & 4 != 0,
},
);
}
r.0.is_empty().then_some(entries)
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(blue: u8, animation: Option<&str>) -> Decoded {
Decoded {
side: 2,
frames: vec![vec![blue; 16], vec![blue + 1; 16]],
animation: animation.map(str::to_owned),
strategy: Strategy::Cutout,
alpha_cutoff_bias: 0.25,
has_transparent: true,
opaque: false,
translucent: true,
}
}
fn scratch(tag: &str) -> PathBuf {
let dir =
std::env::temp_dir().join(format!("horizon-sprite-cache-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(dir.join("assets/minecraft/textures/block")).unwrap();
dir
}
#[test]
fn round_trips() {
let mut entries = HashMap::new();
entries.insert("a:b".to_owned(), sample(1, Some("{\"frametime\":2}")));
entries.insert("a:c".to_owned(), sample(9, None));
let back = parse(&serialize(7, &entries), 7).unwrap();
for (name, d) in &entries {
let e = &back[name];
assert_eq!(
(d.side, &d.frames, &d.animation),
(e.side, &e.frames, &e.animation)
);
assert_eq!(d.alpha_cutoff_bias, e.alpha_cutoff_bias);
assert_eq!(
(d.has_transparent, d.opaque, d.translucent, d.strategy as u8),
(e.has_transparent, e.opaque, e.translucent, e.strategy as u8)
);
}
}
#[test]
fn wrong_fingerprint_truncation_and_garbage_are_misses() {
let mut entries = HashMap::new();
entries.insert("a:b".to_owned(), sample(1, None));
let bytes = serialize(7, &entries);
assert!(parse(&bytes, 8).is_none());
for cut in 0..bytes.len() {
assert!(parse(&bytes[..cut], 7).is_none(), "cut {cut}");
}
assert!(parse(b"garbage", 7).is_none());
let mut extra = bytes.clone();
extra.push(0);
assert!(parse(&extra, 7).is_none());
}
#[test]
fn changed_texture_invalidates_and_corrupt_file_is_ignored() {
let root = scratch("invalidate");
let png = root.join("assets/minecraft/textures/block/x.png");
fs::write(&png, b"one").unwrap();
let mut cache = SpriteCache::open(&root).unwrap();
cache.insert("minecraft:block/x", sample(1, None));
cache.save();
assert!(
SpriteCache::open(&root)
.unwrap()
.get("minecraft:block/x")
.is_some()
);
// Same length, new content and time: still stale.
std::thread::sleep(std::time::Duration::from_millis(30));
fs::write(&png, b"two").unwrap();
assert!(
SpriteCache::open(&root)
.unwrap()
.get("minecraft:block/x")
.is_none()
);
// A new file also invalidates.
let mut cache = SpriteCache::open(&root).unwrap();
cache.insert("minecraft:block/x", sample(1, None));
cache.save();
fs::write(root.join("assets/minecraft/textures/block/y.png"), b"y").unwrap();
assert!(
SpriteCache::open(&root)
.unwrap()
.get("minecraft:block/x")
.is_none()
);
// Corrupt cache file: empty, no error.
fs::write(root.join(FILE), b"HSPR junk").unwrap();
assert!(
SpriteCache::open(&root)
.unwrap()
.get("minecraft:block/x")
.is_none()
);
let _ = fs::remove_dir_all(&root);
}
fn write_png(path: &Path, rgba: [u8; 4]) {
let mut encoder = png::Encoder::new(fs::File::create(path).unwrap(), 16, 16);
encoder.set_color(png::ColorType::Rgba);
encoder.set_depth(png::BitDepth::Eight);
let pixels: Vec<u8> = rgba.iter().copied().cycle().take(16 * 16 * 4).collect();
encoder
.write_header()
.unwrap()
.write_image_data(&pixels)
.unwrap();
}
fn sprite_pixels(root: &Path) -> Vec<u8> {
let mut sprites = crate::sprites::Sprites::with_disk_cache(root);
sprites.insert(root, "minecraft:block/x").unwrap();
sprites.save_disk_cache();
sprites.finish();
sprites.pixels
}
#[test]
fn altered_png_is_not_served_stale_and_cache_matches_decoding() {
let root = scratch("stale");
let png = root.join("assets/minecraft/textures/block/x.png");
write_png(&png, [255, 0, 0, 255]);
let decoded = sprite_pixels(&root);
assert!(root.join(FILE).exists());
assert_eq!(
sprite_pixels(&root),
decoded,
"cache hit differs from decoding"
);
std::thread::sleep(std::time::Duration::from_millis(30));
write_png(&png, [0, 255, 0, 255]);
let fresh = sprite_pixels(&root);
assert_eq!(&fresh[..4], &[0, 255, 0, 255]);
// Corrupt and deleted caches fall back to decoding.
fs::write(root.join(FILE), b"HSPR\x01\0\0\0 junk").unwrap();
assert_eq!(sprite_pixels(&root), fresh);
fs::remove_file(root.join(FILE)).unwrap();
assert_eq!(sprite_pixels(&root), fresh);
let _ = fs::remove_dir_all(&root);
}
}
@@ -1,496 +0,0 @@
//! `StructureBlockEntity`: the structure block's name, offset, size, mode and
//! options, with its save format (`saveAdditional` / `loadAdditional`), the
//! corner scan (`getEnclosingBoundingBox`) and the box the editor shows
//! (`getRenderableBox`).
use horizon_client_core::nbt_value::{float, number, string, text};
use horizon_world::{
nbt::Tag,
worldgen::structure::{Mirror, Rotation},
};
pub const MAX_OFFSET_PER_AXIS: i32 = 48;
pub const MAX_SIZE_PER_AXIS: i32 = 48;
/// `SCAN_CORNER_BLOCKS_RANGE`.
pub const SCAN_CORNER_BLOCKS_RANGE: i32 = 80;
/// `StructureMode`, in declaration order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StructureMode {
Save,
Load,
Corner,
Data,
}
impl StructureMode {
pub const ALL: [Self; 4] = [Self::Save, Self::Load, Self::Corner, Self::Data];
/// `StructureMode.getSerializedName`: the block state's `mode` value.
pub fn serialized_name(self) -> &'static str {
match self {
Self::Save => "save",
Self::Load => "load",
Self::Corner => "corner",
Self::Data => "data",
}
}
pub fn of_serialized_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.serialized_name() == name)
}
/// `StructureMode.LEGACY_CODEC`: `Enum.name()`.
pub fn legacy_name(self) -> &'static str {
match self {
Self::Save => "SAVE",
Self::Load => "LOAD",
Self::Corner => "CORNER",
Self::Data => "DATA",
}
}
pub fn from_legacy_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.legacy_name() == name)
}
pub fn ordinal(self) -> i32 {
self as i32
}
pub fn from_ordinal(ordinal: i32) -> Option<Self> {
usize::try_from(ordinal)
.ok()
.and_then(|i| Self::ALL.get(i).copied())
}
/// `StructureMode.getDisplayName`'s lang key.
pub fn info_key(self) -> String {
format!("structure_block.mode_info.{}", self.serialized_name())
}
/// The mode button's label (`structure_block.mode.<name>`).
pub fn label_key(self) -> String {
format!("structure_block.mode.{}", self.serialized_name())
}
}
/// `StructureBlockEntity.UpdateType`, in declaration order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum UpdateType {
UpdateData,
SaveArea,
LoadArea,
ScanArea,
}
impl UpdateType {
pub fn ordinal(self) -> i32 {
self as i32
}
pub fn from_ordinal(ordinal: i32) -> Option<Self> {
Some(match ordinal {
0 => Self::UpdateData,
1 => Self::SaveArea,
2 => Self::LoadArea,
3 => Self::ScanArea,
_ => return None,
})
}
}
pub fn rotation_from_ordinal(ordinal: i32) -> Option<Rotation> {
usize::try_from(ordinal)
.ok()
.and_then(|i| Rotation::ALL.get(i).copied())
}
pub fn rotation_ordinal(rotation: Rotation) -> i32 {
rotation as i32
}
pub fn rotation_from_legacy_name(name: &str) -> Option<Rotation> {
Rotation::ALL.into_iter().find(|r| r.saved_name() == name)
}
pub fn mirror_from_ordinal(ordinal: i32) -> Option<Mirror> {
Some(match ordinal {
0 => Mirror::None,
1 => Mirror::LeftRight,
2 => Mirror::FrontBack,
_ => return None,
})
}
pub fn mirror_ordinal(mirror: Mirror) -> i32 {
mirror as i32
}
pub fn mirror_from_legacy_name(name: &str) -> Option<Mirror> {
[Mirror::None, Mirror::LeftRight, Mirror::FrontBack]
.into_iter()
.find(|m| m.saved_name() == name)
}
/// `BoundingBoxRenderable.Mode`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RenderMode {
None,
Box,
BoxAndInvisibleBlocks,
}
/// `BoundingBoxRenderable.RenderableBox`: an offset from the block and a
/// size, in blocks.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RenderableBox {
pub offset: [i32; 3],
pub size: [i32; 3],
}
impl RenderableBox {
/// `RenderableBox.fromCorners`.
pub fn from_corners(x0: i32, y0: i32, z0: i32, x1: i32, y1: i32, z1: i32) -> Self {
let (min_x, min_y, min_z) = (x0.min(x1), y0.min(y1), z0.min(z1));
Self {
offset: [min_x, min_y, min_z],
size: [x0.max(x1) - min_x, y0.max(y1) - min_y, z0.max(z1) - min_z],
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct StructureBlock {
/// The structure's id; an unparsable or empty name is none.
pub name: Option<String>,
pub author: String,
pub metadata: String,
pub pos: [i32; 3],
pub size: [i32; 3],
pub mirror: Mirror,
pub rotation: Rotation,
pub mode: StructureMode,
pub ignore_entities: bool,
pub strict: bool,
pub powered: bool,
pub show_air: bool,
pub show_bounding_box: bool,
pub integrity: f32,
pub seed: i64,
}
impl StructureBlock {
/// `new StructureBlockEntity(pos, state)`: the mode is the state's.
pub fn new(mode: StructureMode) -> Self {
Self {
name: None,
author: String::new(),
metadata: String::new(),
pos: [0, 1, 0],
size: [0; 3],
mirror: Mirror::None,
rotation: Rotation::None,
mode,
ignore_entities: true,
strict: false,
powered: false,
show_air: false,
show_bounding_box: true,
integrity: 1.0,
seed: 0,
}
}
/// `StructureBlockEntity.getStructureName`.
pub fn structure_name(&self) -> &str {
self.name.as_deref().unwrap_or("")
}
/// `setStructureName(String)`: empty or unparsable is none (`Identifier.tryParse`).
pub fn set_structure_name(&mut self, name: &str) {
self.name = if name.is_empty() {
None
} else {
parse_identifier(name)
};
}
/// `StructureBlockEntity.saveAdditional`.
pub fn save(&self) -> Vec<(&'static str, Tag)> {
let byte = |b: bool| Tag::Byte(i8::from(b));
vec![
("name", string(self.structure_name())),
("author", string(&self.author)),
("metadata", string(&self.metadata)),
("posX", Tag::Int(self.pos[0])),
("posY", Tag::Int(self.pos[1])),
("posZ", Tag::Int(self.pos[2])),
("sizeX", Tag::Int(self.size[0])),
("sizeY", Tag::Int(self.size[1])),
("sizeZ", Tag::Int(self.size[2])),
("rotation", string(self.rotation.saved_name())),
("mirror", string(self.mirror.saved_name())),
("mode", string(self.mode.legacy_name())),
("ignoreEntities", byte(self.ignore_entities)),
("strict", byte(self.strict)),
("powered", byte(self.powered)),
("showair", byte(self.show_air)),
("showboundingbox", byte(self.show_bounding_box)),
("integrity", Tag::Float(self.integrity.to_bits())),
("seed", Tag::Long(self.seed)),
]
}
/// `StructureBlockEntity.loadAdditional`.
pub fn load(tag: &Tag) -> Self {
let int = |key: &str, default: i32, lo: i32, hi: i32| {
(number(tag.get(key)).unwrap_or(i64::from(default)) as i32).clamp(lo, hi)
};
let flag = |key: &str, default: bool| number(tag.get(key)).map_or(default, |v| v != 0);
let o = MAX_OFFSET_PER_AXIS;
let s = MAX_SIZE_PER_AXIS;
let mut block = Self::new(
text(tag.get("mode"))
.and_then(|m| StructureMode::from_legacy_name(&m))
.unwrap_or(StructureMode::Data),
);
block.set_structure_name(&text(tag.get("name")).unwrap_or_default());
block.author = text(tag.get("author")).unwrap_or_default();
block.metadata = text(tag.get("metadata")).unwrap_or_default();
block.pos = [
int("posX", 0, -o, o),
int("posY", 1, -o, o),
int("posZ", 0, -o, o),
];
block.size = [
int("sizeX", 0, 0, s),
int("sizeY", 0, 0, s),
int("sizeZ", 0, 0, s),
];
block.rotation = text(tag.get("rotation"))
.and_then(|r| rotation_from_legacy_name(&r))
.unwrap_or(Rotation::None);
block.mirror = text(tag.get("mirror"))
.and_then(|m| mirror_from_legacy_name(&m))
.unwrap_or(Mirror::None);
block.ignore_entities = flag("ignoreEntities", true);
block.strict = flag("strict", false);
block.powered = flag("powered", false);
block.show_air = flag("showair", false);
block.show_bounding_box = flag("showboundingbox", true);
block.integrity = float(tag.get("integrity")).map_or(1.0, |f| f as f32);
block.seed = number(tag.get("seed")).unwrap_or(0);
block
}
/// `StructureBlockEntity.renderMode`.
pub fn render_mode(&self) -> RenderMode {
if self.mode != StructureMode::Save && self.mode != StructureMode::Load {
RenderMode::None
} else if self.mode == StructureMode::Save && self.show_air {
RenderMode::BoxAndInvisibleBlocks
} else if self.mode != StructureMode::Save && !self.show_bounding_box {
RenderMode::None
} else {
RenderMode::Box
}
}
/// `StructureBlockEntity.getRenderableBox`.
pub fn renderable_box(&self) -> RenderableBox {
let [x_origin, y0, z_origin] = self.pos;
let size = self.size;
let y1 = y0 + size[1];
let (x_diff, z_diff) = match self.mirror {
Mirror::LeftRight => (size[0], -size[2]),
Mirror::FrontBack => (-size[0], size[2]),
Mirror::None => (size[0], size[2]),
};
let (x0, z0, x1, z1);
match self.rotation {
Rotation::Clockwise90 => {
x0 = if z_diff < 0 { x_origin } else { x_origin + 1 };
z0 = if x_diff < 0 { z_origin + 1 } else { z_origin };
x1 = x0 - z_diff;
z1 = z0 + x_diff;
}
Rotation::Clockwise180 => {
x0 = if x_diff < 0 { x_origin } else { x_origin + 1 };
z0 = if z_diff < 0 { z_origin } else { z_origin + 1 };
x1 = x0 - x_diff;
z1 = z0 - z_diff;
}
Rotation::Counterclockwise90 => {
x0 = if z_diff < 0 { x_origin + 1 } else { x_origin };
z0 = if x_diff < 0 { z_origin } else { z_origin + 1 };
x1 = x0 + z_diff;
z1 = z0 - x_diff;
}
Rotation::None => {
x0 = if x_diff < 0 { x_origin + 1 } else { x_origin };
z0 = if z_diff < 0 { z_origin + 1 } else { z_origin };
x1 = x0 + x_diff;
z1 = z0 + z_diff;
}
}
RenderableBox::from_corners(x0, y0, z0, x1, y1, z1)
}
/// `StructureBlockEntity.getEnclosingBoundingBox` over the corner blocks
/// of this structure's name found in range (`corners`: every position of
/// a corner-mode structure block with the same name), with `at` the block
/// asking. Returns the inclusive min and max, none without a corner.
pub fn enclosing_box(corners: &[[i32; 3]], at: [i32; 3]) -> Option<([i32; 3], [i32; 3])> {
let mut found: Option<([i32; 3], [i32; 3])> = None;
for c in corners {
found = Some(match found {
None => (*c, *c),
Some((min, max)) => (
[min[0].min(c[0]), min[1].min(c[1]), min[2].min(c[2])],
[max[0].max(c[0]), max[1].max(c[1]), max[2].max(c[2])],
),
});
}
let (min, max) = found?;
if corners.len() == 1 {
return Some((
[min[0].min(at[0]), min[1].min(at[1]), min[2].min(at[2])],
[max[0].max(at[0]), max[1].max(at[1]), max[2].max(at[2])],
));
}
Some((min, max))
}
/// `detectSize`'s result for the box: the offset and size the block takes
/// when every side is wider than the corner blocks themselves.
pub fn detected(min: [i32; 3], max: [i32; 3], at: [i32; 3]) -> Option<([i32; 3], [i32; 3])> {
let delta = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];
if delta.iter().all(|d| *d > 1) {
Some((
[min[0] - at[0] + 1, min[1] - at[1] + 1, min[2] - at[2] + 1],
[delta[0] - 1, delta[1] - 1, delta[2] - 1],
))
} else {
None
}
}
}
/// `Identifier.tryParse`: `namespace:path` (the namespace defaults to
/// `minecraft`) with only legal characters, as its string form.
pub fn parse_identifier(text: &str) -> Option<String> {
let (namespace, path) = text.split_once(':').unwrap_or(("minecraft", text));
let namespace = if namespace.is_empty() {
"minecraft"
} else {
namespace
};
let namespace_ok = namespace
.chars()
.all(|c| matches!(c, '_' | '-' | '.' | '0'..='9' | 'a'..='z'));
let path_ok = !path.is_empty()
&& path
.chars()
.all(|c| matches!(c, '_' | '-' | '.' | '/' | '0'..='9' | 'a'..='z'));
(namespace_ok && path_ok).then(|| format!("{namespace}:{path}"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saves_and_loads_like_structure_block_entity() {
let mut block = StructureBlock::new(StructureMode::Save);
block.set_structure_name("house");
block.author = "levzzz".into();
block.pos = [1, -2, 3];
block.size = [4, 5, 6];
block.rotation = Rotation::Clockwise90;
block.mirror = Mirror::FrontBack;
block.ignore_entities = false;
block.strict = true;
block.integrity = 0.25;
block.seed = -9;
let tag = Tag::compound(block.save());
assert_eq!(text(tag.get("name")).as_deref(), Some("minecraft:house"));
assert_eq!(text(tag.get("mode")).as_deref(), Some("SAVE"));
assert_eq!(text(tag.get("rotation")).as_deref(), Some("CLOCKWISE_90"));
assert_eq!(StructureBlock::load(&tag), block.clone());
}
#[test]
fn load_clamps_and_defaults() {
let tag = Tag::compound(vec![
("posX", Tag::Int(99)),
("posY", Tag::Int(-99)),
("sizeX", Tag::Int(-4)),
("sizeY", Tag::Int(100)),
("name", string("Bad Name")),
]);
let block = StructureBlock::load(&tag);
assert_eq!(block.pos, [48, -48, 0]);
assert_eq!(block.size, [0, 48, 0]);
assert_eq!(block.name, None);
assert_eq!(block.mode, StructureMode::Data);
assert!(block.ignore_entities && block.show_bounding_box && !block.strict);
assert_eq!(block.integrity, 1.0);
// Pos defaults to (0, 1, 0).
assert_eq!(
StructureBlock::load(&Tag::compound(Vec::<(&str, Tag)>::new())).pos,
[0, 1, 0]
);
}
#[test]
fn render_mode_and_box_follow_get_renderable_box() {
let mut block = StructureBlock::new(StructureMode::Save);
block.pos = [0, 1, 0];
block.size = [3, 2, 4];
assert_eq!(block.render_mode(), RenderMode::Box);
assert_eq!(
block.renderable_box(),
RenderableBox {
offset: [0, 1, 0],
size: [3, 2, 4]
}
);
block.rotation = Rotation::Clockwise90;
assert_eq!(
block.renderable_box(),
RenderableBox {
offset: [-3, 1, 0],
size: [4, 2, 3]
}
);
block.rotation = Rotation::None;
block.mirror = Mirror::LeftRight;
assert_eq!(
block.renderable_box(),
RenderableBox {
offset: [0, 1, -3],
size: [3, 2, 4]
}
);
block.show_air = true;
assert_eq!(block.render_mode(), RenderMode::BoxAndInvisibleBlocks);
block.mode = StructureMode::Load;
block.show_bounding_box = false;
assert_eq!(block.render_mode(), RenderMode::None);
block.mode = StructureMode::Corner;
assert_eq!(block.render_mode(), RenderMode::None);
}
#[test]
fn corner_scan_matches_detect_size() {
// Two corners: their box; one corner: the box with the asking block.
let (min, max) = StructureBlock::enclosing_box(&[[0, 0, 0], [5, 4, 6]], [2, 0, 2]).unwrap();
assert_eq!((min, max), ([0, 0, 0], [5, 4, 6]));
assert_eq!(
StructureBlock::detected(min, max, [2, 0, 2]),
Some(([-1, 1, -1], [4, 3, 5]))
);
let one = StructureBlock::enclosing_box(&[[0, 0, 0]], [3, 3, 3]).unwrap();
assert_eq!(one, ([0, 0, 0], [3, 3, 3]));
assert_eq!(StructureBlock::enclosing_box(&[], [0, 0, 0]), None);
// A box of one block thickness is no structure.
assert_eq!(
StructureBlock::detected([0, 0, 0], [1, 5, 5], [0, 0, 0]),
None
);
}
#[test]
fn identifiers_parse_like_try_parse() {
assert_eq!(parse_identifier("a/b").as_deref(), Some("minecraft:a/b"));
assert_eq!(parse_identifier("my:house").as_deref(), Some("my:house"));
assert_eq!(parse_identifier("Bad"), None);
assert_eq!(parse_identifier("ns:"), None);
}
}
@@ -1,202 +0,0 @@
//! `TestBlockEntity`: the test block's mode, message and powered flag, with
//! its save format (`saveAdditional` / `loadAdditional`).
use horizon_client_core::nbt_value::{number, string, text};
use horizon_world::nbt::Tag;
/// `TestBlockMode`, in id order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TestBlockMode {
Start,
Log,
Fail,
Accept,
}
impl TestBlockMode {
pub const ALL: [Self; 4] = [Self::Start, Self::Log, Self::Fail, Self::Accept];
/// `getSerializedName`: the block state's `mode` value.
pub fn serialized_name(self) -> &'static str {
match self {
Self::Start => "start",
Self::Log => "log",
Self::Fail => "fail",
Self::Accept => "accept",
}
}
pub fn of_serialized_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|m| m.serialized_name() == name)
}
pub fn id(self) -> i32 {
self as i32
}
/// `ByIdMap.continuous(.., OutOfBoundsStrategy.ZERO)`.
pub fn by_id(id: i32) -> Self {
usize::try_from(id)
.ok()
.and_then(|i| Self::ALL.get(i).copied())
.unwrap_or(Self::Start)
}
/// `getDisplayName`'s lang key.
pub fn label_key(self) -> String {
format!("test_block.mode.{}", self.serialized_name())
}
/// `getDetailedMessage`'s lang key.
pub fn info_key(self) -> String {
format!("test_block.mode_info.{}", self.serialized_name())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TestBlock {
pub mode: TestBlockMode,
pub message: String,
pub powered: bool,
/// `triggered`: not saved; the game test reads and clears it.
pub triggered: bool,
}
/// What a `TestBlockEntity` call asks of the level.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Effects {
/// `level.updateNeighborsAt(pos, block)`.
pub update_neighbors: bool,
/// `log()`.
pub log: bool,
}
impl TestBlock {
/// `new TestBlockEntity(pos, state)`: the mode is the state's.
pub fn new(mode: TestBlockMode) -> Self {
Self {
mode,
message: String::new(),
powered: false,
triggered: false,
}
}
/// `reset`.
pub fn reset(&mut self) -> Effects {
self.triggered = false;
let start = self.mode == TestBlockMode::Start;
if start {
self.powered = false;
}
Effects {
update_neighbors: start,
log: false,
}
}
/// `trigger`: a start block powers up and logs; the others log (LOG
/// only) and remember they were triggered.
pub fn trigger(&mut self) -> Effects {
if self.mode == TestBlockMode::Start {
self.powered = true;
return Effects {
update_neighbors: true,
log: true,
};
}
self.triggered = true;
Effects {
update_neighbors: false,
log: self.mode == TestBlockMode::Log,
}
}
/// `TestBlock.neighborChanged`: `signal` is `hasNeighborSignal`; a start
/// block ignores it, the others trigger on a rising signal.
pub fn neighbor_changed(&mut self, signal: bool) -> Option<Effects> {
if self.mode == TestBlockMode::Start {
return None;
}
if signal && !self.powered {
self.powered = true;
Some(self.trigger())
} else {
if !signal && self.powered {
self.powered = false;
}
None
}
}
/// `TestBlock.ownSignal`: a powered start block gives 15.
pub fn own_signal(&self) -> i32 {
if self.mode == TestBlockMode::Start && self.powered {
15
} else {
0
}
}
/// `saveAdditional` (also `getUpdateTag`, which is `saveCustomOnly`).
pub fn save(&self) -> Vec<(&'static str, Tag)> {
vec![
("mode", string(self.mode.serialized_name())),
("message", string(&self.message)),
("powered", Tag::Byte(i8::from(self.powered))),
]
}
/// `loadAdditional`: a missing or unknown mode is FAIL.
pub fn load(tag: &Tag) -> Self {
Self {
mode: text(tag.get("mode"))
.and_then(|m| TestBlockMode::of_serialized_name(&m))
.unwrap_or(TestBlockMode::Fail),
message: text(tag.get("message")).unwrap_or_default(),
powered: number(tag.get("powered")).is_some_and(|v| v != 0),
triggered: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn saves_and_loads_like_test_block_entity() {
let block = TestBlock {
mode: TestBlockMode::Accept,
message: "all done".into(),
powered: true,
triggered: false,
};
let tag = Tag::compound(block.save());
assert_eq!(text(tag.get("mode")).as_deref(), Some("accept"));
assert_eq!(TestBlock::load(&tag), block);
}
#[test]
fn start_blocks_power_up_and_the_others_trigger_on_a_rising_signal() {
let mut start = TestBlock::new(TestBlockMode::Start);
assert_eq!(start.neighbor_changed(true), None);
assert_eq!(start.own_signal(), 0);
let effects = start.trigger();
assert!(effects.update_neighbors && effects.log && start.own_signal() == 15);
assert!(start.reset().update_neighbors && start.own_signal() == 0);
let mut log = TestBlock::new(TestBlockMode::Log);
let effects = log.neighbor_changed(true).unwrap();
assert!(effects.log && !effects.update_neighbors && log.triggered && log.powered);
// Still powered: no second trigger; a fall clears the flag.
assert_eq!(log.neighbor_changed(true), None);
assert_eq!(log.neighbor_changed(false), None);
assert!(!log.powered && log.triggered);
assert!(!log.reset().update_neighbors && !log.triggered);
let mut accept = TestBlock::new(TestBlockMode::Accept);
assert!(!accept.neighbor_changed(true).unwrap().log);
}
#[test]
fn load_defaults_to_fail_and_ids_wrap_to_start() {
let block = TestBlock::load(&Tag::compound(Vec::<(&str, Tag)>::new()));
assert_eq!(block, TestBlock::new(TestBlockMode::Fail));
assert_eq!(TestBlockMode::by_id(3), TestBlockMode::Accept);
assert_eq!(TestBlockMode::by_id(9), TestBlockMode::Start);
assert_eq!(TestBlockMode::Log.id(), 1);
}
}
@@ -1,265 +0,0 @@
//! `TestInstanceBlockEntity`: the test instance block's test, size, rotation
//! and status, its error markers, and the boxes derived from them.
use horizon_client_core::nbt_value::{number, string, text};
use horizon_world::{
nbt::Tag,
worldgen::structure::{BoundingBox, Rotation},
};
/// `STRUCTURE_OFFSET`: where the structure starts from the block.
pub const STRUCTURE_OFFSET: [i32; 3] = [0, 1, 1];
/// `TestInstanceBlockEntity.Status`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Status {
Cleared,
Running,
Finished,
}
impl Status {
pub fn serialized_name(self) -> &'static str {
match self {
Self::Cleared => "cleared",
Self::Running => "running",
Self::Finished => "finished",
}
}
pub fn of_serialized_name(name: &str) -> Option<Self> {
[Self::Cleared, Self::Running, Self::Finished]
.into_iter()
.find(|s| s.serialized_name() == name)
}
pub fn index(self) -> i32 {
self as i32
}
/// `Status.byIndex`: out of range is CLEARED.
pub fn by_index(index: i32) -> Self {
match index {
1 => Self::Running,
2 => Self::Finished,
_ => Self::Cleared,
}
}
}
/// `TestInstanceBlockEntity.Data`. Components are kept as the NBT they are
/// sent and saved as.
#[derive(Clone, Debug, PartialEq)]
pub struct Data {
/// The test's registry id.
pub test: Option<String>,
pub size: [i32; 3],
pub rotation: Rotation,
pub ignore_entities: bool,
pub status: Status,
pub error_message: Option<Tag>,
}
impl Default for Data {
fn default() -> Self {
Self {
test: None,
size: [0; 3],
rotation: Rotation::None,
ignore_entities: false,
status: Status::Cleared,
error_message: None,
}
}
}
impl Data {
/// `Data.CODEC` encoded.
pub fn save(&self) -> Tag {
let mut entries = Vec::new();
if let Some(test) = &self.test {
entries.push(("test", string(test)));
}
entries.push(("size", Tag::IntArray(self.size.to_vec())));
entries.push(("rotation", string(self.rotation.serialized_name())));
entries.push(("ignore_entities", Tag::Byte(i8::from(self.ignore_entities))));
entries.push(("status", string(self.status.serialized_name())));
if let Some(error) = &self.error_message {
entries.push(("error_message", error.clone()));
}
Tag::compound(entries)
}
/// `Data.CODEC` decoded: size, rotation, ignore_entities and status are
/// required, or the whole value is dropped.
pub fn load(tag: &Tag) -> Option<Self> {
let size = match tag.get("size")? {
Tag::IntArray(v) if v.len() == 3 => [v[0], v[1], v[2]],
_ => return None,
};
Some(Self {
test: text(tag.get("test")),
size,
rotation: Rotation::from_name(&text(tag.get("rotation"))?)?,
ignore_entities: number(tag.get("ignore_entities")).map(|v| v != 0)?,
status: Status::of_serialized_name(&text(tag.get("status"))?)?,
error_message: tag.get("error_message").cloned(),
})
}
}
/// `TestInstanceBlockEntity.ErrorMarker`.
#[derive(Clone, Debug, PartialEq)]
pub struct ErrorMarker {
pub pos: [i32; 3],
pub text: Tag,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TestInstanceBlock {
pub data: Data,
pub error_markers: Vec<ErrorMarker>,
}
impl TestInstanceBlock {
/// `saveAdditional` (also `getUpdateTag`, which is `saveCustomOnly`).
pub fn save(&self) -> Vec<(&'static str, Tag)> {
let mut entries = vec![("data", self.data.save())];
if !self.error_markers.is_empty() {
let markers = self
.error_markers
.iter()
.map(|m| {
Tag::compound([
("pos", Tag::IntArray(m.pos.to_vec())),
("text", m.text.clone()),
])
})
.collect();
entries.push(("errors", Tag::List(markers)));
}
entries
}
/// `loadAdditional`: the data is replaced only when it decodes, and the
/// markers are always replaced.
pub fn load(&mut self, tag: &Tag) {
if let Some(data) = tag.get("data").and_then(Data::load) {
self.data = data;
}
self.error_markers.clear();
if let Some(Tag::List(markers)) = tag.get("errors") {
for m in markers {
if let (Some(Tag::IntArray(p)), Some(text)) = (m.get("pos"), m.get("text"))
&& p.len() == 3
{
self.error_markers.push(ErrorMarker {
pos: [p[0], p[1], p[2]],
text: text.clone(),
});
}
}
}
}
/// `getStructurePos(blockPos)`.
pub fn structure_pos_of(block: [i32; 3]) -> [i32; 3] {
[0, 1, 2].map(|i| block[i] + STRUCTURE_OFFSET[i])
}
/// `getTransformedSize`: the size with the axes swapped for a quarter turn.
pub fn transformed_size(size: [i32; 3], rotation: Rotation) -> [i32; 3] {
if matches!(
rotation,
Rotation::Clockwise90 | Rotation::Counterclockwise90
) {
[size[2], size[1], size[0]]
} else {
size
}
}
/// `getRenderableBox`: the offset from the block and the size to draw,
/// given the test's `padding` and rotation.
pub fn renderable_box(&self, padding: i32, rotation: Rotation) -> ([i32; 3], [i32; 3]) {
let offset = STRUCTURE_OFFSET.map(|o| o + padding);
(offset, Self::transformed_size(self.data.size, rotation))
}
/// `getStructureBoundingBox`.
pub fn structure_box(&self, block: [i32; 3], padding: i32, rotation: Rotation) -> BoundingBox {
let corner = Self::structure_pos_of([0, 1, 2].map(|i| block[i] + padding));
let size = Self::transformed_size(self.data.size, rotation);
BoundingBox::from_corners(corner, [0, 1, 2].map(|i| corner[i] + size[i] - 1))
}
/// `getStartCorner`: the corner the template is placed from.
pub fn start_corner(&self, block: [i32; 3], padding: i32, rotation: Rotation) -> [i32; 3] {
let [x, _, z] = self.data.size;
let c = Self::structure_pos_of([0, 1, 2].map(|i| block[i] + padding));
match rotation {
Rotation::None => c,
Rotation::Clockwise90 => [c[0] + z - 1, c[1], c[2]],
Rotation::Clockwise180 => [c[0] + x - 1, c[1], c[2] + z - 1],
Rotation::Counterclockwise90 => [c[0], c[1], c[2] + x - 1],
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn sample() -> TestInstanceBlock {
TestInstanceBlock {
data: Data {
test: Some("minecraft:always_pass".into()),
size: [3, 4, 5],
rotation: Rotation::Clockwise180,
ignore_entities: true,
status: Status::Finished,
error_message: Some(string("boom")),
},
error_markers: vec![ErrorMarker {
pos: [1, 2, 3],
text: string("here"),
}],
}
}
#[test]
fn saves_and_loads_like_test_instance_block_entity() {
let block = sample();
let tag = Tag::compound(block.save());
assert_eq!(
text(tag.get("data").unwrap().get("rotation")).as_deref(),
Some("180")
);
let mut loaded = TestInstanceBlock::default();
loaded.load(&tag);
assert_eq!(loaded, block);
// No markers, no `errors` key; a bad `data` leaves the old one.
let mut plain = block.clone();
plain.error_markers.clear();
assert!(Tag::compound(plain.save()).get("errors").is_none());
let mut kept = block;
kept.load(&Tag::compound([(
"data",
Tag::compound(Vec::<(&str, Tag)>::new()),
)]));
assert_eq!(kept.data.test.as_deref(), Some("minecraft:always_pass"));
assert!(kept.error_markers.is_empty());
}
#[test]
fn boxes_follow_padding_and_rotation() {
let block = sample();
// A quarter turn swaps the horizontal sizes.
let (offset, size) = block.renderable_box(2, Rotation::Clockwise90);
assert_eq!((offset, size), ([2, 3, 3], [5, 4, 3]));
let bounds = block.structure_box([10, 64, 10], 2, Rotation::None);
assert_eq!(bounds.min, [12, 67, 13]);
assert_eq!(bounds.max, [14, 70, 17]);
assert_eq!(
block.start_corner([10, 64, 10], 2, Rotation::Counterclockwise90),
[12, 67, 15]
);
assert_eq!(Status::by_index(7), Status::Cleared);
}
}
@@ -1,133 +0,0 @@
// Horizon's world post pass: the world, rendered at the resolution scale,
// copied (bilinear) or anti-aliased with FXAA onto the screen before the
// hand and HUD. Only used when a non-vanilla setting asks for it.
@group(0) @binding(0) var world: texture_2d<f32>;
@group(0) @binding(1) var world_sampler: sampler;
struct PostOut {
@builtin(position) clip: vec4<f32>,
@location(0) uv: vec2<f32>,
};
@vertex fn vs_post(@builtin(vertex_index) i: u32) -> PostOut {
let p = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
var out: PostOut;
out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0);
out.uv = vec2(p.x, 1.0 - p.y);
return out;
}
@fragment fn fs_copy(in: PostOut) -> @location(0) vec4<f32> {
// The alpha carries the emissive mark through to HDR output (hdr.wgsl).
return textureSampleLevel(world, world_sampler, in.uv, 0.0);
}
fn luma(c: vec3<f32>) -> f32 {
return dot(c, vec3(0.299, 0.587, 0.114));
}
// FXAA 3.11 (console quality): blend along the local edge direction.
@fragment fn fs_fxaa(in: PostOut) -> @location(0) vec4<f32> {
let texel = 1.0 / vec2<f32>(textureDimensions(world));
let centre = textureSampleLevel(world, world_sampler, in.uv, 0.0);
let rgb_m = centre.rgb;
let nw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, -0.5) * texel, 0.0).rgb);
let ne = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, -0.5) * texel, 0.0).rgb);
let sw = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(-0.5, 0.5) * texel, 0.0).rgb);
let se = luma(textureSampleLevel(world, world_sampler, in.uv + vec2(0.5, 0.5) * texel, 0.0).rgb);
let m = luma(rgb_m);
let lo = min(m, min(min(nw, ne), min(sw, se)));
let hi = max(m, max(max(nw, ne), max(sw, se)));
if hi - lo < max(0.0312, hi * 0.125) {
return centre;
}
var dir = vec2(-((nw + ne) - (sw + se)), (nw + sw) - (ne + se));
let reduce = max((nw + ne + sw + se) * 0.25 * 0.125, 1.0 / 128.0);
let scale = 1.0 / (min(abs(dir.x), abs(dir.y)) + reduce);
dir = clamp(dir * scale, vec2(-8.0), vec2(8.0)) * texel;
let a = 0.5 * (textureSampleLevel(world, world_sampler, in.uv + dir * (1.0 / 3.0 - 0.5), 0.0).rgb
+ textureSampleLevel(world, world_sampler, in.uv + dir * (2.0 / 3.0 - 0.5), 0.0).rgb);
let b = a * 0.5 + 0.25 * (textureSampleLevel(world, world_sampler, in.uv - dir * 0.5, 0.0).rgb
+ textureSampleLevel(world, world_sampler, in.uv + dir * 0.5, 0.0).rgb);
let lb = luma(b);
if lb < lo || lb > hi {
return vec4(a, centre.a);
}
return vec4(b, centre.a);
}
// TAA (`world_post.rs`): blend this frame into the history, reprojected from the
// depth buffer through the camera's motion and clamped to this frame's 3x3
// neighbourhood so that what moved or appeared does not ghost.
struct Taa {
reproject: mat4x4<f32>,
// xy: this frame's jitter in clip space; z: 1 when the history is unusable.
jitter: vec4<f32>,
};
@group(0) @binding(2) var history: texture_2d<f32>;
@group(0) @binding(3) var depth: texture_depth_2d;
@group(0) @binding(4) var<uniform> taa: Taa;
// Catmull-Rom over the history in 5 bilinear taps: sharper than one under motion.
fn sample_history(uv: vec2<f32>) -> vec3<f32> {
let size = vec2<f32>(textureDimensions(history));
let pos = uv * size;
let centre = floor(pos - 0.5) + 0.5;
let f = pos - centre;
let w0 = f * (-0.5 + f * (1.0 - 0.5 * f));
let w1 = 1.0 + f * f * (-2.5 + 1.5 * f);
let w2 = f * (0.5 + f * (2.0 - 1.5 * f));
let w3 = f * f * (-0.5 + 0.5 * f);
let w12 = w1 + w2;
let t0 = (centre - 1.0) / size;
let t3 = (centre + 2.0) / size;
let t12 = (centre + w2 / w12) / size;
let c = textureSampleLevel(history, world_sampler, vec2(t12.x, t0.y), 0.0).rgb * (w12.x * w0.y)
+ textureSampleLevel(history, world_sampler, vec2(t0.x, t12.y), 0.0).rgb * (w0.x * w12.y)
+ textureSampleLevel(history, world_sampler, t12, 0.0).rgb * (w12.x * w12.y)
+ textureSampleLevel(history, world_sampler, vec2(t3.x, t12.y), 0.0).rgb * (w3.x * w12.y)
+ textureSampleLevel(history, world_sampler, vec2(t12.x, t3.y), 0.0).rgb * (w12.x * w3.y);
let weight = w12.x * w0.y + w0.x * w12.y + w12.x * w12.y + w3.x * w12.y + w12.x * w3.y;
return max(c / weight, vec3(0.0));
}
// It runs at the history's size, which upscaling makes larger than the world's.
// The history is unjittered: each output pixel takes the world pixel whose
// jittered sample lands nearest its centre, weighted by how near it lands.
@fragment fn fs_taa(in: PostOut) -> @location(0) vec4<f32> {
let size = vec2<f32>(textureDimensions(world));
// The jitter moved the scene by `jitter` in clip space: where this pixel's
// point was drawn, in world pixels.
let drawn = (in.uv + taa.jitter.xy * vec2(0.5, -0.5)) * size;
let last = vec2<i32>(size) - 1;
let p = clamp(vec2<i32>(floor(drawn)), vec2(0), last);
let centre = textureLoad(world, p, 0);
var lo = centre.rgb;
var hi = centre.rgb;
// Reversed depth: the nearest of the 3x3 is the largest, and its motion keeps
// the edges of what is in front from trailing.
var near = 0.0;
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
let q = clamp(p + vec2(x, y), vec2(0), last);
let c = textureLoad(world, q, 0).rgb;
lo = min(lo, c);
hi = max(hi, c);
near = max(near, textureLoad(depth, q, 0));
}
}
let ndc = vec2(in.uv.x * 2.0 - 1.0, 1.0 - in.uv.y * 2.0);
let previous = taa.reproject * vec4(ndc, near, 1.0);
let uv = vec2(0.5, -0.5) * previous.xy / previous.w + 0.5;
if taa.jitter.z > 0.0 || any(uv != clamp(uv, vec2(0.0), vec2(1.0))) {
return vec4(centre.rgb, centre.a);
}
let past = clamp(sample_history(uv), lo, hi);
// How far the sample landed from this pixel's centre, in output pixels: a
// Gaussian of it scales the new frame's share, so that frames whose sample
// fell far away (most of them when upscaling) barely move the pixel.
let off = (drawn - (vec2<f32>(p) + 0.5)) * vec2<f32>(textureDimensions(history)) / size;
let share = 0.1 * exp(-2.0 * dot(off, off));
// The alpha carries the emissive mark through to HDR output (hdr.wgsl).
return vec4(mix(past, centre.rgb, share), centre.a);
}
+8 -7
View File
@@ -11,7 +11,6 @@ description = "Horizon native development client"
horizon-assets = { path = "../horizon-assets" }
horizon-client-core = { path = "../horizon-client-core" }
horizon-client-input = { path = "../horizon-client-input" }
horizon-client-render = { path = "../horizon-client-render" }
horizon-command = { path = "../horizon-command" }
horizon-items = { path = "../horizon-items" }
horizon-core = { path = "../horizon-core" }
@@ -22,8 +21,6 @@ horizon-world = { path = "../horizon-world" }
horizon-protocol = { path = "../horizon-protocol" }
# server.properties, eula.txt and the user lists, shared with horizon-server.
horizon-server-files = { path = "../horizon-server-files" }
# The dedicated server's anticheat, off unless server.toml's [anticheat] turns it on (docs/anticheat.md).
horizon-anticheat = { path = "../horizon-anticheat" }
# Shader packs: reading them and turning their GLSL into naga modules.
horizon-shaders = { path = "../horizon-shaders" }
# Horizon's own shader packs: the format, the stages and the check (docs/shaders.md).
@@ -46,6 +43,9 @@ serde_json = { version = "1.0.151", features = ["raw_value"] }
# hlsl-out: the gfx.rs tests translate every shader as wgpu's DirectX 12 backend does. A normal feature,
# not a dev-dependency's, so builds, tests and examples share one build of naga, wgpu and this crate.
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out"] }
# Sound (ALSA on Linux); the `audio` feature.
cpal = { version = "0.16", optional = true }
symphonia = { version = "0.5", default-features = false, features = ["ogg", "vorbis"] }
miniz_oxide = "0.8"
ab_glyph = "0.2.32"
log = "0.4"
@@ -67,8 +67,7 @@ unicode-bidi = "0.3.18"
[target.'cfg(unix)'.dependencies]
# The server thread's CPU time per tick (`HORIZON_SPIKES`, spans.rs).
# `LevelStorageAccess.estimateDiskSpace` (statvfs) too.
rustix = { version = "1", default-features = false, features = ["std", "time", "process", "fs"] }
rustix = { version = "1", default-features = false, features = ["std", "time"] }
[target.'cfg(windows)'.dependencies]
# Use the registered URI handler without routing links through Explorer/cmd.
@@ -91,9 +90,12 @@ winresource = "0.1"
default = ["audio", "controllers"]
# Sound output. Without it (and `controllers`) the program links neither libasound nor libudev on
# Linux: the server build (`--no-default-features`, released as horizon-engine; docs/server.md).
audio = ["horizon-client-render/audio"]
audio = ["dep:cpal"]
# Controllers: gilrs, and the DualSense's own output. Without it only `horizon-ctl pad`'s virtual pad.
controllers = ["dep:gilrs", "dep:horizon-dualsense", "horizon-client-input/controllers"]
# Runs code mods (wasmtime and cranelift: a quarter of a clean build). On in every release build
# (release.yml); the tests and probes don't need it. Content mods load without it.
mods = ["horizon-mods/runtime"]
# Records the call sites of mob random draws (`mob_ai_probe` traces).
rng-trace = ["horizon-core/rng-trace"]
@@ -106,7 +108,6 @@ path = "examples/probe/main.rs"
workspace = true
[dev-dependencies]
horizon-client-render = { path = "../horizon-client-render", features = ["test-support"] }
horizon-items = { path = "../horizon-items", features = ["test-support"] }
# Every WGSL shader translated as wgpu's DirectX 12 backend does (gfx.rs tests).
naga = { version = "30.0.1", features = ["wgsl-in", "hlsl-out", "msl-out", "spv-out"] }
@@ -11,57 +11,5 @@
"horizon.options.look_deadzone": "Look Deadzone",
"horizon.options.button_glyphs": "Button Glyphs",
"horizon.options.menu_navigation": "Menu Navigation",
"horizon.options.on_screen_keyboard": "On-Screen Keyboard",
"horizon.options.chat_delay": "Chat Delay",
"horizon.options.lightbar.health": "Health",
"horizon.options.lightbar.dimension": "Dimension",
"horizon.options.glyphs.auto": "Auto",
"horizon.options.glyphs.xbox": "Xbox",
"horizon.options.glyphs.playstation": "PlayStation",
"horizon.options.glyphs.nintendo": "Nintendo",
"horizon.options.menu_focus": "Focus",
"horizon.options.menu_pointer": "Pointer",
"horizon.options.keyboard.auto": "Auto",
"horizon.options.keyboard.horizon": "Horizon",
"horizon.options.keyboard.steam": "Steam",
"horizon.options.unavailable": "This feature is not yet available in Horizon.",
"horizon.options.search": "Search settings...",
"horizon.pages.mods": "Mods",
"horizon.pages.shader_packs": "Shader Packs",
"horizon.pages.controller": "Controller Settings",
"horizon.pages.controller_binds": "Controller Binds",
"horizon.pages.extras": "Horizon Extras",
"horizon.pages.settings": "Horizon Settings",
"horizon.pages.agent": "AI Agent",
"horizon.pages.settings.tooltip": "Horizon's own settings: graphics, controllers, extras and mods.",
"horizon.pages.graphics.tooltip": "Graphics, simply: each setting says what it costs.",
"horizon.pages.graphics_advanced.tooltip": "Every graphics setting, Horizon's included, with what each costs.",
"horizon.pages.controller.tooltip": "Controllers: their buttons, sticks, vibration and menu navigation.",
"horizon.pages.extras.tooltip": "Optional additions, all off by default: the game stays vanilla until you turn one on.",
"horizon.pages.agent.tooltip": "Let your own AI agent play: horizon-ctl and MCP clients on this computer.",
"horizon.pages.shader_packs.tooltip": "Shader packs from the shaderpacks folder: Horizon's own and those in the shaders/ format. One runs at a time.",
"horizon.pages.mods.tooltip": "Mods made for Horizon, from the horizon-mods folder. Each runs in a sandbox and stays off until you turn it on.",
"horizon.pages.open.graphics": "Graphics...",
"horizon.pages.open.graphics_advanced": "Advanced Graphics...",
"horizon.pages.open.shader_packs": "Shader Packs...",
"horizon.pages.open.controller": "Controller Settings...",
"horizon.pages.open.extras": "Extras...",
"horizon.pages.open.mods": "Mods...",
"horizon.pages.open.agent": "AI Agent...",
"horizon.pages.open.horizon_graphics": "Horizon Graphics...",
"horizon.pages.open.controller_binds": "Controller Binds...",
"horizon.pages.open.horizon_settings": "Horizon Settings...",
"horizon.mods.empty": "No mods: put .hmod files in the horizon-mods folder",
"horizon.mods.stopped": " (Stopped)",
"horizon.mods.dev": " (Dev)",
"horizon.mods.settings": "Settings",
"horizon.mods.open_folder": "Open Mod Folder",
"horizon.shader_packs.empty": "No shader packs: put them in the shaderpacks folder",
"horizon.shader_packs.kind_horizon": " (Horizon)",
"horizon.agent.copy_details": "Copy Connection Details",
"horizon.multiplayer.join": "Join",
"horizon.multiplayer.cancel_reconnecting": "Cancel Reconnecting",
"horizon.multiplayer.join_friend": "Join a Friend",
"horizon.multiplayer.invite_code": "Invite Code",
"horizon.multiplayer.relay": "Relay (optional)"
"horizon.options.on_screen_keyboard": "On-Screen Keyboard"
}
@@ -1,15 +0,0 @@
{
"horizon.options.controller": "Kontroler",
"horizon.options.vibration": "Wibracje",
"horizon.options.adaptive_triggers": "Adaptacyjne spusty",
"horizon.options.lightbar": "Pasek świetlny",
"horizon.options.look_sensitivity": "Czułość rozglądania",
"horizon.options.invert_x": "Odwróć oś X rozglądania",
"horizon.options.invert_y": "Odwróć oś Y rozglądania",
"horizon.options.sneak_button": "Przycisk skradania",
"horizon.options.move_deadzone": "Martwa strefa ruchu",
"horizon.options.look_deadzone": "Martwa strefa rozglądania",
"horizon.options.button_glyphs": "Symbole przycisków",
"horizon.options.menu_navigation": "Nawigacja po menu",
"horizon.options.on_screen_keyboard": "Klawiatura ekranowa"
}
@@ -11,57 +11,5 @@
"horizon.options.look_deadzone": "Мёртвая зона обзора",
"horizon.options.button_glyphs": "Символы кнопок",
"horizon.options.menu_navigation": "Навигация по меню",
"horizon.options.on_screen_keyboard": "Экранная клавиатура",
"horizon.options.chat_delay": "Задержка чата",
"horizon.options.lightbar.health": "Здоровье",
"horizon.options.lightbar.dimension": "Измерение",
"horizon.options.glyphs.auto": "Авто",
"horizon.options.glyphs.xbox": "Xbox",
"horizon.options.glyphs.playstation": "PlayStation",
"horizon.options.glyphs.nintendo": "Nintendo",
"horizon.options.menu_focus": "Фокус",
"horizon.options.menu_pointer": "Указатель",
"horizon.options.keyboard.auto": "Авто",
"horizon.options.keyboard.horizon": "Horizon",
"horizon.options.keyboard.steam": "Steam",
"horizon.options.unavailable": "Эта возможность в Horizon пока недоступна.",
"horizon.options.search": "Поиск настроек...",
"horizon.pages.mods": "Моды",
"horizon.pages.shader_packs": "Шейдерпаки",
"horizon.pages.controller": "Настройки контроллера",
"horizon.pages.controller_binds": "Назначения кнопок контроллера",
"horizon.pages.extras": "Дополнения Horizon",
"horizon.pages.settings": "Настройки Horizon",
"horizon.pages.agent": "ИИ-агент",
"horizon.pages.settings.tooltip": "Собственные настройки Horizon: графика, контроллеры, дополнения и моды.",
"horizon.pages.graphics.tooltip": "Графика без лишнего: у каждой настройки написано, чего она стоит.",
"horizon.pages.graphics_advanced.tooltip": "Все графические настройки, включая собственные настройки Horizon, и их цена.",
"horizon.pages.controller.tooltip": "Контроллеры: кнопки, стики, вибрация и навигация по меню.",
"horizon.pages.extras.tooltip": "Дополнительные возможности, все выключены по умолчанию: игра остаётся ванильной, пока вы не включите что-то.",
"horizon.pages.agent.tooltip": "Пусть играет ваш ИИ-агент: horizon-ctl и MCP-клиенты на этом компьютере.",
"horizon.pages.shader_packs.tooltip": "Шейдерпаки из папки shaderpacks: собственные паки Horizon и паки в формате shaders/. Одновременно работает один.",
"horizon.pages.mods.tooltip": "Моды для Horizon из папки horizon-mods. Каждый работает в песочнице и выключен, пока вы его не включите.",
"horizon.pages.open.graphics": "Графика...",
"horizon.pages.open.graphics_advanced": "Продвинутая графика...",
"horizon.pages.open.shader_packs": "Шейдерпаки...",
"horizon.pages.open.controller": "Настройки контроллера...",
"horizon.pages.open.extras": "Дополнения...",
"horizon.pages.open.mods": "Моды...",
"horizon.pages.open.agent": "ИИ-агент...",
"horizon.pages.open.horizon_graphics": "Графика Horizon...",
"horizon.pages.open.controller_binds": "Назначения кнопок...",
"horizon.pages.open.horizon_settings": "Настройки Horizon...",
"horizon.mods.empty": "Модов нет: положите файлы .hmod в папку horizon-mods",
"horizon.mods.stopped": " (остановлен)",
"horizon.mods.dev": " (разработка)",
"horizon.mods.settings": "Настройки",
"horizon.mods.open_folder": "Открыть папку модов",
"horizon.shader_packs.empty": "Шейдерпаков нет: положите их в папку shaderpacks",
"horizon.shader_packs.kind_horizon": " (Horizon)",
"horizon.agent.copy_details": "Скопировать данные подключения",
"horizon.multiplayer.join": "Подключиться",
"horizon.multiplayer.cancel_reconnecting": "Отменить переподключение",
"horizon.multiplayer.join_friend": "Играть с другом",
"horizon.multiplayer.invite_code": "Код приглашения",
"horizon.multiplayer.relay": "Ретранслятор (необязательно)"
"horizon.options.on_screen_keyboard": "Экранная клавиатура"
}
@@ -1,15 +0,0 @@
{
"horizon.options.controller": "Геймпад",
"horizon.options.vibration": "Вібрація",
"horizon.options.adaptive_triggers": "Адаптивні тригери",
"horizon.options.lightbar": "Світлова панель",
"horizon.options.look_sensitivity": "Чутливість огляду",
"horizon.options.invert_x": "Інвертувати огляд по X",
"horizon.options.invert_y": "Інвертувати огляд по Y",
"horizon.options.sneak_button": "Кнопка присідання",
"horizon.options.move_deadzone": "Мертва зона руху",
"horizon.options.look_deadzone": "Мертва зона огляду",
"horizon.options.button_glyphs": "Значки кнопок",
"horizon.options.menu_navigation": "Навігація в меню",
"horizon.options.on_screen_keyboard": "Екранна клавіатура"
}
@@ -12,14 +12,12 @@ use horizon_client::{
assets::Assets,
blocks::BlockFacts,
crafting::{Recipe, Recipes},
enchant::Enchantments,
items::{ItemStack, Items},
mod_content::{self, ContentMod},
stations::StationRecipes,
};
use horizon_core::{geometry::Axis, random::LegacyRandom};
use horizon_world::chunk::BlockState;
use horizon_world::loot::PackOverlay;
use serde_json::{Map, Value, json};
use std::{collections::BTreeMap, fs, path::Path};
@@ -79,10 +77,9 @@ fn main() -> Result<()> {
let assets = Assets::load(&root).map_err(step("assets"))?;
let registry = assets.registry;
let facts = BlockFacts::load(&root, registry).map_err(step("block facts"))?;
let items = Items::load(&root, registry, &facts, &PackOverlay::NONE).map_err(step("items"))?;
let recipes = Recipes::load(&root, &items, &PackOverlay::NONE).map_err(step("recipes"))?;
let stations = StationRecipes::load(&root, &items, &PackOverlay::NONE);
let enchantments = Enchantments::load(&root);
let items = Items::load(&root, registry, &facts).map_err(step("items"))?;
let recipes = Recipes::load(&root, &items).map_err(step("recipes"))?;
let stations = StationRecipes::load(&root, &items);
let collisions =
horizon_client::collisions::load(&root, registry).map_err(step("collisions"))?;
let loaded = began.elapsed().as_secs_f64() - built;
@@ -200,35 +197,7 @@ fn main() -> Result<()> {
item_rows.insert(
name.clone(),
match items.items.get(name.as_str()) {
Some(i) => {
let props = enchantments.props(name);
let repairable: Vec<String> = props
.into_iter()
.flat_map(|p| &p.repairable)
.flat_map(|r| match r.strip_prefix('#') {
Some(tag) => items.item_tag_order.get(tag).cloned().unwrap_or_default(),
None => vec![r.clone()],
})
.collect();
json!({
"max_stack_size": i.max_stack,
"block": i.block.map(|b| b.0),
"max_damage": i.max_damage,
"modifiers": i.modifiers.iter().map(|(attribute, id, amount, operation, slot)| {
json!({"type": attribute, "id": id, "amount": amount, "operation": operation, "slot": slot})
}).collect::<Vec<_>>(),
"tool": i.tool_damage_per_block.map(|per_block| json!({
"rules": i.tool.iter().map(|r| json!({"blocks": r.blocks, "speed": r.speed, "correct_for_drops": r.correct})).collect::<Vec<_>>(),
"default_mining_speed": i.tool_default_speed,
"damage_per_block": per_block,
})),
"enchantable": props.map_or(0, |p| p.enchantable),
"repairable": repairable,
"equip_slot": i.equip_slot,
"equip_asset": i.equip_asset,
"food": i.food.map(|(nutrition, saturation)| json!({"nutrition": nutrition, "saturation": saturation})),
})
}
Some(i) => json!({"max_stack_size": i.max_stack, "block": i.block.map(|b| b.0)}),
None => Value::Null,
},
);
@@ -7,7 +7,6 @@ use horizon_client::{
chunk::{Chunk, MIN_Y, SECTIONS, Section},
fast_hash::FxHashMap,
portal_sections::PortalSections,
section_mask::SectionMask,
};
use horizon_core::{
geometry::{Aabb, Vec3},
@@ -84,14 +83,17 @@ fn may_hold_portal_cached(
if count > 64 {
return true;
}
let y_mask = SectionMask::below(y1 as usize + 1).from(y0 as usize);
let mut y_mask = 0u32;
for sy in y0..=y1 {
y_mask |= 1 << sy;
}
(x0..=x1).any(|cx| {
(z0..=z1).any(|cz| {
world.get(&(cx, cz)).is_some_and(|chunk| {
let portals = cache.get((cx, cz), chunk, |v| {
cache.get((cx, cz), chunk, |v| {
behaviours.portal_axis(BlockStateId(v)).is_some()
});
!(portals & y_mask).is_empty()
}) & y_mask
!= 0
})
})
})
@@ -153,9 +153,6 @@ pub fn main() -> Result<()> {
bits(position),
bits(velocity)
)),
ArrowEvent::PotionPuff { id, color } => {
events.push(format!("potion-puff {id} {color:08x}"))
}
ArrowEvent::Sound {
sound,
volume,
@@ -16,7 +16,6 @@ use horizon_client::{
items::Items,
};
use horizon_core::random::LegacyRandom;
use horizon_world::loot::PackOverlay;
use horizon_world::registry::{BlockRegistry, BlockStateId};
use serde_json::Value;
use std::{
@@ -128,7 +127,7 @@ pub fn main() -> Result<()> {
let registry = assets.registry;
let facts = BlockFacts::load(root, registry)?;
let renderer = BlockEntityRenderer::load(root, registry)?;
let tags = Items::tags_only(root, &PackOverlay::NONE)?;
let tags = Items::tags_only(root)?;
let frames = tags
.block_tags
.get("minecraft:conduit_effect_block")
@@ -1,37 +0,0 @@
//! Block-model tints without a level, including blank and invalid tint indices.
use horizon_client::{
assets::Assets, blocks::BlockFacts, item_render::ItemRenderer, mesher::MeshTables, models,
};
use horizon_world::registry::BlockStateId;
use serde_json::Value;
use std::{
fs,
io::{BufWriter, Write},
path::Path,
};
pub fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<_> = crate::args().collect();
let input: Value = serde_json::from_slice(&fs::read(&args[1])?)?;
let root = Path::new(input["resources"].as_str().unwrap());
let assets = Assets::load(root)?;
let render = assets.reload(root)?;
let facts = BlockFacts::load(root, assets.registry)?;
let tables = MeshTables::new(
&assets,
&render,
&facts,
models::load_visibility(root, assets.registry)?,
)?;
let grass = ItemRenderer::load(root)?.grass_color(0.5, 1.0) as u32;
let mut output = BufWriter::new(fs::File::create(&args[2])?);
for row in input["cases"].as_array().unwrap() {
let state = row[0].as_u64().unwrap() as u32;
let index = row[1].as_i64().unwrap() as i32;
let color = tables
.default_tint(BlockStateId(state), index, grass)
.map_or(-1, |rgb| (0xFF00_0000 | rgb) as i32);
writeln!(output, "{state} {index} {color}")?;
}
Ok(())
}
@@ -9,7 +9,6 @@ use horizon_client::{
items::Items,
};
use horizon_world::chunk::BlockState;
use horizon_world::loot::PackOverlay;
use std::{fs, path::Path};
fn parse(text: &str) -> BlockState {
@@ -59,7 +58,7 @@ pub fn main() -> horizon_client::Result<()> {
.ok_or("usage: block_transform_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root, &PackOverlay::NONE)?;
let items = Items::catalog(root)?;
let assets = Assets::load(root)?;
let transformers = Transformers::load(root, assets.registry)?;
let mut out = String::new();
@@ -302,7 +302,7 @@ fn avatar(c: &Value, out: &mut impl Write) -> Result<()> {
for op in c["ops"].as_array().unwrap() {
let name = op[0].as_str().unwrap();
match name {
"tick" => state.tick([0.0; 3]),
"tick" => state.tick(),
"move" => state.add_walked(fl(&op[1]), fl(&op[2])),
"bob" => state.update_bob(b(&op[1]) && !b(&op[2]) && !b(&op[3]), vec3(&op[4])),
"reset" => state.reset_bob(),
@@ -10,7 +10,6 @@ use horizon_client::{
menu::{Env, Kind, Menu},
};
use horizon_world::chunk::BlockState;
use horizon_world::loot::PackOverlay;
use serde_json::Value;
use std::{fs, path::Path};
@@ -78,9 +77,9 @@ pub fn main() -> horizon_client::Result<()> {
.ok_or("usage: cauldron_fixture RESOURCES INPUT OUTPUT")?,
);
let input = fs::read_to_string(args.get(2).ok_or("missing INPUT")?)?;
let items = Items::catalog(root, &PackOverlay::NONE)?;
let recipes = Recipes::load(root, &items, &PackOverlay::NONE)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items, &PackOverlay::NONE);
let items = Items::catalog(root)?;
let recipes = Recipes::load(root, &items)?;
let brewing = horizon_client::brewing::Brewing::load(root, &items);
// The inventory menu never reads banner patterns.
let banners = horizon_client::banner::Banners::default();
let station_recipes = horizon_client::stations::StationRecipes::default();
@@ -43,7 +43,6 @@ pub fn registries(r: &Value, permission: u8) -> Registries {
reg.timelines = strings(&r["timelines"]);
reg.dimensions = strings(&r["dimensions"]);
reg.players = strings(&r["players"]);
reg.selected_entities = strings(&r["selected_entities"]);
reg.teams = strings(&r["teams"]);
reg.objectives = strings(&r["objectives"]);
reg.tracked = strings(&r["tracked"]);
@@ -1,74 +0,0 @@
//! Double chests for tools/test_chest_pair_parity.py: reads one JSON case per
//! line (see VanillaChestPairOracle), a chest's block state at the origin and
//! another block state at the offset "at", and prints what
//! `horizon_client::containers::ChestHalf` pairs them into, as the game's
//! menus and hoppers do: "double" with the right half's x,z then the left
//! half's, or "single".
//!
//! usage: chest_pair_fixture INPUT OUTPUT
use horizon_client::containers::{ChestHalf, is_chest_block};
use serde_json::Value;
use std::collections::BTreeMap;
use std::fs;
/// `minecraft:chest[facing=north,type=left]` as its name and properties.
fn parse(state: &str) -> Option<(&str, BTreeMap<&str, &str>)> {
let (name, props) = match state.split_once('[') {
Some((name, rest)) => (name, rest.strip_suffix(']')?),
None => (state, ""),
};
let props = props
.split(',')
.filter(|p| !p.is_empty())
.map(|p| p.split_once('='))
.collect::<Option<_>>()?;
Some((name, props))
}
fn half<'a>(name: &'a str, props: &BTreeMap<&str, &'a str>) -> Option<ChestHalf<'a>> {
Some(ChestHalf {
block: name,
kind: props.get("type")?,
facing: props.get("facing")?,
})
}
fn case(line: &str) -> Option<String> {
let case: Value = serde_json::from_str(line).ok()?;
let (name, props) = parse(case["state"].as_str()?)?;
let (other_name, other_props) = parse(case["other"].as_str()?)?;
let at = (
i32::try_from(case["at"][0].as_i64()?).ok()?,
i32::try_from(case["at"][1].as_i64()?).ok()?,
);
if !is_chest_block(name) {
return None;
}
let own = half(name, &props)?;
let paired = own.connected_step() == Some(at)
&& half(other_name, &other_props).is_some_and(|other| own.pairs_with(&other));
Some(if !paired {
"single".to_owned()
} else if own.kind == "right" {
format!("double 0,0 {},{}", at.0, at.1)
} else {
format!("double {},{} 0,0", at.0, at.1)
})
}
pub fn main() -> horizon_client::Result<()> {
let args: Vec<String> = crate::args().collect();
let input = fs::read_to_string(
args.get(1)
.ok_or("usage: chest_pair_fixture INPUT OUTPUT")?,
)?;
let lines: Vec<String> = input
.lines()
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
.collect();
fs::write(
args.get(2).ok_or("missing OUTPUT")?,
lines.join("\n") + "\n",
)?;
Ok(())
}
@@ -178,7 +178,6 @@ pub fn main() -> horizon_client::Result<()> {
reg.timelines = strings(&r["timelines"]);
reg.dimensions = strings(&r["dimensions"]);
reg.players = strings(&r["players"]);
reg.selected_entities = strings(&r["selected_entities"]);
reg.teams = strings(&r["teams"]);
reg.objectives = strings(&r["objectives"]);
reg.tracked = strings(&r["tracked"]);
@@ -1,98 +0,0 @@
//! Container menu titles for tools/test_container_title_parity.py: reads one
//! JSON case per line (see VanillaContainerTitleOracle) and prints the title
//! the server opens the container's menu with, as canonical NBT. A single
//! block entity is placed as the game places it (`block_entity_item::place`,
//! whose `CustomName` the game keeps in `World::block_names`), then named by
//! `containers::display_name`; a double chest's halves by
//! `containers::double_chest_name`.
//!
//! usage: container_title_fixture INPUT OUTPUT
use horizon_client::block_entity_item::place;
use horizon_client::block_entity_nbt::canonical;
use horizon_client::containers::{default_name_key, display_name, double_chest_name};
use horizon_client::save::text;
use horizon_world::nbt::{Tag, parse_snbt};
use serde_json::Value;
use std::fs;
/// ParityData.canon of a text component: sorted keys.
fn canon(tag: &Tag, out: &mut String) {
match tag {
Tag::Compound(map) => {
let mut keys: Vec<_> = map.iter().map(|(k, v)| (k.to_string_lossy(), v)).collect();
keys.sort_by(|a, b| a.0.cmp(&b.0));
out.push('{');
for (i, (k, v)) in keys.into_iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str(&k);
out.push(':');
canon(v, out);
}
out.push('}');
}
Tag::List(items) => {
out.push('[');
for (i, item) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
canon(item, out);
}
out.push(']');
}
other => out.push_str(&horizon_client::item_data::canon_tag(other)),
}
}
fn snbt(value: &Value) -> Option<Tag> {
parse_snbt(value.as_str()?).ok().map(|(tag, _)| tag)
}
/// The custom name the game keeps for a block entity saved as `value`.
fn custom_name(value: &Value) -> Option<Option<String>> {
let saved = canonical(&snbt(value)?)?;
Some(text(saved.get("CustomName")))
}
fn case(line: &str) -> Option<String> {
let case: Value = serde_json::from_str(line).ok()?;
let title = if let Some(first) = case.get("first") {
let first = custom_name(first)?;
let second = custom_name(&case["second"])?;
double_chest_name(first.as_deref(), second.as_deref())
} else {
let saved = canonical(&snbt(&case["nbt"])?)?;
// BlockItem.updateBlockEntityComponents, as Game::apply_placed_item runs it.
let placed = match case.get("patch") {
Some(p) => match snbt(p)? {
Tag::Compound(patch) => place(&saved, &patch, true),
_ => return None,
},
None => saved,
};
let key = default_name_key(case["block"].as_str()?)?;
display_name(text(placed.get("CustomName")).as_deref(), key)
};
let mut out = String::new();
canon(&title, &mut out);
Some(out)
}
pub fn main() -> horizon_client::Result<()> {
let args: Vec<String> = crate::args().collect();
let input = fs::read_to_string(
args.get(1)
.ok_or("usage: container_title_fixture INPUT OUTPUT")?,
)?;
let lines: Vec<String> = input
.lines()
.map(|line| case(line).unwrap_or_else(|| "error".to_owned()))
.collect();
fs::write(
args.get(2).ok_or("missing OUTPUT")?,
lines.join("\n") + "\n",
)?;
Ok(())
}
Loaded 100 of 1257 files, more files were not shown because too many files have changed in this diff. Show more