Merge main into fix branch (resolves the conflict with main)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-27 03:38:18 +01:00
192 changed files with 10457 additions and 1048 deletions
+1
View File
@@ -144,6 +144,7 @@ jobs:
with: with:
base: ${{ github.event.pull_request.base.sha }} base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }} head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
# Horizon never downloads the game. These jobs need a self-hosted Linux runner # Horizon never downloads the game. These jobs need a self-hosted Linux runner
# (label horizon-game) holding the maintainer's own copy: the official launcher's # (label horizon-game) holding the maintainer's own copy: the official launcher's
# game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in # game directory in HORIZON_MINECRAFT_DIR and the pinned server jar in
+2 -2
View File
@@ -25,8 +25,8 @@ jobs:
parity-main: parity-main:
# A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs # A Mac mini runner of its own (ludovics-mac-mini-2 holds only this label since 2026-10-26): behind PR parity jobs
# this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited # this run waited 2 h while every merge replaced the pending one, and on the release runner a release then waited
# behind the next run. PR parity jobs have ludovics-mac-mini and the desktop. Not the desktop: a job slowed down # behind the next run. PR parity jobs have ludovics-mac-mini and playhorizon. Not playhorizon: its 4 CPUs
# because the maintainer came back could time out, and a failure here bisects and comments on merges. # make a core-crate run several times longer, and a failure here bisects and comments on merges.
runs-on: [self-hosted, macOS, horizon-parity-main] runs-on: [self-hosted, macOS, horizon-parity-main]
timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures timeout-minutes: 240 # a core-crate batch reruns ~300 harnesses (~60-90 min), a bisect a few rounds of the failures
steps: steps:
+43 -62
View File
@@ -1,6 +1,6 @@
name: parity name: parity
# The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner, which holds the maintainer's # The vanilla harnesses a pull request's changes can affect, on the Mac mini's runner or playhorizon's, which hold the
# own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository # maintainer's own Minecraft files (Horizon never downloads the game). Called by ci.yml for pull requests from this repository
# and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md. # and by run-parity.yml when a maintainer labels a fork's pull request run-parity. See docs/release-flow.md.
on: on:
workflow_call: workflow_call:
@@ -13,6 +13,13 @@ on:
description: The commit to check out and test description: The commit to check out and test
type: string type: string
required: true required: true
full:
description: >-
The pull request carries the full-parity label (a change every harness reaches, such as a crate split): it
runs on playhorizon's runner only, so the Mac mini's runners stay free for the others. While that runner is
busy the job waits for it.
type: boolean
default: false
permissions: permissions:
contents: read contents: read
env: env:
@@ -21,40 +28,53 @@ env:
jobs: jobs:
parity: parity:
runs-on: [self-hosted, horizon-game] runs-on: ${{ inputs.full && fromJSON('["self-hosted", "horizon-game", "playhorizon"]') || fromJSON('["self-hosted", "horizon-game"]') }}
timeout-minutes: 120 # a change to core crates reruns ~300 harnesses: ~60-90 min on the Mac mini # A change to core crates reruns ~350 harnesses: ~60-90 min on the Mac mini; on playhorizon (4 of its 8 vCPUs, 4
# harnesses at a time) up to a few hours, and any pull request's job may land there.
timeout-minutes: ${{ inputs.full && 360 || 180 }}
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with: with:
# The commit the event names: a fork's later pushes need another run-parity label. # The commit the event names: a fork's later pushes need another run-parity label. The next step merges
# main into it.
ref: ${{ inputs.head }} ref: ${{ inputs.head }}
fetch-depth: 0 fetch-depth: 0
persist-credentials: false persist-credentials: false
# Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs. # Keeps .local/ (parity state, probe builds, oracle results) and target/ between runs.
clean: false clean: false
- name: The head merged into main (what merging it would land)
id: merge
env:
BASE_SHA: ${{ inputs.base }}
HEAD_SHA: ${{ inputs.head }}
run: |
# Harness fixes and game fixes that reached main since the branch was made then apply here too: a head
# tested alone failed harnesses already fixed on main (server_knockback before #2114, mob_ai's heap before
# #2270, save_roundtrip before #2212). Selection then compares with this main, so it sees only the pull
# request's own changes. A head that conflicts with main is tested alone.
set -euo pipefail
git merge --abort 2>/dev/null || true
git fetch -q --no-tags origin +refs/heads/main:refs/remotes/origin/main
main=$(git rev-parse origin/main)
if git -c user.name=parity -c user.email=parity@localhost merge -q --no-edit --no-ff "$main" >/dev/null 2>&1; then
echo "base=$main" >> "$GITHUB_OUTPUT"
echo "Tested: head ${HEAD_SHA:0:9} merged into main ${main:0:9}" | tee -a "$GITHUB_STEP_SUMMARY"
else
git merge --abort
echo "base=$BASE_SHA" >> "$GITHUB_OUTPUT"
echo "::warning::head ${HEAD_SHA:0:9} conflicts with main ${main:0:9}: tested alone, without main's fixes"
echo "Tested: head ${HEAD_SHA:0:9} alone (it conflicts with main ${main:0:9})" | tee -a "$GITHUB_STEP_SUMMARY"
fi
- uses: dtolnay/rust-toolchain@stable - uses: dtolnay/rust-toolchain@stable
- name: Tools from the runner - name: Tools from the runner
run: bash tools/ci/runner-env.sh run: bash tools/ci/runner-env.sh
- name: Vanilla data, and resources prepared by this preparer - name: Vanilla data, and resources prepared by this preparer
env: run: bash tools/ci/vanilla-data.sh
BASE_SHA: ${{ inputs.base }}
run: |
# main's script: one written before a fix to it left a real .local/horizon-client without sounds.json on
# the runner, and every later job there failed `subtitle`. A branch that changes the script runs its own.
set -euo pipefail
if git rev-parse --verify -q origin/main >/dev/null \
&& git diff --quiet "$(git merge-base "$BASE_SHA" HEAD)" HEAD -- tools/ci/vanilla-data.sh; then
git show origin/main:tools/ci/vanilla-data.sh > "$RUNNER_TEMP/vanilla-data.sh"
bash "$RUNNER_TEMP/vanilla-data.sh"
else
bash tools/ci/vanilla-data.sh
fi
- name: The prepared output is the one the preparer's OUTPUT_VERSION says - name: The prepared output is the one the preparer's OUTPUT_VERSION says
env: env:
BASE_SHA: ${{ inputs.base }} BASE_SHA: ${{ steps.merge.outputs.base }}
run: | run: |
# The job runs main's workflow on the head's files: a head made before OUTPUT_VERSION (#1947) has neither # A head made before OUTPUT_VERSION (#1947) that conflicts with main has neither the tool nor the number.
# the tool nor the number, so there is nothing to check.
if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then if [ ! -f tools/prepare_output.py ] || ! grep -q OUTPUT_VERSION crates/horizon-prepare/src/lib.rs; then
echo "This head's preparer has no OUTPUT_VERSION: nothing to check" echo "This head's preparer has no OUTPUT_VERSION: nothing to check"
exit 0 exit 0
@@ -65,47 +85,8 @@ jobs:
- name: The harnesses this change can affect - name: The harnesses this change can affect
env: env:
PARITY_HOSTS: '' PARITY_HOSTS: ''
BASE_SHA: ${{ inputs.base }} BASE_SHA: ${{ steps.merge.outputs.base }}
run: | run: python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400 # world_spawn takes ~1480 s on a busy runner
# main's selection (tools/parity.py --changed --list with main's parity.py and parity_reach.py), so a
# branch made before a better selection landed gets it too; the head's own runner then runs those
# harnesses. A branch that changes the selection itself selects with its own code.
set -euo pipefail
own() { python3 tools/parity.py --changed "$BASE_SHA" --timeout 2400; } # world_spawn takes ~1480 s on a busy runner
fork_point=$(git merge-base "$BASE_SHA" HEAD)
if ! git rev-parse --verify -q origin/main >/dev/null || ! git diff --quiet "$fork_point" HEAD -- tools/parity.py tools/parity_reach.py; then
own
exit
fi
had_reach=$(git ls-files tools/parity_reach.py)
git show origin/main:tools/parity.py > tools/parity.py
git show origin/main:tools/parity_reach.py > tools/parity_reach.py
status=0
python3 tools/parity.py --changed "$BASE_SHA" --list > .local/parity-selection.txt || status=$?
git checkout -- tools/parity.py
if [ -n "$had_reach" ]; then git checkout -- tools/parity_reach.py; else rm -f tools/parity_reach.py; fi
cat .local/parity-selection.txt
if [ "$status" != 0 ]; then
echo "main's selection failed: the head's own selection runs"
own
exit
fi
names=$(sed '$d' .local/parity-selection.txt | grep -E '^[A-Za-z0-9_#]+$' || true)
# The summary line says how many would run: a count that doesn't match the names read (a format change)
# must not let the job pass untested.
expected=$(tail -1 .local/parity-selection.txt | sed -nE 's/^([0-9]+) of [0-9]+ harnesses would run$/\1/p')
count=$(printf '%s' "$names" | grep -c . || true)
if [ -z "$expected" ] || [ "$expected" != "$count" ]; then
echo "main's selection listed $count names, its summary says '${expected:-?}': the head's own selection runs"
own
exit
fi
if [ "$count" = 0 ]; then
echo "Nothing to run."
exit 0
fi
# shellcheck disable=SC2086
python3 tools/parity.py $names --timeout 2400
- name: Logs of the failed harnesses - name: Logs of the failed harnesses
if: failure() if: failure()
uses: actions/upload-artifact@v4 uses: actions/upload-artifact@v4
+1
View File
@@ -22,3 +22,4 @@ jobs:
with: with:
base: ${{ github.event.pull_request.base.sha }} base: ${{ github.event.pull_request.base.sha }}
head: ${{ github.event.pull_request.head.sha }} head: ${{ github.event.pull_request.head.sha }}
full: ${{ contains(github.event.pull_request.labels.*.name, 'full-parity') }}
+6 -4
View File
@@ -34,7 +34,9 @@ Game workspace (root `Cargo.toml`); `launcher/` and `crates/horizon-telemetry-se
| Crate | Owns | | Crate | Owns |
|---|---| |---|---|
| `horizon-client` | The game: a lib (`src/lib.rs`, ~190 flat modules) 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`, ~180 flat modules) and the bin (`src/main.rs` → `game.rs` + `game/`), plus `horizon-ctl` (`src/bin/horizon-ctl/`). Also the dedicated server (`--dedicated`) |
| `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-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-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-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` | | `horizon-protocol` | Network protocol 777: codecs, framing, encryption, `packets/{handshake,status,login,configuration,play}.rs`, `entity_data.rs` |
@@ -118,16 +120,16 @@ python3 tools/agent_control_e2e.py # horizon-ctl / MCP end to end
| Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` | | Other entities | L: `entities.rs`, `projectiles.rs`, `arrows.rs`; G: `boats.rs`, `minecarts.rs`, `mounts.rs`, `armor_stands.rs`, `paintings.rs`, `frames.rs`, `fireworks.rs`, `tnt.rs`, `explosion.rs` |
| Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` | | Player actions | game.rs (`fn use_hand`, `fn use_item`, `fn attack`, `fn tick_mining`, `fn break_block`); G: `hand.rs`, `combat.rs`, `consume.rs`, `potions.rs`, `shield.rs`, `crossbow.rs`, `trident.rs`, `fishing.rs`; L: `motion.rs` + `motion/` (movement), `collisions.rs`, `items.rs`, `item_data.rs` |
| Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` | | Inventory and containers | L: `menu.rs` (`AbstractContainerMenu.clicked`), `container_screen.rs`, `containers.rs`, `creative.rs`, `crafting.rs`, `recipe_book*.rs`, `stations.rs`, `merchant.rs`; game.rs `fn menu_ops`, `fn click_inventory`; G: `stations.rs`, `trading.rs`, `recipe_book.rs`, `machines.rs` |
| Commands | parse: L: `command/` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`, `nbt_path.rs`; G: `functions.rs`, `command_blocks.rs` | | Commands | parse: crate `horizon-command` (`args.rs`, `selector.rs`, `tree_*.rs`, `vanilla.rs`); run: G: `commands.rs` (dispatch) + `commands/*.rs` (`admin`, `execute`, `items`, `players`, `world_cmds`...); L: `scoreboard_cmd.rs`, `data_cmd.rs`; `horizon-client-core`: `nbt_path.rs`, `scoreboard.rs`; G: `functions.rs`, `command_blocks.rs` |
| UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` | | UI screens | `Screen` enum in game.rs; L: `title.rs` + `title/`, `options_ui.rs`, `multiplayer.rs`, `pack_screen.rs`, `graphics_ui.rs`, `screen_draw.rs`, `ui.rs` (widgets), `hud.rs`, `hud_layout.rs`, `hud_overlays.rs`, `chat.rs`, `tab_list.rs`; G: `startup_menu.rs`, `screens.rs` (pause, death), `options.rs`, `lan_screen.rs`, `chat.rs`, `sign_edit.rs`, `books.rs` |
| Multiplayer client | L: `net.rs` (network thread); G: `remote.rs` (`fn handle_packet`, `fn tick_remote`), `remote_*.rs` (mob data, objects, projectiles, vehicles, stations) | | 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) | | 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` | | 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` | | 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`, `block_entity_nbt.rs`, `options_file.rs`; G: `saving.rs`, `persist.rs` (entities); `crates/horizon-world/src/{region.rs,nbt.rs,datafix/}` | | 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`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.rs`; G: `pad.rs`, `pad_menu.rs` | | Input | game.rs `fn window_event`, `fn key_pressed`, `fn play_mouse`; L: `keybinds.rs`, `keymapping.rs`, `key_names.rs`, `mouse.rs`, `input.rs`, `interaction_input.rs`, `gamepad.rs`, `osk.rs`, `clipboard.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` | | Audio | L: `audio.rs` (mixer), `sound_engine.rs`, `sound_events.rs`, `music.rs`, `ambience.rs`; G: `music.rs`, `subtitle_hud.rs` |
| Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`, `lang.rs`; crate `horizon-assets`; G: `packs.rs` | | Resource packs | L: `packs.rs` + `packs/`, `pack_screen.rs`, `atlas_sources.rs`, `sprites.rs`, `mipmap.rs`, `model_library.rs`, `font.rs`; `horizon-client-core/src/lang.rs`; crate `horizon-assets`; G: `packs.rs` |
| Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) | | Agent control | L: `control.rs` (socket), `bin/horizon-ctl/`; G: `control.rs`, `agent.rs`, `events.rs`, `ui_control.rs` ([docs/agent-control.md](docs/agent-control.md)) |
| Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` | | Mods | crate `horizon-mods`; G: `mods.rs`; L: `mod_content.rs`, `mod_list.rs` |
| Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` | | Horizon extras, settings | L: `extras.rs`, `graphics.rs`, `settings.rs`, `minimap.rs`; G: `extras.rs`, `tweaks.rs`, `options.rs` |
Generated
+33
View File
@@ -216,6 +216,13 @@ version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "beacons"
version = "0.1.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]] [[package]]
name = "bit-set" name = "bit-set"
version = "0.10.0" version = "0.10.0"
@@ -1365,6 +1372,8 @@ dependencies = [
"glam", "glam",
"horizon-assets", "horizon-assets",
"horizon-bench", "horizon-bench",
"horizon-client-core",
"horizon-command",
"horizon-core", "horizon-core",
"horizon-dualsense", "horizon-dualsense",
"horizon-friends", "horizon-friends",
@@ -1396,6 +1405,23 @@ dependencies = [
"zip", "zip",
] ]
[[package]]
name = "horizon-client-core"
version = "0.1.0"
dependencies = [
"horizon-world",
"serde_json",
]
[[package]]
name = "horizon-command"
version = "0.1.0"
dependencies = [
"horizon-client-core",
"horizon-protocol",
"horizon-world",
]
[[package]] [[package]]
name = "horizon-core" name = "horizon-core"
version = "0.1.0" version = "0.1.0"
@@ -2971,6 +2997,13 @@ dependencies = [
"objc2-quartz-core 0.3.2", "objc2-quartz-core 0.3.2",
] ]
[[package]]
name = "recipes"
version = "1.0.0"
dependencies = [
"horizon-mod-sdk",
]
[[package]] [[package]]
name = "redox_syscall" name = "redox_syscall"
version = "0.4.1" version = "0.4.1"
+40 -1
View File
@@ -1,6 +1,45 @@
[workspace] [workspace]
exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"] exclude = ["launcher", "crates/horizon-telemetry-server", "crates/horizon-mod-registry", "third_party/wgpu-hal"]
members = ["crates/horizon-core", "crates/horizon-dualsense", "crates/horizon-threads", "crates/horizon-hdr", "crates/horizon-world", "crates/horizon-client", "crates/horizon-server-files", "crates/horizon-server", "crates/horizon-bots", "crates/horizon-assets", "crates/horizon-protocol", "crates/horizon-theme", "crates/horizon-prepare", "crates/horizon-telemetry", "crates/horizon-bench", "crates/horizon-friends", "crates/horizon-relay", "crates/horizon-mod-sdk", "crates/horizon-mods", "crates/horizon-mods/tests/guest", "crates/horizon-mods/tests/ui_guest", "crates/cargo-horizon-mod", "crates/horizon-port-pack", "crates/horizon-shaders", "crates/horizon-shader-api", "crates/horizon-release-sign", "crates/horizon-mod-sdk/examples/coords-hud", "crates/horizon-mod-sdk/examples/predator-missile", "crates/horizon-mod-sdk/examples/welcome", "mods/official/fps-overlay", "mods/official/keystrokes", "mods/official/minimap", "mods/official/zoom", "xtask"] members = [
"crates/horizon-core",
"crates/horizon-dualsense",
"crates/horizon-threads",
"crates/horizon-hdr",
"crates/horizon-world",
"crates/horizon-client",
"crates/horizon-client-core",
"crates/horizon-command",
"crates/horizon-server-files",
"crates/horizon-server",
"crates/horizon-bots",
"crates/horizon-assets",
"crates/horizon-protocol",
"crates/horizon-theme",
"crates/horizon-prepare",
"crates/horizon-telemetry",
"crates/horizon-bench",
"crates/horizon-friends",
"crates/horizon-relay",
"crates/horizon-mod-sdk",
"crates/horizon-mods",
"crates/horizon-mods/tests/guest",
"crates/horizon-mods/tests/ui_guest",
"crates/cargo-horizon-mod",
"crates/horizon-port-pack",
"crates/horizon-shaders",
"crates/horizon-shader-api",
"crates/horizon-release-sign",
"crates/horizon-mod-sdk/examples/coords-hud",
"crates/horizon-mod-sdk/examples/predator-missile",
"crates/horizon-mod-sdk/examples/welcome",
"crates/horizon-mod-sdk/examples/beacons",
"mods/official/fps-overlay",
"mods/official/keystrokes",
"mods/official/minimap",
"mods/official/zoom",
"xtask",
"mods/official/recipes",
]
resolver = "2" resolver = "2"
[workspace.package] [workspace.package]
+9
View File
@@ -266,8 +266,17 @@ fn play(path: &Path, report: &mut Report) -> Result<(), String> {
format!("{} quiet command(s)", lines.len()) format!("{} quiet command(s)", lines.len())
} }
Output::Stopped { reason, .. } => return Err(format!("it stopped: {reason}")), 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::OpenScreen { .. } => "opened a screen".to_string(),
Output::CloseScreen { .. } => "closed its 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 } => { Output::Shake { strength, seconds } => {
format!("shook the camera: {strength:.2} for {seconds:.1} s") format!("shook the camera: {strength:.2} for {seconds:.1} s")
} }
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "horizon-client-core"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.90"
description = "The client's lowest layer: chat text and translations, SNBT and NBT paths, the scoreboard, boss bars, game rules and the registry and particle tables commands name"
[dependencies]
horizon-world = { path = "../horizon-world" }
serde_json = { version = "1.0.151", features = ["raw_value"] }
[lints]
workspace = true
@@ -259,7 +259,7 @@ fn is_pos(tag: &Tag) -> bool {
matches!(tag, Tag::IntArray(v) if v.len() == 3) matches!(tag, Tag::IntArray(v) if v.len() == 3)
} }
/// The loaded `SignText` of one side, or the empty text. /// The loaded `SignText` of one side, or the empty text.
pub(crate) fn sign_side(tag: Option<&Tag>) -> Tag { pub fn sign_side(tag: Option<&Tag>) -> Tag {
let empty = || string(""); let empty = || string("");
let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) { let mut messages: Vec<Tag> = match tag.and_then(|t| t.get("messages")) {
Some(Tag::List(list)) => list.iter().filter_map(component).collect(), Some(Tag::List(list)) => list.iter().filter_map(component).collect(),
@@ -268,7 +268,7 @@ pub fn to_text_with(
} else if let Some(sel) = o.get("selector").and_then(Value::as_str) { } else if let Some(sel) = o.get("selector").and_then(Value::as_str) {
resolve(sel) resolve(sel)
} else if let Some(key) = o.get("keybind").and_then(Value::as_str) { } else if let Some(key) = o.get("keybind").and_then(Value::as_str) {
crate::keybinds::display_name(key) crate::key_display::display_name(key)
} else { } else {
Text::empty() Text::empty()
}; };
@@ -292,27 +292,4 @@ mod tests {
assert_eq!(GameRules::load(&dir), rules); assert_eq!(GameRules::load(&dir), rules);
let _ = fs::remove_dir_all(dir); let _ = fs::remove_dir_all(dir);
} }
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = fs::remove_dir_all(&dir);
let mut level = crate::save::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = crate::save::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = fs::remove_dir_all(dir);
}
} }
@@ -0,0 +1,18 @@
//! Resource identifiers (`Identifier`).
/// Identifier.parse: `ns:path` or `path`, validated.
pub fn parse_identifier(raw: &str) -> Option<String> {
let (ns, path) = match raw.split_once(':') {
Some(("", path)) => ("minecraft", path),
Some((ns, path)) => (ns, path),
None => ("minecraft", raw),
};
let ns_ok = ns != ".."
&& ns
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
let path_ok = path.chars().all(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
});
(ns_ok && path_ok).then(|| format!("{ns}:{path}"))
}
@@ -0,0 +1,38 @@
//! Key display names (`InputConstants.Key.getDisplayName`), shared by key
//! mappings and `keybind` text components.
use crate::text::Text;
/// InputConstants.Key.getDisplayName: one-character keys as the upper-case
/// character, others by translation.
pub fn display_name(key: &str) -> Text {
if let Some(rest) = key.strip_prefix("key.keyboard.")
&& rest.chars().count() == 1
{
let c = rest.to_uppercase();
return Text::literal(c);
}
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()
&& !crate::lang::has(key)
{
return Text::translate("key.mouse", &[Text::literal(n)]);
}
Text::translate(key, &[])
}
@@ -42,8 +42,12 @@ struct Bundled;
impl ResourceSource for Bundled { impl ResourceSource for Bundled {
fn read(&self, path: &str) -> Option<Vec<u8>> { fn read(&self, path: &str) -> Option<Vec<u8>> {
let body = match path { let body = match path {
"assets/horizon/lang/en_us.json" => include_str!("../assets/horizon/lang/en_us.json"), "assets/horizon/lang/en_us.json" => {
"assets/horizon/lang/ru_ru.json" => include_str!("../assets/horizon/lang/ru_ru.json"), include_str!("../../horizon-client/assets/horizon/lang/en_us.json")
}
"assets/horizon/lang/ru_ru.json" => {
include_str!("../../horizon-client/assets/horizon/lang/ru_ru.json")
}
_ => return None, _ => return None,
}; };
Some(body.as_bytes().to_vec()) Some(body.as_bytes().to_vec())
+23
View File
@@ -0,0 +1,23 @@
//! The client's lowest layer, below commands and gameplay: chat text and
//! translations, SNBT and NBT paths, text components, the scoreboard, boss
//! bars, game rules, block entity NBT tables, and the registry, particle and
//! sound source tables commands name. horizon-client re-exports each module
//! under its old path (`horizon_client::text`, ...).
#![forbid(unsafe_code)]
pub mod block_entity_nbt;
pub mod bossbar;
pub mod component;
pub mod fastutil_order;
pub mod gamerules;
pub mod identifier;
pub mod key_display;
pub mod lang;
pub mod nbt_path;
pub mod particle_type;
pub mod registries;
pub mod scoreboard;
pub mod snbt;
pub mod sound_source;
pub mod text;
pub mod uuid;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;
@@ -0,0 +1,209 @@
//! Particle types (`ParticleTypes`): the vanilla particle types with a client
//! implementation, by registry name, and their per-type flags.
macro_rules! particle_types {
($($variant:ident = $name:literal),* $(,)?) => {
/// Vanilla particle types with a client implementation here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParticleType { $($variant),* }
impl ParticleType {
pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*];
/// Registry path (`minecraft:<name>`), also the sprite-set file name.
pub fn name(self) -> &'static str {
match self { $(ParticleType::$variant => $name),* }
}
pub fn from_name(name: &str) -> Option<Self> {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
match name { $($name => Some(ParticleType::$variant),)* _ => None }
}
}
};
}
particle_types! {
Block = "block",
BlockCrumble = "block_crumble",
Trail = "trail",
DustPillar = "dust_pillar",
FallingDust = "falling_dust",
Smoke = "smoke",
LargeSmoke = "large_smoke",
WhiteSmoke = "white_smoke",
Flame = "flame",
SoulFireFlame = "soul_fire_flame",
CopperFireFlame = "copper_fire_flame",
SmallFlame = "small_flame",
Lava = "lava",
DrippingWater = "dripping_water",
FallingWater = "falling_water",
DrippingLava = "dripping_lava",
FallingLava = "falling_lava",
LandingLava = "landing_lava",
DrippingHoney = "dripping_honey",
FallingHoney = "falling_honey",
LandingHoney = "landing_honey",
FallingNectar = "falling_nectar",
FallingSporeBlossom = "falling_spore_blossom",
SporeBlossomAir = "spore_blossom_air",
DrippingObsidianTear = "dripping_obsidian_tear",
FallingObsidianTear = "falling_obsidian_tear",
LandingObsidianTear = "landing_obsidian_tear",
DrippingDripstoneWater = "dripping_dripstone_water",
FallingDripstoneWater = "falling_dripstone_water",
DrippingDripstoneLava = "dripping_dripstone_lava",
FallingDripstoneLava = "falling_dripstone_lava",
Splash = "splash",
Rain = "rain",
Bubble = "bubble",
SulfurBubbles = "sulfur_bubbles",
BubblePop = "bubble_pop",
BubbleColumnUp = "bubble_column_up",
CurrentDown = "current_down",
Underwater = "underwater",
Portal = "portal",
ReversePortal = "reverse_portal",
Enchant = "enchant",
Nautilus = "nautilus",
VaultConnection = "vault_connection",
Crit = "crit",
EnchantedHit = "enchanted_hit",
DamageIndicator = "damage_indicator",
Heart = "heart",
AngryVillager = "angry_villager",
HappyVillager = "happy_villager",
Composter = "composter",
Mycelium = "mycelium",
Dolphin = "dolphin",
EggCrack = "egg_crack",
Poof = "poof",
Explosion = "explosion",
ExplosionEmitter = "explosion_emitter",
CampfireCosySmoke = "campfire_cosy_smoke",
CampfireSignalSmoke = "campfire_signal_smoke",
Note = "note",
Dust = "dust",
TotemOfUndying = "totem_of_undying",
Firework = "firework",
EndRod = "end_rod",
Ash = "ash",
WhiteAsh = "white_ash",
CrimsonSpore = "crimson_spore",
WarpedSpore = "warped_spore",
CherryLeaves = "cherry_leaves",
PaleOakLeaves = "pale_oak_leaves",
TintedLeaves = "tinted_leaves",
Effect = "effect",
InstantEffect = "instant_effect",
EntityEffect = "entity_effect",
Witch = "witch",
Infested = "infested",
Cloud = "cloud",
Sneeze = "sneeze",
Snowflake = "snowflake",
Soul = "soul",
SculkSoul = "sculk_soul",
DragonBreath = "dragon_breath",
Gust = "gust",
SmallGust = "small_gust",
GustEmitterLarge = "gust_emitter_large",
GustEmitterSmall = "gust_emitter_small",
DustColorTransition = "dust_color_transition",
SculkCharge = "sculk_charge",
SculkChargePop = "sculk_charge_pop",
Shriek = "shriek",
SonicBoom = "sonic_boom",
Vibration = "vibration",
SweepAttack = "sweep_attack",
Glow = "glow",
WaxOn = "wax_on",
WaxOff = "wax_off",
ElectricSpark = "electric_spark",
Scrape = "scrape",
SquidInk = "squid_ink",
GlowSquidInk = "glow_squid_ink",
Item = "item",
ItemSlime = "item_slime",
ItemSnowball = "item_snowball",
ItemCobweb = "item_cobweb",
SulfurCubeGoo = "sulfur_cube_goo",
Flash = "flash",
Firefly = "firefly",
TrialSpawnerDetection = "trial_spawner_detection",
TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous",
TrialOmen = "trial_omen",
RaidOmen = "raid_omen",
OminousSpawning = "ominous_spawning",
Spit = "spit",
Fishing = "fishing",
DustPlume = "dust_plume",
RedPoplarLeaves = "red_poplar_leaves",
OrangePoplarLeaves = "orange_poplar_leaves",
YellowPoplarLeaves = "yellow_poplar_leaves",
PauseMobGrowth = "pause_mob_growth",
ResetMobGrowth = "reset_mob_growth",
BlockMarker = "block_marker",
}
impl ParticleType {
/// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`):
/// spawned regardless of distance.
pub fn override_limiter(self) -> bool {
matches!(
self,
Self::BlockMarker
| Self::DamageIndicator
| Self::ExplosionEmitter
| Self::Explosion
| Self::Gust
| Self::GustEmitterLarge
| Self::GustEmitterSmall
| Self::SonicBoom
| Self::SculkCharge
| Self::SculkChargePop
| Self::Vibration
| Self::Poof
| Self::Spit
| Self::SquidInk
| Self::SweepAttack
| Self::CampfireCosySmoke
| Self::CampfireSignalSmoke
| Self::GlowSquidInk
| Self::Glow
| Self::WaxOn
| Self::WaxOff
| Self::ElectricSpark
| Self::Scrape
| Self::TrialSpawnerDetection
| Self::TrialSpawnerDetectionOminous
| Self::VaultConnection
| Self::OminousSpawning
)
}
/// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class
/// hardcodes the translucent layer, drawn after translucent terrain.
/// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their
/// layer from the sprite instead (`Layer.bySprite`); see the `translucent`
/// sprite set on the engine.
pub fn translucent_layer(self) -> bool {
match self {
// CampfireSmokeParticle.
Self::CampfireCosySmoke | Self::CampfireSignalSmoke
// PlayerCloudParticle.
| Self::Cloud | Self::Sneeze
// SpellParticle.
| Self::Effect | Self::InstantEffect | Self::EntityEffect
| Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
// EmissiveRisingParticle.
| Self::Soul | Self::SculkSoul
// SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
// VibrationSignalParticle, FireflyParticle, OverlayParticle.
| Self::SculkCharge | Self::SculkChargePop | Self::Shriek
| Self::Vibration | Self::Firefly | Self::Flash
// SimpleAnimatedParticle and its subclasses: EndRodParticle,
// SparkParticle (firework), SquidInkParticle, TotemParticle.
| Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
| Self::TotemOfUndying
// FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
| Self::VaultConnection => true,
_ => false,
}
}
}
@@ -0,0 +1,188 @@
//! Registry contents and source state that commands validate and complete
//! arguments against (what the server's registry access holds).
use std::collections::BTreeMap;
/// Registry contents and source state used to validate and complete arguments.
#[derive(Clone, Debug, Default)]
pub struct Registries {
/// Permission level of the command source.
pub permission: u8,
pub items: Vec<String>,
pub item_tags: Vec<String>,
/// Block id -> (property, allowed values).
pub blocks: BTreeMap<String, Vec<(String, Vec<String>)>>,
pub block_tags: Vec<String>,
/// Entity types that `summon` can create.
pub summonable: Vec<String>,
/// Every entity type (selector `type=`).
pub entity_types: Vec<String>,
pub effects: Vec<String>,
pub enchantments: Vec<String>,
pub structures: Vec<String>,
pub biomes: Vec<String>,
pub dimensions: Vec<String>,
pub clocks: Vec<String>,
pub timelines: Vec<String>,
pub time_markers: Vec<String>,
pub advancements: Vec<String>,
/// Game rule name -> integer-valued.
pub game_rules: Vec<(String, bool)>,
pub players: Vec<String>,
/// Scoreboard objective names, team names and tracked score holders.
pub objectives: Vec<String>,
pub teams: Vec<String>,
pub tracked: Vec<String>,
/// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
pub functions: Vec<String>,
/// `/data ... storage` ids.
pub storages: Vec<String>,
/// Boss bar ids and datapack predicate ids.
pub bossbars: Vec<String>,
pub predicates: Vec<String>,
pub item_modifiers: Vec<String>,
pub schedules: Vec<String>,
pub stopwatches: Vec<String>,
pub recipes: Vec<String>,
pub sounds: Vec<String>,
pub damage_types: Vec<String>,
pub attributes: Vec<String>,
pub loot_tables: Vec<String>,
pub templates: Vec<String>,
pub random_sequences: Vec<String>,
pub datapacks_enabled: Vec<String>,
pub datapacks_disabled: Vec<String>,
pub function_tags: Vec<String>,
/// The block the source is looking at (relevant coordinates).
pub target_block: Option<[i32; 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>,
/// Blocks whose default state has a block entity.
pub block_entities: std::collections::BTreeSet<String>,
/// Block tag -> member blocks.
pub block_tag_members: BTreeMap<String, Vec<String>>,
/// Data component types with a codec (not transient).
pub persistent_components: Vec<String>,
/// Recipes `/recipe` can give (not special).
pub learnable_recipes: Vec<String>,
/// Advancement id -> criterion names.
pub advancement_criteria: BTreeMap<String, Vec<String>>,
/// World clock -> time markers shown in commands.
pub clock_time_markers: BTreeMap<String, Vec<String>>,
/// Trigger objectives the source may use (`/trigger` suggestions).
pub trigger_objectives: Vec<String>,
/// Objectives with the `trigger` criterion -> holder -> whether its score is locked.
pub trigger_scores: BTreeMap<String, BTreeMap<String, bool>>,
}
/// The ids and tag ids of one registry.
#[derive(Clone, Debug, Default)]
pub struct RegistryIds {
pub ids: Vec<String>,
pub tags: Vec<String>,
}
const EMPTY: &[String] = &[];
impl Registries {
/// 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
/// mob effects, data component types and dialogs, block entities and tag
/// members. Registries that data packs reload stay with the game.
pub fn fill_from_export(&mut self, r: &serde_json::Value) {
fn strings(v: &serde_json::Value) -> Vec<String> {
v.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
let fill = |field: &mut Vec<String>, key: &str| {
if field.is_empty() {
*field = strings(&r[key]);
}
};
fill(&mut self.effects, "effects");
fill(&mut self.enchantments, "enchantments");
fill(&mut self.attributes, "attributes");
fill(&mut self.damage_types, "damage_types");
fill(&mut self.templates, "templates");
fill(&mut self.persistent_components, "persistent_components");
fill(&mut self.learnable_recipes, "learnable_recipes");
const RELOADED: [&str; 5] = [
"minecraft:advancement",
"minecraft:recipe",
"minecraft:loot_table",
"minecraft:predicate",
"minecraft:item_modifier",
];
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) {
continue;
}
self.by_registry.insert(
name.clone(),
RegistryIds {
ids: strings(&entry["ids"]),
tags: strings(&entry["tags"]),
},
);
}
if self.block_entities.is_empty() {
self.block_entities = strings(&r["block_entities"]).into_iter().collect();
}
if self.block_tag_members.is_empty() {
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
self.block_tag_members.insert(tag.clone(), strings(members));
}
}
if self.clock_time_markers.is_empty() {
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
self.clock_time_markers
.insert(clock.clone(), strings(markers));
}
}
if self.advancement_criteria.is_empty() {
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
self.advancement_criteria
.insert(id.clone(), strings(criteria));
}
}
}
/// The element ids of a registry (sorted).
pub fn ids(&self, registry: &str) -> &[String] {
if let Some(r) = self.by_registry.get(registry) {
return &r.ids;
}
match registry {
"minecraft:item" => &self.items,
"minecraft:entity_type" => &self.entity_types,
"minecraft:mob_effect" => &self.effects,
"minecraft:enchantment" => &self.enchantments,
"minecraft:worldgen/structure" => &self.structures,
"minecraft:worldgen/biome" => &self.biomes,
"minecraft:world_clock" => &self.clocks,
"minecraft:timeline" => &self.timelines,
"minecraft:attribute" => &self.attributes,
"minecraft:damage_type" => &self.damage_types,
"minecraft:sound_event" => &self.sounds,
"minecraft:predicate" => &self.predicates,
"minecraft:item_modifier" => &self.item_modifiers,
"minecraft:loot_table" => &self.loot_tables,
"minecraft:recipe" => &self.recipes,
"minecraft:advancement" => &self.advancements,
_ => EMPTY,
}
}
/// The tag ids of a registry (sorted).
pub fn tags(&self, registry: &str) -> &[String] {
if let Some(r) = self.by_registry.get(registry) {
return &r.tags;
}
match registry {
"minecraft:item" => &self.item_tags,
"minecraft:block" => &self.block_tags,
_ => EMPTY,
}
}
}
@@ -2,9 +2,9 @@
//! `ObjectiveCriteria`, `NumberFormat`) and its saved data //! `ObjectiveCriteria`, `NumberFormat`) and its saved data
//! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`). //! (`data/minecraft/scoreboard.dat`, `ScoreboardSaveData.Packed`).
use crate::{ use crate::{
command::Registries,
component, component,
fastutil_order::{HashSetOrder, OpenOrder}, fastutil_order::{HashSetOrder, OpenOrder},
registries::Registries,
text::{self, Style, Text}, text::{self, Style, Text},
}; };
use horizon_world::nbt::Tag; use horizon_world::nbt::Tag;
@@ -1266,7 +1266,7 @@ fn entity_uuids(tag: &mut Tag) {
}) })
.collect::<Option<Vec<i32>>>(), .collect::<Option<Vec<i32>>>(),
Tag::String(s) => { Tag::String(s) => {
crate::save::uuid_from_text(&s.to_string_lossy()).map(Vec::from) crate::uuid::uuid_from_text(&s.to_string_lossy()).map(Vec::from)
} }
_ => None, _ => None,
}; };
@@ -0,0 +1,7 @@
//! Sound sources (`SoundSource`), by name.
/// SoundSource names in vanilla order.
pub const SOUND_SOURCES: [&str; 11] = [
"master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
"voice", "ui",
];
@@ -71,7 +71,7 @@ pub struct Style {
} }
/// A style's `font` field: an identifier (`alt` is `minecraft:alt`). /// A style's `font` field: an identifier (`alt` is `minecraft:alt`).
pub fn font_id(v: &Value) -> Option<String> { pub fn font_id(v: &Value) -> Option<String> {
crate::command::args::parse_identifier(v.as_str()?) crate::identifier::parse_identifier(v.as_str()?)
} }
impl Style { impl Style {
pub fn color(c: u32) -> Self { pub fn color(c: u32) -> Self {
+24
View File
@@ -0,0 +1,24 @@
//! UUIDs as vanilla's four-int form, to and from their text form.
pub fn uuid_text(u: [i32; 4]) -> String {
let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
)
}
pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> {
let hex: String = s.chars().filter(|c| *c != '-').collect();
if hex.len() != 32 {
return None;
}
let mut out = [0i32; 4];
for (i, v) in out.iter_mut().enumerate() {
*v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32;
}
Some(out)
}
+2
View File
@@ -9,6 +9,8 @@ description = "Horizon native development client"
[dependencies] [dependencies]
horizon-assets = { path = "../horizon-assets" } horizon-assets = { path = "../horizon-assets" }
horizon-client-core = { path = "../horizon-client-core" }
horizon-command = { path = "../horizon-command" }
horizon-core = { path = "../horizon-core" } horizon-core = { path = "../horizon-core" }
# The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority). # The server thread ahead of the workers (MinecraftServer.spin's Thread.setPriority).
horizon-threads = { path = "../horizon-threads" } horizon-threads = { path = "../horizon-threads" }
+24 -1
View File
@@ -1,7 +1,7 @@
//! Biome colours from the pinned biome definitions and colormaps //! Biome colours from the pinned biome definitions and colormaps
//! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`). //! (`Biome.getGrassColor`/`getFoliageColor`/..., `BlockTintSources`).
use crate::Result; use crate::Result;
use horizon_core::{noise::SimplexNoise, random::LegacyRandom}; use horizon_core::{noise::SimplexNoise, position::BlockPos, random::LegacyRandom};
use serde_json::Value; use serde_json::Value;
use std::{collections::HashMap, fs, path::Path}; use std::{collections::HashMap, fs, path::Path};
@@ -33,6 +33,8 @@ pub struct BiomeInfo {
pub increased_fire_burnout: bool, pub increased_fire_burnout: bool,
pub name: String, pub name: String,
pub temperature: f32, pub temperature: f32,
/// `temperature_modifier: frozen` (the frozen oceans).
pub frozen: bool,
pub downfall: f32, pub downfall: f32,
pub precipitation: bool, pub precipitation: bool,
pub grass: u32, pub grass: u32,
@@ -45,6 +47,26 @@ pub struct BiomeInfo {
pub fog: Option<u32>, pub fog: Option<u32>,
pub water_fog: u32, pub water_fog: u32,
} }
impl BiomeInfo {
/// `Biome.getHeightAdjustedTemperature`: the frozen modifier, then cooler
/// with height above `sea_level + 17`.
pub fn temperature_at(&self, pos: BlockPos, sea_level: i32) -> f32 {
use horizon_world::worldgen::biome_temperature::{
BiomeTemperatureSettings, TemperatureModifier,
};
BiomeTemperatureSettings {
base_temperature: self.temperature,
modifier: if self.frozen {
TemperatureModifier::Frozen
} else {
TemperatureModifier::None
},
has_precipitation: self.precipitation,
downfall: self.downfall,
}
.height_adjusted(pos, sea_level)
}
}
pub struct Biomes { pub struct Biomes {
pub list: Vec<BiomeInfo>, pub list: Vec<BiomeInfo>,
pub index: HashMap<String, u16>, pub index: HashMap<String, u16>,
@@ -135,6 +157,7 @@ impl Biomes {
.as_bool() .as_bool()
.unwrap_or(false), .unwrap_or(false),
temperature, temperature,
frozen: v["temperature_modifier"].as_str() == Some("frozen"),
downfall, downfall,
precipitation: v["has_precipitation"].as_bool().unwrap_or(true), precipitation: v["has_precipitation"].as_bool().unwrap_or(true),
grass: color(&effects["grass_color"]) grass: color(&effects["grass_color"])
+18
View File
@@ -370,6 +370,12 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
"minecraft:bat" => { "minecraft:bat" => {
map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag))); map.insert("BatFlags".into(), Tag::Byte(i8::from(m.extra.flag)));
} }
"minecraft:turtle" => {
map.insert("has_egg".into(), Tag::Byte(i8::from(m.extra.flag)));
if let Some(home) = m.extra.home {
map.insert("home_pos".into(), Tag::IntArray(home.to_vec()));
}
}
"minecraft:creaking" => { "minecraft:creaking" => {
// home_pos: the heart it is bound to. // home_pos: the heart it is bound to.
if let Some(home) = m.extra.home { if let Some(home) = m.extra.home {
@@ -876,6 +882,18 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
{ {
crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]); crate::mobs::creaking::set_transient(&mut m, [home[0], home[1], home[2]]);
} }
if m.species() == crate::mobs::Species::Turtle {
// Turtle.readAdditionalSaveData: `home_pos` (else where it stands) and `has_egg`.
m.extra.flag = flag(tag, "has_egg");
m.extra.home = Some(match tag.get("home_pos") {
Some(Tag::IntArray(home)) if home.len() == 3 => [home[0], home[1], home[2]],
_ => [
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
],
});
}
if m.species() == crate::mobs::Species::Wither { if m.species() == crate::mobs::Species::Wither {
m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32; m.extra.counter = number(tag.get("Invul")).unwrap_or(0) as i32;
} }
+86 -21
View File
@@ -102,7 +102,12 @@ mod maps;
mod minecarts; mod minecarts;
mod mob_blocks; mod mob_blocks;
mod mob_gear; mod mob_gear;
mod mod_browser;
#[cfg(feature = "mods")]
mod mod_browser_recipes;
mod mod_input; mod mod_input;
#[cfg(feature = "mods")]
mod mod_recipes;
mod mod_render; mod mod_render;
mod mods; mod mods;
mod mount_menu; mod mount_menu;
@@ -370,7 +375,7 @@ impl Options {
match arg.as_str() { match arg.as_str() {
"--help" | "-h" => { "--help" | "-h" => {
println!( println!(
"Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.", "Horizon — Minecraft Java Edition {} in Rust\n\n --resources PATH Prepared resources (horizon-prepare)\n --render-distance N Chunks, 2..64 (default 12)\n --world NAME World folder under saves/ (default \"New World\")\n --seed N World seed for new worlds (default 0)\n --width N, --height N Window size (default 1280 x 720)\n --creative Creative mode (default survival)\n --test-terrain Simple test terrain instead of vanilla generation\n --frames N Exit after N frames (testing)\n --world-frames N Exit after N frames drawn in the world (testing)\n --smoke-report PATH Write a JSON report on exit\n --benchmark SCENARIO Run a benchmark (standard, village, forest, ocean, mountain), write its report to benchmarks/ and quit\n --control Accept horizon-ctl commands on a local socket\n --control-socket PATH Control socket path (default $XDG_RUNTIME_DIR/horizon-control.sock)\n --server HOST[:PORT] Join a multiplayer server (offline mode) at start\n --quickPlaySingleplayer WORLD Open this world of saves/ at start, only if it exists (vanilla's)\n --quickPlayMultiplayer HOST[:PORT] The same as --server (vanilla's name)\n --name NAME Player name for multiplayer (default: generated once, kept in horizon-player.txt)\n --session-file PATH Signed-in account from the launcher (read once, then deleted)\n --dev-mod PATH A Horizon mod (.hmod or folder) to develop: always on, reloaded when rebuilt\n --in-frame Run single player's world in the frame, not on its server thread\n --pregen Add Horizon's /pregen command (docs/pregeneration.md)\n\nControls: mouse look, WASD move, Space jump, Left Shift sneak, Left Ctrl sprint,\nleft click break, right click place/use, 1-9/scroll hotbar, E inventory,\nQ drop, F3 debug, Esc pause.",
horizon_core::VANILLA_VERSION horizon_core::VANILLA_VERSION
); );
return Ok(None); return Ok(None);
@@ -425,6 +430,16 @@ impl Options {
"--width" => o.window_size[0] = value.parse::<u32>()?.max(1), "--width" => o.window_size[0] = value.parse::<u32>()?.max(1),
"--height" => o.window_size[1] = value.parse::<u32>()?.max(1), "--height" => o.window_size[1] = value.parse::<u32>()?.max(1),
"--world" => o.world = Some(value), "--world" => o.world = Some(value),
// Vanilla's quick play (Main, QuickPlay.joinSingleplayerWorld): only a
// world that exists opens; else the title screen. --world also creates one.
"--quickPlaySingleplayer" => {
let folder = std::env::current_dir()?.join("saves").join(&value);
if folder.join("level.dat").is_file() {
o.world = Some(value);
} else {
eprintln!("Quick play: there is no world {value} in saves/");
}
}
"--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?), "--dev-mod" => o.dev_mods.push(std::path::absolute(&value)?),
"--benchmark" => { "--benchmark" => {
if horizon_client::benchmark::scenes(&value).is_none() { if horizon_client::benchmark::scenes(&value).is_none() {
@@ -435,7 +450,7 @@ impl Options {
} }
o.benchmark = Some(value); o.benchmark = Some(value);
} }
"--server" => o.server = Some(value), "--server" | "--quickPlayMultiplayer" => o.server = Some(value),
"--name" => o.player_name = Some(value), "--name" => o.player_name = Some(value),
"--session-file" => session_file = Some(value), "--session-file" => session_file = Some(value),
"--control-socket" => o.control = Some(value.into()), "--control-socket" => o.control = Some(value.into()),
@@ -3115,6 +3130,11 @@ impl Game<'_> {
kind: "hatch_sniffer", kind: "hatch_sniffer",
.. ..
} => self.hatch_sniffer([pos.x, pos.y, pos.z]), } => self.hatch_sniffer([pos.x, pos.y, pos.z]),
LevelEvent::BlockEvent {
pos,
state,
kind: "hatch_turtles",
} => self.hatch_turtles([pos.x, pos.y, pos.z], state),
LevelEvent::BlockEvent { LevelEvent::BlockEvent {
pos, pos,
kind: "portal_spawn", kind: "portal_spawn",
@@ -4512,6 +4532,22 @@ impl Game<'_> {
}; };
self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5; self.eye += (camera_eye.unwrap_or(eye_height) - self.eye) * 0.5;
let crouching = player.pose == horizon_client::pose::Pose::Crouching; let crouching = player.pose == horizon_client::pose::Pose::Crouching;
// `LivingEntity.baseTick` (Soul Speed) comes before `aiStep` (the
// glide's wear): both draw from the level random.
if let Some((at, velocity)) = self.tick_soul_speed() {
self.particles.send_particles(
&horizon_client::particles::ParticleOptions::simple(
horizon_client::particles::ParticleType::Soul,
),
at,
velocity,
1.0,
0,
);
if let Some(host) = self.lan.as_ref() {
lan_particles::send_soul_particle(host, at, velocity);
}
}
// `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear. // `ItemStack.hurtAndBreak` for the glide: Unbreaking can save the wear.
if glider_wear > 0 if glider_wear > 0
&& !self.creative && !self.creative
@@ -5402,6 +5438,7 @@ impl Game<'_> {
Screen::CommandBlock => self.draw_command_block(&mut batch), Screen::CommandBlock => self.draw_command_block(&mut batch),
Screen::Inventory => { Screen::Inventory => {
self.draw_inventory(&mut batch); self.draw_inventory(&mut batch);
self.draw_mod_browser(&mut batch);
} }
Screen::Creative => { Screen::Creative => {
self.draw_creative(&mut batch); self.draw_creative(&mut batch);
@@ -5794,6 +5831,7 @@ impl Game<'_> {
self.last_inv_click = None; self.last_inv_click = None;
} }
pub(super) fn close_container(&mut self) { pub(super) fn close_container(&mut self) {
self.mod_browser_closed();
self.reset_inventory_clicks(); self.reset_inventory_clicks();
self.close_station(); self.close_station();
self.mount_closed(); self.mount_closed();
@@ -6521,6 +6559,9 @@ impl Game<'_> {
fn inventory_press(&mut self, right: bool) { fn inventory_press(&mut self, right: bool) {
use horizon_client::container_screen::Target; use horizon_client::container_screen::Target;
use horizon_client::menu::Input; use horizon_client::menu::Input;
if self.mod_browser_press(right) {
return;
}
if !right && self.sort_press() { if !right && self.sort_press() {
return; return;
} }
@@ -6704,24 +6745,8 @@ impl Game<'_> {
} }
/// `hasClickedOutside` of the open screen at the cursor. /// `hasClickedOutside` of the open screen at the cursor.
fn clicked_outside(&self, batch: &HudBatch) -> bool { fn clicked_outside(&self, batch: &HudBatch) -> bool {
use horizon_client::container_screen::{Book, Image, clicked_outside}; use horizon_client::container_screen::{Book, clicked_outside};
let (ox, oy) = self.inventory_origin(batch); let image = self.container_image(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
let image = Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
};
let book = self let book = self
.recipe_book_area(batch) .recipe_book_area(batch)
.map(|(visible, tab_hovered)| Book { .map(|(visible, tab_hovered)| Book {
@@ -6735,6 +6760,26 @@ impl Game<'_> {
book, book,
) )
} }
/// The open container screen's window: its place and size.
fn container_image(&self, batch: &HudBatch) -> horizon_client::container_screen::Image {
let (ox, oy) = self.inventory_origin(batch);
let (shift, width, height) = if self.screen == Screen::Creative {
(0.0, Creative::WIDTH as i32, Creative::HEIGHT as i32)
} else {
let (shift, width) = match self.station.as_ref().map(|s| s.kind) {
Some(stations::Kind::Merchant) => (-50.0, 276),
Some(stations::Kind::Beacon) => (beacon::SHIFT, 230),
_ => (0.0, 176),
};
(shift, width, self.screen_height() as i32)
};
horizon_client::container_screen::Image {
left: (ox + shift) as i32,
top: oy as i32,
width,
height,
}
}
/// A click outside the window (slot id -999): `THROW` does nothing; a /// A click outside the window (slot id -999): `THROW` does nothing; a
/// `PICKUP` drops the carried stack (left) or one of it (right), thrown /// `PICKUP` drops the carried stack (left) or one of it (right), thrown
/// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`). /// from the hand (`AbstractContainerMenu.doClick`, `LivingEntity.drop`).
@@ -6895,7 +6940,7 @@ impl Game<'_> {
} }
} }
fn click_inventory(&mut self, right: bool) { fn click_inventory(&mut self, right: bool) {
if self.mount_click(right) { if self.mod_browser_press(right) || self.mount_click(right) {
return; return;
} }
if self.recipe_book_click(right) { if self.recipe_book_click(right) {
@@ -8067,6 +8112,7 @@ impl Game<'_> {
creative: bool, creative: bool,
create: Option<&horizon_client::title::WorldOptions>, create: Option<&horizon_client::title::WorldOptions>,
) -> Result<()> { ) -> Result<()> {
world_loading::world_data_used();
if self.defer_world_entry(PendingWorldEntry::Local { if self.defer_world_entry(PendingWorldEntry::Local {
folder: folder.to_owned(), folder: folder.to_owned(),
name: name.map(str::to_owned), name: name.map(str::to_owned),
@@ -12127,6 +12173,14 @@ impl ApplicationHandler for Game<'_> {
// The recipe book's search box takes every key but Escape. // The recipe book's search box takes every key but Escape.
self.recipe_key(&event); self.recipe_key(&event);
} }
WindowEvent::KeyboardInput { event, .. }
if self.mod_browser_typing()
&& event.state == ElementState::Pressed
&& !matches!(event.physical_key, PhysicalKey::Code(KeyCode::Escape)) =>
{
// A mod's item panel's search box, as the recipe book's.
self.mod_browser_key(&event);
}
WindowEvent::KeyboardInput { event, .. } WindowEvent::KeyboardInput { event, .. }
if self.station_typing() if self.station_typing()
&& event.state == ElementState::Pressed && event.state == ElementState::Pressed
@@ -13036,6 +13090,17 @@ impl Game<'_> {
if self.rest_loader.is_some() { if self.rest_loader.is_some() {
return Ok(()); return Ok(());
} }
let on_world_screens = self.title.as_ref().is_some_and(|title| {
!matches!(
title.mode,
horizon_client::title::Mode::Main | horizon_client::title::Mode::Multiplayer(_)
)
});
world_loading::preload_world_data(
on_world_screens,
&self.options.resources,
self.pack.assets.registry,
);
if std::mem::take(&mut self.pending_pack_reload) { if std::mem::take(&mut self.pending_pack_reload) {
self.reload_packs(); self.reload_packs();
} }
@@ -115,6 +115,7 @@ impl Game<'_> {
"in_fire" | "campfire" | "hot_floor" => DamageKind::InFire, "in_fire" | "campfire" | "hot_floor" => DamageKind::InFire,
"lava" => DamageKind::Lava, "lava" => DamageKind::Lava,
"drown" => DamageKind::Drown, "drown" => DamageKind::Drown,
"dry_out" => DamageKind::DryOut,
"magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic, "magic" | "indirect_magic" | "dragon_breath" => DamageKind::Magic,
"sting" => DamageKind::Sting, "sting" => DamageKind::Sting,
"cactus" | "sweet_berry_bush" => DamageKind::Cactus, "cactus" | "sweet_berry_bush" => DamageKind::Cactus,
@@ -628,6 +628,9 @@ impl Game<'_> {
// The port, or the game rules' search and number boxes. // The port, or the game rules' search and number boxes.
Screen::WorldOptions if text == "\\b" => self.world_options_text(None), Screen::WorldOptions if text == "\\b" => self.world_options_text(None),
Screen::WorldOptions => self.world_options_text(Some(text)), Screen::WorldOptions => self.world_options_text(Some(text)),
Screen::Inventory if self.mod_browser_typing() => {
self.mod_browser_text((text != "\\b").then_some(text), text == "\\b")
}
Screen::Inventory if self.recipe_search_focused() => { Screen::Inventory if self.recipe_search_focused() => {
self.recipe_text(Some(text), false) self.recipe_text(Some(text), false)
} }
+71 -2
View File
@@ -1289,6 +1289,10 @@ impl Game<'_> {
self.mob_vibration_particle(from, to, ticks) self.mob_vibration_particle(from, to, ticks)
} }
MobEvent::DigParticles { at } => self.warden_dig_particles(at), MobEvent::DigParticles { at } => self.warden_dig_particles(at),
MobEvent::BlockBreakEffect { pos, block } => {
let state = self.world.block(block[0], block[1], block[2]);
self.destroy_particles(pos, state);
}
MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius), MobEvent::Darkness { at, radius } => self.apply_darkness(at, radius),
MobEvent::CreakingHurt { MobEvent::CreakingHurt {
home, home,
@@ -1327,11 +1331,51 @@ impl Game<'_> {
m.ai.aggressive |= aggressive; m.ai.aggressive |= aggressive;
} }
} }
MobEvent::GiftLoot { mob, table, at } => self.drop_gift_loot(mob, table, at), MobEvent::GiftLoot { mob, table, at } => {
// Turtle.ageBoundaryReached: only with mob loot on.
if table == "minecraft:gameplay/turtle_grow" && !self.ui.rules.bool("mob_drops")
{
continue;
}
self.drop_gift_loot(mob, table, at);
}
} }
} }
Ok(()) Ok(())
} }
/// `TurtleEggBlock.randomTick` at the last hatch stage: one baby turtle
/// per egg, a day from grown, with the egg as its home (the sound, the
/// crumbs and the block's removal came from the level).
pub(super) fn hatch_turtles(
&mut self,
pos: [i32; 3],
state: horizon_world::registry::BlockStateId,
) {
let eggs = self
.pack
.assets
.registry
.state(state)
.and_then(|s| s.properties.get("eggs"))
.and_then(|v| v.parse::<i32>().ok())
.unwrap_or(1);
for i in 0..eggs {
let at = [
f64::from(pos[0]) + 0.3 + f64::from(i) * 0.2,
f64::from(pos[1]),
f64::from(pos[2]) + 0.3,
];
if let Some(id) = self.spawn_mob("minecraft:turtle", at, true)
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == id)
{
m.extra.age = -24000;
m.extra.home = Some(pos);
m.yaw = 0.0;
m.body_yaw = 0.0;
m.head_yaw = 0.0;
}
}
}
fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) { fn apply_setup(&mut self, id: u32, setup: &SpawnSetup) {
let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else { let Some(m) = self.mobs.iter_mut().find(|m| m.id == id) else {
return; return;
@@ -1394,6 +1438,8 @@ impl Game<'_> {
.unwrap_or_else(|| parent.clone()); .unwrap_or_else(|| parent.clone());
let mut child = parent.clone(); let mut child = parent.clone();
child.baby = true; child.baby = true;
// TurtleBreedGoal.breed triggers it without a child.
let turtle = p.species() == Species::Turtle;
if matches!( if matches!(
( (
p.species(), p.species(),
@@ -1406,7 +1452,7 @@ impl Game<'_> {
) { ) {
child.kind = "minecraft:mule".into(); child.kind = "minecraft:mule".into();
} }
self.trigger_bred(&parent, &partner_view, Some(&child)); self.trigger_bred(&parent, &partner_view, (!turtle).then_some(&child));
} }
if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) { if let Some(q) = self.mobs.iter_mut().find(|m| m.id == partner) {
q.extra.age = 6000; q.extra.age = 6000;
@@ -1418,6 +1464,19 @@ impl Game<'_> {
self.lay_sniffer_egg(&p); self.lay_sniffer_egg(&p);
return; return;
} }
// TurtleBreedGoal.breed: the goal gave the mother her egg; only the
// experience is left, and only with mob loot on.
if p.species() == Species::Turtle {
// One `new ExperienceOrb` of 1 to 7 from the mother's random (not
// split up as `ExperienceOrb.award` does).
if self.ui.rules.bool("mob_drops")
&& let Some(m) = self.mobs.iter_mut().find(|m| m.id == parent)
{
let xp = 1 + m.random.next_int_bound(7).unwrap_or(0) as u32;
self.add_orb([p.position.x, p.position.y, p.position.z], xp);
}
return;
}
let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0; let coin = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0; let coin2 = self.world.random.next_int_bound(2).unwrap_or(0) == 0;
// A horse and a donkey have a mule. // A horse and a donkey have a mule.
@@ -2695,6 +2754,7 @@ impl Game<'_> {
let mut handled = true; let mut handled = true;
let mut drops: Vec<(String, u32)> = Vec::new(); let mut drops: Vec<(String, u32)> = Vec::new();
let is_food = m.kind.food.contains(&item); let is_food = m.kind.food.contains(&item);
let baby_turtle = species == Species::Turtle && m.is_baby();
match species { match species {
Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => { Species::Cow | Species::Mooshroom if item == "minecraft:bucket" && !m.is_baby() => {
give = Some("minecraft:milk_bucket"); give = Some("minecraft:milk_bucket");
@@ -2984,6 +3044,14 @@ impl Game<'_> {
if !handled { if !handled {
return Ok(false); return Ok(false);
} }
// Turtle.ageBoundaryReached: food that finishes a baby's growth.
if baby_turtle && !self.mobs[index].is_baby() {
self.handle_mob_events(vec![MobEvent::GiftLoot {
mob: self.mobs[index].id,
table: "minecraft:gameplay/turtle_grow",
at: feet,
}])?;
}
self.swing_arm(); self.swing_arm();
if let Some(s) = sound { if let Some(s) = sound {
let pitch = let pitch =
@@ -3456,6 +3524,7 @@ pub(super) fn damage_type(kind: horizon_client::mobs::DamageKind, player: bool)
K::InFire => "minecraft:in_fire", K::InFire => "minecraft:in_fire",
K::Lava => "minecraft:lava", K::Lava => "minecraft:lava",
K::Drown => "minecraft:drown", K::Drown => "minecraft:drown",
K::DryOut => "minecraft:dry_out",
K::Magic => "minecraft:magic", K::Magic => "minecraft:magic",
K::Sting => "minecraft:sting", K::Sting => "minecraft:sting",
K::Cactus => "minecraft:cactus", K::Cactus => "minecraft:cactus",
@@ -3,10 +3,14 @@
//! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power //! unbreaking (`minecraft:item_damage`), sharpness/smite/bane and power
//! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`), //! (`minecraft:damage`), knockback, fire aspect, infinity (`minecraft:ammo_use`),
//! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and //! thorns (`minecraft:post_attack`), mending (`minecraft:repair_with_xp`) and
//! the armor attribute effects (respiration, depth strider, ...). //! the armor attribute effects (respiration, depth strider, ...) and Soul
//! Speed's `location_changed` and `tick` effects.
use super::Game; use super::Game;
use horizon_client::{enchant::EffectContext, items::ItemStack}; use horizon_client::{
use horizon_core::random::RandomSource; enchant::{EffectContext, Enchantments, level_value},
items::ItemStack,
};
use horizon_core::{position::BlockPos, random::RandomSource};
/// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`). /// Where Mending found a damaged item (`EnchantedItemInUse.inSlot`).
#[derive(Clone, Copy)] #[derive(Clone, Copy)]
@@ -458,6 +462,134 @@ impl Game<'_> {
} }
ignite ignite
} }
/// Soul Speed (`data/minecraft/enchantment/soul_speed.json`), the parts of
/// `Enchantment.runLocationChangedEffects` and `tick` that file uses. The
/// `location_changed` effects run when the player enters a new block, lands,
/// or its boots change:
/// - the speed and movement efficiency modifiers turn on over a soul speed
/// block (not flying, not riding) and stay on while airborne, then off
/// (`enchantment_active_check`);
/// - the boots lose 1 durability with a 4% chance when on such a block.
///
/// Every fifth tick the player walking on one also gets a soul particle
/// (returned as its position and velocity, for the caller to show or send
/// to the players around) and sometimes a sound. Runs for the window's own
/// player and for each guest on the server (`guest_server_tick`); a remote
/// client leaves it to its server.
pub(super) fn tick_soul_speed(&mut self) -> Option<([f64; 3], [f64; 3])> {
const ID: &str = "minecraft:soul_speed";
let player = self.player.as_mut()?;
if player.client_side {
return None;
}
let level = self.armor[3]
.as_ref()
.map_or(0, |s| s.enchantment_level(ID));
let position = player.position;
let (on_ground, flying) = (player.ground.on_ground, player.flying);
let moved = position.subtract(player.old_position);
let (tick, width) = (player.health.tick_count, player.dimensions.width);
let fx = &mut player.location_effects;
let on_soul = fx.on_soul_speed_block;
let block = BlockPos::containing(position);
let changed_block = fx.block.replace(block) != Some(block);
let landed = std::mem::take(&mut fx.landed);
// Changed boots: `stopLocationBasedEffects`, then the effects run again.
let equipped = std::mem::replace(&mut fx.boots_level, level) != level;
let was_active = fx.applied_level;
let mut active = was_active > 0 && !equipped;
let mut wear = false;
if level > 0 && (changed_block || landed || equipped) {
let riding = self.riding.is_some();
let wanted = !riding && !flying && (on_soul || (active && !on_ground));
active = wanted;
// `random_chance` is the first term of the wear's `all_of`: it
// draws from the level random before the block is looked at.
let roll = self.world.random.next_float() < 0.04;
wear = roll && on_ground && on_soul;
}
fx.applied_level = if active { level } else { 0 };
// `Entity.getKnownMovement` horizontal speed of at least 1.0E-5.
let walking = moved.x * moved.x + moved.z * moved.z >= 1.0e-10;
let tick_effects = level > 0 && !flying && on_ground && walking && on_soul && tick % 5 == 0;
// The attribute effects were applied to the player before: swap them.
if was_active > 0 && (!active || equipped) {
for (attribute, id, _, op) in
soul_speed_modifiers(&self.res.stations().enchantments, was_active)
{
let _ = player.set_modifier(&attribute, &id, 0.0, &op, false);
}
}
if active && (was_active == 0 || equipped) {
for (attribute, id, amount, op) in
soul_speed_modifiers(&self.res.stations().enchantments, level)
{
let _ = player.set_modifier(&attribute, &id, amount, &op, true);
}
}
if wear && !self.creative {
self.wear_boots(1);
}
if level == 0 {
return None;
}
let r = &mut self.world.random;
// `spawn_particles`: in the bounding box, 0.1 above the feet, thrown
// back against the movement (-0.2) and up (0.1).
let particle = tick_effects.then(|| {
let x = position.x + (r.next_double() - 0.5) * f64::from(width);
let z = position.z + (r.next_double() - 0.5) * f64::from(width);
(
[x, position.y + 0.1, z],
[moved.x * -0.2, 0.1, moved.z * -0.2],
)
});
// `play_sound`: its `random_chance` (35%) comes first in its `all_of`,
// so the level random is drawn every tick the boots are worn; volume
// 0.6, pitch 0.6 to 1.0.
if r.next_float() < 0.35 && tick_effects {
let pitch = r.next_float() * 0.4 + 0.6;
self.audio.play(
"minecraft:particle.soul_escape",
Some([position.x, position.y, position.z]),
0.6,
pitch,
);
}
particle
}
/// `ItemStack.hurtAndBreak` on the worn boots (`change_item_damage`):
/// Unbreaking applies, and they break when worn out.
fn wear_boots(&mut self, amount: u32) {
let Some(stack) = self.armor[3].clone() else {
return;
};
let loss = self.durability_loss(&stack, amount);
let max = self
.res
.items()
.get(&stack.item)
.map_or(0, |info| info.max_damage);
if max == 0 {
return;
}
let Some(boots) = self.armor[3].as_mut() else {
return;
};
boots.damage += loss;
if boots.damage >= max {
self.armor[3] = None;
if let Some(eye) = self.eye_position() {
self.audio.play(
"minecraft:entity.item.break",
Some(eye),
0.8,
0.8 + self.world.random.next_float() * 0.4,
);
}
self.apply_equipment();
}
}
/// Enchantment attribute modifiers of worn armor (respiration, depth strider...). /// Enchantment attribute modifiers of worn armor (respiration, depth strider...).
/// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`), /// Each piece's modifier id ends with its slot (`EnchantmentAttributeEffect.idForSlot`),
/// so the same enchantment on two pieces stacks instead of replacing itself. /// so the same enchantment on two pieces stacks instead of replacing itself.
@@ -481,3 +613,28 @@ impl Game<'_> {
self.potions.enchant_modifiers = wanted; self.potions.enchant_modifiers = wanted;
} }
} }
/// Soul Speed's `attribute` effects at `level` (attribute, id, amount, operation),
/// the id taking the boots slot like `EnchantmentAttributeEffect.idForSlot`.
fn soul_speed_modifiers(
enchantments: &Enchantments,
level: u32,
) -> Vec<(String, String, f64, String)> {
let Some(e) = enchantments.get("minecraft:soul_speed") else {
return Vec::new();
};
e.effects["minecraft:location_changed"][0]["effect"]["effects"]
.as_array()
.into_iter()
.flatten()
.filter(|a| a["type"] == "minecraft:attribute")
.map(|a| {
(
a["attribute"].as_str().unwrap_or("").to_owned(),
format!("{}/feet", a["id"].as_str().unwrap_or("")),
f64::from(level_value(&a["amount"], level)),
a["operation"].as_str().unwrap_or("add_value").to_owned(),
)
})
.collect()
}
+53 -22
View File
@@ -126,28 +126,7 @@ impl Game<'_> {
pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> { pub(super) fn find_player_spawn(&mut self, suggestion: [i32; 3]) -> Result<Option<Vec3>> {
let mut finder = match self.player_spawn { let mut finder = match self.player_spawn {
Some(finder) => finder, Some(finder) => finder,
None if self.level.game_mode == 2 => { None => self.spawn_finder(suggestion),
// Adventure mode: the suggestion itself.
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
finder
}
None => {
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
}; };
let found = loop { let found = loop {
let Some(candidate) = finder.next_candidate() else { let Some(candidate) = finder.next_candidate() else {
@@ -176,6 +155,58 @@ impl Game<'_> {
self.player_spawn = found.is_none().then_some(finder); self.player_spawn = found.is_none().then_some(finder);
Ok(found) Ok(found)
} }
/// A new PlayerSpawnFinder around `suggestion`: the respawn radius, cut
/// by the world border; the suggestion itself in adventure mode.
fn spawn_finder(&self, suggestion: [i32; 3]) -> PlayerSpawnFinder {
if self.level.game_mode == 2 {
let mut finder = PlayerSpawnFinder::new(suggestion, 0, |_| 0);
finder.next_candidate();
return finder;
}
let mut radius = self.ui.rules.int("respawn_radius").max(0);
let to_border = self
.border
.distance(f64::from(suggestion[0]), f64::from(suggestion[2]))
.floor() as i32;
if to_border < radius {
radius = to_border;
}
if to_border <= 1 {
radius = 1;
}
PlayerSpawnFinder::new(suggestion, radius, |n| {
entity_random().next_int_bound(n).unwrap_or(0)
})
}
/// ServerPlayer.adjustSpawnLocation for a server's new player: where
/// PlayerSpawnFinder.findSpawn puts their feet around the world spawn
/// (`spawn`, the feet there), so that players new to a world don't all
/// stand in one spot. Vanilla waits for each candidate's chunk; a server
/// tick can't, so a candidate in a chunk not loaded yet is passed over,
/// and `spawn` stays when the search never reaches a loaded column.
pub(super) fn server_player_spawn(&self, spawn: [f64; 3]) -> [f64; 3] {
let suggestion = spawn.map(|v| v.floor() as i32);
let mut finder = self.spawn_finder(suggestion);
while let Some(candidate) = finder.next_candidate() {
let (x, z) = match candidate {
SpawnCandidate::Column(x, z) => (x, z),
SpawnCandidate::Suggestion => (suggestion[0], suggestion[2]),
};
if !self.streaming.is_lit(x >> 4, z >> 4) {
continue;
}
let feet = match candidate {
SpawnCandidate::Column(x, z) => level_respawn_pos(&self.spawn_columns(), x, z)
.filter(|&pos| self.player_fits(pos))
.map(bottom_center),
SpawnCandidate::Suggestion => Some(self.fixup_spawn_height(suggestion)),
};
if let Some(feet) = feet {
return [feet.x, feet.y, feet.z];
}
}
spawn
}
/// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the /// PlayerSpawnFinder.noCollisionNoLiquid: a player's box standing at the
/// block's bottom centre touches no block or liquid. /// block's bottom centre touches no block or liquid.
fn player_fits(&self, pos: [i32; 3]) -> bool { fn player_fits(&self, pos: [i32; 3]) -> bool {
+27 -8
View File
@@ -24,11 +24,24 @@ use horizon_protocol::{
}; };
use std::{ use std::{
collections::HashMap, collections::HashMap,
sync::{Arc, OnceLock}, sync::{Arc, Mutex},
}; };
/// The registries and tags are the same for every world: load them once. /// The registries and tags are the same for every world: load them once.
static SYNC: OnceLock<std::result::Result<Arc<SyncData>, String>> = OnceLock::new(); static SYNC: Mutex<Option<std::result::Result<Arc<SyncData>, String>>> = Mutex::new(None);
/// The registries and tags a server sends, loaded from `root` the first time.
pub(super) fn sync_data(root: &std::path::Path) -> std::result::Result<Arc<SyncData>, String> {
let mut sync = SYNC.lock().unwrap_or_else(|e| e.into_inner());
sync.get_or_insert_with(|| SyncData::load(root).map(Arc::new))
.clone()
}
/// Let go of what `sync_data` loaded: for a preload no world used
/// (game/world_loading.rs).
pub(super) fn forget_sync_data() {
*SYNC.lock().unwrap_or_else(|e| e.into_inner()) = None;
}
/// The settings of the open world (WorldOptionsScreen's multiplayer section). /// The settings of the open world (WorldOptionsScreen's multiplayer section).
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
@@ -562,10 +575,7 @@ impl Game<'_> {
config: HubConfig, config: HubConfig,
host: Option<u128>, host: Option<u128>,
) -> Result<()> { ) -> Result<()> {
let root = self.options.resources.clone(); let sync = sync_data(&self.options.resources)?;
let sync = SYNC
.get_or_init(|| SyncData::load(&root).map(Arc::new))
.clone()?;
let biome_names: Vec<String> = self let biome_names: Vec<String> = self
.res .res
.biomes() .biomes()
@@ -1128,8 +1138,17 @@ impl Game<'_> {
g.game_mode = default_mode; g.game_mode = default_mode;
} }
if !known { if !known {
g.position = spawn; // ServerPlayer.adjustSpawnLocation: a player new to the world
g.previous_position = spawn; // stands where PlayerSpawnFinder puts them, not all on one spot
// (it reads the loaded level, which holds the spawn when it is
// the overworld).
let feet = if self.dim == super::Dim::Overworld {
self.server_player_spawn(spawn)
} else {
spawn
};
g.position = feet;
g.previous_position = feet;
g.health = 20.0; g.health = 20.0;
g.food = 20; g.food = 20;
g.dimension = super::Dim::Overworld.id().to_owned(); g.dimension = super::Dim::Overworld.id().to_owned();
@@ -2183,6 +2183,7 @@ impl Game<'_> {
let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height()); let in_wall = !g.sleeping && self.in_wall(g.position, g.eye_height());
let at = g.position; let at = g.position;
let sneaking = g.sneaking; let sneaking = g.sneaking;
let mut soul = None;
let events = self.as_guest(host, conn, |game| { let events = self.as_guest(host, conn, |game| {
let (rules, motion) = (game.world.health_rules, game.motion); let (rules, motion) = (game.world.health_rules, game.motion);
let health = &motion.health; let health = &motion.health;
@@ -2252,6 +2253,7 @@ impl Game<'_> {
w.player.shift_key_down = sneaking; w.player.shift_key_down = sneaking;
w.player.freeze_immune = freeze_immune; w.player.freeze_immune = freeze_immune;
let _ = w.server_block_damage(start); let _ = w.server_block_damage(start);
let _ = w.update_soul_speed_block();
let _ = w.tick_environment_damage(); let _ = w.tick_environment_damage();
let _ = w.apply_fire_contact(); let _ = w.apply_fire_contact();
let _ = w.server_hazards_tick(in_wall); let _ = w.server_hazards_tick(in_wall);
@@ -2279,6 +2281,9 @@ impl Game<'_> {
// LivingEntity.baseTick: outside the world border, then tickEffects. // LivingEntity.baseTick: outside the world border, then tickEffects.
game.border_damage(); game.border_damage();
game.tick_mob_effects(); game.tick_mob_effects();
// Soul Speed's effects (LivingEntity.baseTick's location_changed
// and tick effects); its particle goes to the players around.
soul = game.tick_soul_speed();
let Some(player) = game.player.as_mut() else { let Some(player) = game.player.as_mut() else {
return (Vec::new(), None); return (Vec::new(), None);
}; };
@@ -2307,6 +2312,9 @@ impl Game<'_> {
let Some((events, marked)) = events else { let Some((events, marked)) = events else {
return; return;
}; };
if let Some((at, velocity)) = soul {
super::lan_particles::send_soul_particle(host, at, velocity);
}
self.as_guest(host, conn, |game| game.tick_player_sculk_events()); self.as_guest(host, conn, |game| game.tick_player_sculk_events());
for event in events { for event in events {
match event { match event {
@@ -24,6 +24,35 @@ fn rgb(c: [f32; 4]) -> [f32; 3] {
[c[0], c[1], c[2]] [c[0], c[1], c[2]]
} }
/// `ServerLevel.sendParticles` of one soul particle moving by `velocity`
/// (Soul Speed's `spawn_particles`): sent to the players within 32 blocks.
pub(super) fn send_soul_particle(host: &super::lan::LanHost, at: [f64; 3], velocity: [f64; 3]) {
let Some(id) = host
.hub
.registry_id("minecraft:particle_type", "minecraft:soul")
else {
return;
};
let packet = C::LevelParticles(play::LevelParticles {
particle: Particle { id, data: None },
override_limiter: false,
always_show: false,
pos: at,
dist: velocity.map(|v| v as f32),
max_speed: [1.0; 3],
count: 0,
randomization: 0,
});
for g in host.hub.guests.iter().filter(|g| host.hub.here(g)) {
let distance: f64 = (0..3)
.map(|k| (g.position[k].floor() + 0.5 - at[k]).powi(2))
.sum();
if distance < 32.0 * 32.0 {
g.send(&packet);
}
}
}
impl Game<'_> { impl Game<'_> {
/// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point. /// `SonicBoom.tick` uses `ServerLevel.sendParticles` for each ray point.
/// Keep the local event's rendering; connected players receive one at rest. /// Keep the local event's rendering; connected players receive one at rest.
+15
View File
@@ -109,6 +109,19 @@ pub(super) struct Levels {
parked: HashMap<Dim, Parked>, parked: HashMap<Dim, Parked>,
} }
impl Levels {
/// The chunks of each level not in place (capability `world` lends
/// them to server mods for a call).
#[cfg_attr(not(feature = "mods"), allow(dead_code))]
pub(super) fn parked_chunks(
&mut self,
) -> impl Iterator<Item = (Dim, &mut horizon_client::chunk_map::ChunkMap)> {
self.parked
.iter_mut()
.map(|(d, p)| (*d, &mut p.world.chunks))
}
}
impl Game<'_> { impl Game<'_> {
/// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`). /// A new level for `dim`, opened from the save (`MinecraftServer.createLevels`).
fn open_level(&self, dim: Dim) -> Result<Parked> { fn open_level(&self, dim: Dim) -> Result<Parked> {
@@ -314,6 +327,8 @@ impl Game<'_> {
}; };
self.update_dedicated_streaming(); self.update_dedicated_streaming();
self.update_world(); self.update_world();
// What server mods set in this level since its last tick.
self.apply_mod_block_writes();
result = if paused { result = if paused {
self.tick_lan(true); self.tick_lan(true);
Ok(()) Ok(())
@@ -0,0 +1,485 @@
//! Capability `ui`'s panel beside container screens (WIT `interface
//! browser`, docs/mods.md): the items a recipe viewer mod lists, drawn as
//! the game's own item slots in pages right of the screen's window, with a
//! search box under them. The mod says what the panel holds; the game pages
//! it and tells the mod what the player clicked, typed, and which of the
//! mod's keys went down over an item. With no mod showing a panel, each
//! hook here returns after one check.
use super::Game;
#[cfg(feature = "mods")]
use {
super::Screen,
horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
ui::EditBox,
},
horizon_mods::{BrowserClick, BrowserEvent, BrowserStack},
};
#[cfg(not(feature = "mods"))]
impl Game<'_> {
pub(super) fn draw_mod_browser(&mut self, _batch: &mut horizon_client::hud::HudBatch) {}
pub(super) fn mod_browser_press(&mut self, _right: bool) -> bool {
false
}
pub(super) fn mod_browser_typing(&self) -> bool {
false
}
pub(super) fn mod_browser_key(&mut self, _event: &winit::event::KeyEvent) {}
pub(super) fn mod_browser_text(&mut self, _text: Option<&str>, _backspace: bool) {}
pub(super) fn mod_browser_closed(&mut self) {}
}
/// One slot of the panel, in GUI pixels.
#[cfg(feature = "mods")]
const SLOT: f32 = 18.0;
/// The most columns the panel takes, and the fewest it shows with.
#[cfg(feature = "mods")]
const COLUMNS: (usize, usize) = (12, 2);
/// The gap between the window and the panel, and the screen's edges.
#[cfg(feature = "mods")]
const MARGIN: f32 = 8.0;
/// The panel's state in the game.
#[cfg(feature = "mods")]
#[derive(Default)]
pub(super) struct Browser {
/// The items' owner and version they were made from.
of: Option<(usize, u64)>,
/// The mod's items as stacks; `None` for an item the game doesn't have.
stacks: Vec<Option<ItemStack>>,
page: usize,
search: Option<EditBox>,
/// The search text the mod last heard.
sent: String,
/// `set-recipes`' recipes, shown instead of the items.
pub(super) recipes: Option<super::mod_browser_recipes::Pages>,
}
/// Where the panel's parts are this frame.
#[cfg(feature = "mods")]
pub(super) struct Layout {
/// The panel's whole area, for clicks that hit none of its parts.
pub(super) area: [f32; 4],
/// The grid's top left corner, its columns and rows.
pub(super) grid: (f32, f32),
pub(super) columns: usize,
pub(super) rows: usize,
/// The page arrows' row.
pub(super) arrows_y: f32,
pub(super) search: [f32; 4],
}
#[cfg(feature = "mods")]
impl Layout {
fn per_page(&self) -> usize {
self.columns * self.rows
}
pub(super) fn width(&self) -> f32 {
self.columns as f32 * SLOT
}
fn slot(&self, n: usize) -> (f32, f32) {
(
self.grid.0 + (n % self.columns) as f32 * SLOT,
self.grid.1 + (n / self.columns) as f32 * SLOT,
)
}
/// The page arrows: backward, then forward.
pub(super) fn arrows(&self) -> [(f32, f32); 2] {
[
(self.grid.0, self.arrows_y),
(self.grid.0 + self.width() - 12.0, self.arrows_y),
]
}
}
#[cfg(feature = "mods")]
pub(super) fn inside(p: (f32, f32), [x, y, w, h]: [f32; 4]) -> bool {
p.0 >= x && p.1 >= y && p.0 < x + w && p.1 < y + h
}
#[cfg(feature = "mods")]
impl Game<'_> {
fn browser_batch(&self) -> Option<HudBatch> {
let r = self.renderer.as_ref()?;
Some(HudBatch::new([r.config.width, r.config.height]))
}
/// The mod showing a panel, with its items made into stacks once per
/// `set-items`; none while no mod shows one or no container screen is up.
fn browser_sync(&mut self) -> Option<usize> {
if self.screen != Screen::Inventory || self.title.is_some() {
return None;
}
let Some((owner, version)) = self.mods.mods.browser_items().map(|(o, v, _)| (o, v)) else {
self.mods.browser.of = None;
self.mods.browser.stacks.clear();
return None;
};
if self.mods.browser.of != Some((owner, version)) {
let items = self.res.items();
let stacks = self
.mods
.mods
.browser_items()
.map_or_else(Vec::new, |(_, _, list)| {
list.iter().map(|s| browser_stack(items, s)).collect()
});
self.mods.browser.stacks = stacks;
// The same title again (the mod updating its buttons) keeps the page.
let old = self.mods.browser.recipes.take();
self.mods.browser.recipes = self
.mods
.mods
.browser_recipes(owner)
.map(|shown| super::mod_browser_recipes::Pages::new(items, shown, old));
self.mods.browser.of = Some((owner, version));
}
Some(owner)
}
/// The panel's parts: right of the window, from the top of the screen to
/// the search box at its foot. None when the screen has no room for it.
fn browser_layout(&self, batch: &HudBatch) -> Option<Layout> {
let image = self.container_image(batch);
let left = (image.left + image.width) as f32 + MARGIN;
let right = batch.width - MARGIN;
let columns = (((right - left) / SLOT).floor().max(0.0) as usize).min(COLUMNS.0);
if columns < COLUMNS.1 {
return None;
}
let x = (left + (right - left - columns as f32 * SLOT) / 2.0).floor();
let arrows_y = MARGIN;
let top = arrows_y + 17.0 + 4.0;
let search = [x, batch.height - MARGIN - 16.0, columns as f32 * SLOT, 16.0];
let rows = ((search[1] - 4.0 - top) / SLOT).floor().max(0.0) as usize;
(rows > 0).then_some(Layout {
area: [left, 0.0, right - left, batch.height],
grid: (x, top),
columns,
rows,
arrows_y,
search,
})
}
fn browser_pages(&self, layout: &Layout) -> usize {
self.mods
.browser
.stacks
.len()
.div_ceil(layout.per_page())
.max(1)
}
/// The stack under the pointer on the panel, an item's or a recipe's,
/// as the mod sent it and as a stack.
fn browser_pointed_stack(&self, layout: &Layout) -> Option<(BrowserStack, ItemStack)> {
if self.mods.browser.recipes.is_some() {
if let Some((_, sent, stack)) = self.recipe_tab_hovered(layout) {
return Some((sent, stack));
}
let (_, _, sent, stack) = self.recipe_slot_hovered(layout)?;
return Some((sent, stack));
}
let (index, stack) = self.browser_hovered(layout)?;
let (_, _, items) = self.mods.mods.browser_items()?;
Some((items.get(index)?.clone(), stack))
}
/// The panel's item under the pointer: its index and stack.
fn browser_hovered(&self, layout: &Layout) -> Option<(usize, ItemStack)> {
if self.mods.browser.recipes.is_some() {
return None;
}
let first = self.mods.browser.page * layout.per_page();
(0..layout.per_page()).find_map(|n| {
let (x, y) = layout.slot(n);
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let stack = self.mods.browser.stacks.get(first + n)?.clone()?;
Some((first + n, stack))
})
}
fn browser_search(&mut self, layout: &Layout) -> &mut EditBox {
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit.focused = false;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
search
}
/// The items' page arrows and grid.
fn draw_browser_items(&mut self, batch: &mut HudBatch, layout: &Layout) {
let pages = self.browser_pages(layout);
self.mods.browser.page = self.mods.browser.page.min(pages - 1);
let page = self.mods.browser.page;
let cursor = self.cursor;
if pages > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let shown = [page > 0, page + 1 < pages];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, shown)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(shown))
{
if !shown {
continue;
}
let hover = inside(cursor, [x, y, 12.0, 17.0]);
let suffix = if hover { "_highlighted" } else { "" };
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
let first = page * layout.per_page();
for n in 0..layout.per_page() {
let Some(stack) = self.mods.browser.stacks.get(first + n) else {
break;
};
let Some(stack) = stack.clone() else {
continue;
};
let (x, y) = layout.slot(n);
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
let rect = [x + 1.0, y + 1.0, 16.0, 16.0];
if inside(cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&name,
rect,
true,
horizon_client::widgets::Kind::Button,
);
}
}
/// Draws the panel over the open container screen, then the carried
/// stack or the tooltip again so they stay on top of it.
pub(super) fn draw_mod_browser(&mut self, batch: &mut HudBatch) {
if self.browser_sync().is_none() {
return;
}
let Some(layout) = self.browser_layout(batch) else {
return;
};
let cursor = self.cursor;
if self.mods.browser.recipes.is_some() {
self.draw_browser_recipes(batch, &layout);
} else {
self.draw_browser_items(batch, &layout);
}
let hint = self.translate("gui.recipebook.search_hint", "Search...");
let search = self.browser_search(&layout);
// The hint shows in an empty box without focus, as the recipe book's.
search.suggestion = (search.value.is_empty() && !search.focused).then_some(hint);
let mut search = search.clone();
search.draw(batch, &self.gui.atlas, None);
self.mods.browser.search = Some(search);
if self.carried.is_some() {
self.draw_carried(batch);
} else if let Some(stack) = self.browser_pointed_stack(&layout) {
let lines = self.stack_tooltip(&stack.1);
self.draw_tooltip_lines(batch, &lines, cursor.0, cursor.1);
} else {
self.draw_slot_tooltip(batch);
}
}
/// A mouse press on a container screen: true when the panel took it
/// (its search box, page arrows, items or empty space; a click there
/// never throws the carried stack).
pub(super) fn mod_browser_press(&mut self, right: bool) -> bool {
let Some(owner) = self.browser_sync() else {
return false;
};
let Some(batch) = self.browser_batch() else {
return false;
};
let Some(layout) = self.browser_layout(&batch) else {
return false;
};
let cursor = self.cursor;
let shift = self.has_shift_down();
let atlas = &self.gui.atlas;
let search = self.mods.browser.search.get_or_insert_with(|| {
let mut edit = EditBox::new(0.0, 0.0, 0.0, 0.0);
edit.max_length = 50;
edit
});
[search.x, search.y, search.width, search.height] = layout.search;
if inside(cursor, layout.search) {
search.focused = true;
search.click(atlas, cursor.0, shift, false);
search.reset_blink();
return true;
}
search.focused = false;
if self.mods.browser.recipes.is_some() {
return self.browser_recipes_press(&layout, owner, right)
|| inside(cursor, layout.area);
}
let pages = self.browser_pages(&layout);
let page = self.mods.browser.page;
let [back, forward] = layout.arrows();
let step = if pages > 1 && page > 0 && inside(cursor, [back.0, back.1, 12.0, 17.0]) {
Some(page - 1)
} else if pages > 1
&& page + 1 < pages
&& inside(cursor, [forward.0, forward.1, 12.0, 17.0])
{
Some(page + 1)
} else {
None
};
if let Some(to) = step {
self.mods.browser.page = to;
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
return true;
}
if let Some((index, _)) = self.browser_hovered(&layout) {
let event = BrowserEvent::Clicked(BrowserClick {
index: index as u32,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
inside(cursor, layout.area)
}
/// Whether keys go to the panel's search box.
pub(super) fn mod_browser_typing(&self) -> bool {
self.screen == Screen::Inventory
&& self.mods.browser.of.is_some()
&& self.mods.browser.search.as_ref().is_some_and(|s| s.focused)
}
/// A key press while the search box has focus.
pub(super) fn mod_browser_key(&mut self, event: &winit::event::KeyEvent) {
use winit::keyboard::PhysicalKey;
let shortcut = self.edit_shortcut(event);
let ctrl = self.has_control_down();
let shift = self.has_shift_down();
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if let Some(shortcut) = shortcut {
search.shortcut(shortcut, &mut self.clipboard);
} else {
let handled = match event.physical_key {
PhysicalKey::Code(code) => search.key(code, ctrl, shift),
_ => false,
};
if !handled
&& !ctrl
&& let Some(text) = &event.text
{
let text: String = text.chars().filter(|c| !c.is_control()).collect();
search.insert_text(&text);
}
}
search.reset_blink();
self.browser_searched();
}
/// Text typed (or one backspace) into the search box (`horizon-ctl type`).
pub(super) fn mod_browser_text(&mut self, text: Option<&str>, backspace: bool) {
let Some(search) = self.mods.browser.search.as_mut() else {
return;
};
if backspace {
search.delete_chars(-1);
} else if let Some(text) = text {
search.insert_text(text);
}
self.browser_searched();
}
/// The mod hears the search text when it changed.
fn browser_searched(&mut self) {
let (Some((owner, _)), Some(search)) = (self.mods.browser.of, &self.mods.browser.search)
else {
return;
};
if search.value != self.mods.browser.sent {
let value = search.value.clone();
self.mods.browser.sent.clone_from(&value);
self.mods.browser.page = 0;
self.mods
.mods
.browser_event(owner, BrowserEvent::Search(value));
}
}
/// The container screen closed: the search box lets go of the keys.
pub(super) fn mod_browser_closed(&mut self) {
if let Some(search) = self.mods.browser.search.as_mut() {
search.focused = false;
}
}
/// The item under the pointer on a container screen, for the mods' keys
/// (`browser`'s `key` event): the panel's, else a slot's.
pub(super) fn mod_browser_pointed(&mut self) -> Option<BrowserStack> {
let batch = self.browser_batch()?;
let stack = match self
.browser_sync()
.and_then(|_| self.browser_layout(&batch))
{
// The panel's stacks as the mod sent them.
Some(layout) if inside(self.cursor, layout.area) => {
return Some(self.browser_pointed_stack(&layout)?.0);
}
_ => {
let slot = self.slot_at(&batch, self.cursor.0, self.cursor.1)?;
self.slot_view(slot)?
}
};
Some(BrowserStack {
item: stack.item.to_string(),
count: stack.count,
components: super::mod_recipes::components(&stack),
})
}
}
/// A mod's item as a stack: an item the game has, its components read as
/// `/give` reads them (ones it can't read are left out).
#[cfg(feature = "mods")]
pub(super) fn browser_stack(
items: &horizon_client::items::Items,
s: &BrowserStack,
) -> Option<ItemStack> {
items.get(&s.item)?;
let (damage, extra) = if s.components.is_empty() {
(0, None)
} else {
horizon_client::item_data::command_components(&s.components).map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
})
};
Some(ItemStack {
item: s.item.as_str().into(),
count: s.count.clamp(1, 99),
damage,
extra,
})
}
@@ -0,0 +1,523 @@
//! `browser.set-recipes` (docs/mods.md): a mod's recipes shown in its item
//! panel's place, laid out by the game with its own slots, arrows and
//! buttons, paged to the panel's height, under a title and a back button.
//! The mod hears clicks on their slots, their action buttons, the back
//! button and page turns.
use super::{
Game,
mod_browser::{Layout, browser_stack, inside},
};
use horizon_client::{
hud::{HudBatch, rgba},
items::ItemStack,
};
use horizon_mods::{BrowserEvent, BrowserLayout, BrowserSlotClick, BrowserStack, RecipePage};
use std::time::Instant;
const SLOT: f32 = 18.0;
/// The title row's height, and the gap under each recipe.
const TITLE: f32 = 18.0;
/// A tab's step: an 18 px slot and a gap.
const TAB: f32 = 20.0;
const GAP: f32 = 6.0;
/// One recipe as the game draws it.
pub(super) struct Shown {
layout: BrowserLayout,
width: usize,
height: usize,
/// Each slot's stacks (the result last), as the mod sent them and as
/// stacks; a stack the game doesn't have is left out of the cycle.
slots: Vec<Vec<(BrowserStack, ItemStack)>>,
note: String,
action: Option<bool>,
}
/// The recipes a panel shows, and its page.
pub(super) struct Pages {
title: String,
/// The tabs' icons and the selected one.
tabs: Vec<(BrowserStack, Option<ItemStack>)>,
tab: usize,
recipes: Vec<Shown>,
page: usize,
since: Instant,
}
impl Pages {
pub(super) fn new(
items: &horizon_client::items::Items,
shown: &RecipePage,
old: Option<Pages>,
) -> Self {
let (title, list, tab) = (&shown.title, &shown.recipes, shown.tab as usize);
let kept = old.filter(|o| o.title == *title && o.tab == tab);
let cycle = |stacks: &[BrowserStack]| -> Vec<(BrowserStack, ItemStack)> {
stacks
.iter()
.filter_map(|s| Some((s.clone(), browser_stack(items, s)?)))
.collect()
};
let recipes = list
.iter()
.map(|r| {
let mut slots: Vec<_> = r.slots.iter().map(|s| cycle(s)).collect();
slots.push(cycle(&r.results));
Shown {
layout: r.layout,
width: r.width as usize,
height: r.height as usize,
slots,
note: r.note.clone(),
action: r.action,
}
})
.collect();
Self {
title: title.clone(),
tabs: shown
.tabs
.iter()
.map(|t| (t.clone(), browser_stack(items, t)))
.collect(),
tab,
recipes,
page: kept.as_ref().map_or(0, |o| o.page),
since: kept.map_or_else(Instant::now, |o| o.since),
}
}
}
impl Shown {
/// The inputs' block: its size and each input slot's place in it.
fn inputs(&self) -> ((f32, f32), Vec<(f32, f32)>) {
let row = |n: usize| (0..n).map(|i| (i as f32 * SLOT, 0.0)).collect();
match self.layout {
BrowserLayout::Grid => {
let (w, h) = (self.width.max(1), self.height.max(1));
let at = (0..w * h)
.map(|i| ((i % w) as f32 * SLOT, (i / w) as f32 * SLOT))
.collect();
((w as f32 * SLOT, h as f32 * SLOT), at)
}
// The input over the flame.
BrowserLayout::Cooking => ((SLOT, 2.0 * SLOT), vec![(0.0, 0.0)]),
BrowserLayout::Single => ((SLOT, SLOT), row(1)),
BrowserLayout::Smithing => ((3.0 * SLOT, SLOT), row(3)),
BrowserLayout::Brewing => ((2.0 * SLOT, SLOT), row(2)),
}
}
/// The height of its slots, arrow and button, `room` wide.
fn block(&self, room: f32) -> f32 {
let h = self.inputs().0.1;
let (_, _, action) = self.places(room);
match self.action {
Some(_) => h.max(action.1 + 12.0),
None => h,
}
}
fn height(&self, room: f32) -> f32 {
let note = if self.note.is_empty() { 0.0 } else { 11.0 };
self.block(room) + note + GAP
}
/// Every slot's place from the recipe's corner (the result last), the
/// arrow's and the action button's: beside the result, or under it
/// when the panel is `room` wide and that doesn't fit.
fn places(&self, room: f32) -> (Vec<(f32, f32)>, (f32, f32), (f32, f32)) {
let ((w, h), mut at) = self.inputs();
// The mod's slots beyond the layout's are not shown.
at.truncate(self.slots.len() - 1);
let arrow = (w + 4.0, ((h - 16.0) / 2.0).floor());
let result = (w + 32.0, ((h - SLOT) / 2.0).floor());
let action = if result.0 + SLOT + 16.0 <= room {
(result.0 + SLOT + 4.0, ((h - 12.0) / 2.0).floor())
} else {
(result.0 + 3.0, result.1 + SLOT + 2.0)
};
while at.len() < self.slots.len() - 1 {
at.push((f32::NAN, f32::NAN));
}
at.push(result);
(at, arrow, action)
}
}
/// The tabs' places, in rows under the title row.
fn tab_places(pages: &Pages, layout: &Layout) -> Vec<(f32, f32)> {
let per_row = ((layout.width() / TAB).floor() as usize).max(1);
(0..pages.tabs.len())
.map(|i| {
(
layout.grid.0 + (i % per_row) as f32 * TAB,
layout.grid.1 + TITLE + 3.0 + (i / per_row) as f32 * TAB,
)
})
.collect()
}
/// Where the recipes start: under the title row and the tabs.
fn recipes_top(pages: &Pages, layout: &Layout) -> f32 {
let tabs = tab_places(pages, layout);
tabs.last()
.map_or(layout.grid.1 + TITLE, |&(_, y)| y + TAB + 3.0)
}
impl Game<'_> {
/// The first recipe of each page, filling the panel from the tabs to
/// the search box.
fn recipe_pages(pages: &Pages, layout: &Layout) -> Vec<usize> {
let room = layout.search[1] - 4.0 - recipes_top(pages, layout);
let mut starts = vec![0];
let mut used = 0.0;
for (i, r) in pages.recipes.iter().enumerate() {
let h = r.height(layout.width());
if used > 0.0 && used + h > room {
starts.push(i);
used = 0.0;
}
used += h;
}
starts
}
/// The recipes on the open page, each with its corner.
fn recipes_shown(&self, layout: &Layout) -> Vec<(usize, (f32, f32))> {
let Some(pages) = &self.mods.browser.recipes else {
return Vec::new();
};
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let end = starts.get(page + 1).copied().unwrap_or(pages.recipes.len());
let mut y = recipes_top(pages, layout);
(starts[page]..end)
.map(|i| {
let at = (layout.grid.0, y);
y += pages.recipes[i].height(layout.width());
(i, at)
})
.collect()
}
fn back_button(&self, layout: &Layout) -> ([f32; 4], String) {
let label = self.translate("gui.back", "Back");
let w = HudBatch::text_width(&self.gui.atlas, &label) + 8.0;
([layout.grid.0, layout.grid.1, w, 14.0], label)
}
/// What a slot of a shown recipe holds now: its stacks cycle once a second.
fn recipe_slot_now(&self, recipe: usize, slot: usize) -> Option<&(BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let stacks = pages.recipes.get(recipe)?.slots.get(slot)?;
let n = pages.since.elapsed().as_secs() as usize;
stacks.get(n % stacks.len().max(1))
}
/// The tab under the pointer: its index and icon.
pub(super) fn recipe_tab_hovered(
&self,
layout: &Layout,
) -> Option<(usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
let places = tab_places(pages, layout);
places.iter().enumerate().find_map(|(i, &(x, y))| {
if !inside(self.cursor, [x, y, SLOT, SLOT]) {
return None;
}
let (sent, stack) = pages.tabs.get(i)?;
Some((i, sent.clone(), stack.clone()?))
})
}
/// The recipe slot under the pointer: recipe, slot, and its stack now.
pub(super) fn recipe_slot_hovered(
&self,
layout: &Layout,
) -> Option<(usize, usize, BrowserStack, ItemStack)> {
let pages = self.mods.browser.recipes.as_ref()?;
self.recipes_shown(layout)
.into_iter()
.find_map(|(i, (x, y))| {
let (at, _, _) = pages.recipes[i].places(layout.width());
at.iter().enumerate().find_map(|(k, &(sx, sy))| {
if !inside(self.cursor, [x + sx, y + sy, SLOT, SLOT]) {
return None;
}
let (mod_stack, stack) = self.recipe_slot_now(i, k)?.clone();
Some((i, k, mod_stack, stack))
})
})
}
/// Draws the title row, the page's recipes and the page arrows.
pub(super) fn draw_browser_recipes(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let (title, pages_n) = (pages.title.clone(), starts.len());
let (back, label) = self.back_button(layout);
let atlas = &self.gui.atlas;
let hover = inside(cursor, back);
let sprite = if hover {
"gui/sprites/widget/button_highlighted"
} else {
"gui/sprites/widget/button"
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
back[0],
back[1],
back[2],
back[3],
u32::MAX,
);
batch.text(atlas, &label, back[0] + 4.0, back[1] + 3.0, u32::MAX, true);
horizon_client::widgets::record(&label, back, true);
let room = layout.width() - back[2] - 4.0;
// Cut to the panel with vanilla's ellipsis (CommonComponents.ELLIPSIS).
let shown = if atlas.font.fit(&title, room) >= title.chars().count() {
title
} else {
let fit = atlas.font.fit(&title, room - atlas.font.width("..."));
let kept: String = title.chars().take(fit).collect();
format!("{}...", kept.trim_end())
};
batch.text(
atlas,
&shown,
back[0] + back[2] + 4.0,
back[1] + 3.0,
u32::MAX,
true,
);
self.draw_recipe_tabs(batch, layout);
if pages_n > 1 {
let labels = [
self.translate("gui.recipebook.previous_page", "Previous Page"),
self.translate("gui.recipebook.next_page", "Next Page"),
];
let visible = [page > 0, page + 1 < pages_n];
let atlas = &self.gui.atlas;
for (((x, y), name), (label, visible)) in layout
.arrows()
.into_iter()
.zip(["page_backward", "page_forward"])
.zip(labels.iter().zip(visible))
{
if !visible {
continue;
}
let suffix = if inside(cursor, [x, y, 12.0, 17.0]) {
"_highlighted"
} else {
""
};
batch.sprite(
atlas,
&format!("gui/sprites/recipe_book/{name}{suffix}"),
x,
y,
);
horizon_client::widgets::record(label, [x, y, 12.0, 17.0], true);
}
let text = format!("{}/{pages_n}", page + 1);
let w = HudBatch::text_width(atlas, &text);
let x = (layout.grid.0 + (layout.width() - w) / 2.0).floor();
batch.text(atlas, &text, x, layout.arrows_y + 5.0, u32::MAX, true);
}
for (i, (x, y)) in self.recipes_shown(layout) {
let Some(r) = self.mods.browser.recipes.as_ref().map(|p| &p.recipes[i]) else {
break;
};
let (at, arrow, action) = r.places(layout.width());
let h = r.block(layout.width());
let (cooking, note, button) =
(r.layout == BrowserLayout::Cooking, r.note.clone(), r.action);
let atlas = &self.gui.atlas;
for &(sx, sy) in at.iter().filter(|p| p.0.is_finite()) {
batch.sprite(atlas, "gui/sprites/container/slot", x + sx, y + sy);
}
if cooking {
batch.sprite(
atlas,
"gui/sprites/container/furnace/lit_progress",
x + 2.0,
y + SLOT + 2.0,
);
}
batch.sprite(
atlas,
"gui/sprites/container/furnace/burn_progress",
x + arrow.0,
y + arrow.1,
);
if let Some(enabled) = button {
let rect = [x + action.0, y + action.1, 12.0, 12.0];
let sprite = match (enabled, inside(cursor, rect)) {
(false, _) => "gui/sprites/widget/button_disabled",
(true, true) => "gui/sprites/widget/button_highlighted",
(true, false) => "gui/sprites/widget/button",
};
horizon_client::ui::nine_slice(
batch,
atlas,
sprite,
rect[0],
rect[1],
12.0,
12.0,
u32::MAX,
);
let color = if enabled {
u32::MAX
} else {
rgba(160, 160, 160, 255)
};
batch.text(atlas, "+", rect[0] + 3.0, rect[1] + 2.0, color, true);
horizon_client::widgets::record(&format!("+ {i}"), rect, enabled);
}
if !note.is_empty() {
batch.text(atlas, &note, x, y + h + 2.0, rgba(224, 224, 224, 255), true);
}
for (k, &(sx, sy)) in at.iter().enumerate().filter(|(_, p)| p.0.is_finite()) {
let Some((_, stack)) = self.recipe_slot_now(i, k).cloned() else {
continue;
};
self.draw_item(batch, &stack, x + sx + 1.0, y + sy + 1.0);
if inside(cursor, [x + sx, y + sy, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + sx + 1.0,
y + sy + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} {i}:{k}"),
[x + sx + 1.0, y + sy + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Button,
);
}
}
}
/// The tabs, on slots; the selected one framed.
fn draw_recipe_tabs(&mut self, batch: &mut HudBatch, layout: &Layout) {
let Some(pages) = &self.mods.browser.recipes else {
return;
};
let places = tab_places(pages, layout);
let tabs: Vec<Option<ItemStack>> = pages.tabs.iter().map(|t| t.1.clone()).collect();
let selected = pages.tab;
for (i, (&(x, y), stack)) in places.iter().zip(tabs).enumerate() {
let atlas = &self.gui.atlas;
batch.sprite(atlas, "gui/sprites/container/slot", x, y);
let Some(stack) = stack else {
continue;
};
self.draw_item(batch, &stack, x + 1.0, y + 1.0);
// The selected tab: a white frame around its slot.
if i == selected {
let white = rgba(255, 255, 255, 255);
let atlas = &self.gui.atlas;
batch.fill(atlas, x - 1.0, y - 1.0, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y + SLOT, SLOT + 2.0, 1.0, white);
batch.fill(atlas, x - 1.0, y, 1.0, SLOT, white);
batch.fill(atlas, x + SLOT, y, 1.0, SLOT, white);
}
if inside(self.cursor, [x, y, SLOT, SLOT]) {
batch.fill(
&self.gui.atlas,
x + 1.0,
y + 1.0,
16.0,
16.0,
rgba(255, 255, 255, 128),
);
}
let name = self.pack.names.display_item(&stack.item);
horizon_client::widgets::record_as(
&format!("{name} tab"),
[x + 1.0, y + 1.0, 16.0, 16.0],
true,
horizon_client::widgets::Kind::Tab(i == selected),
);
}
}
/// A press on the recipes: true when it hit one of their parts.
pub(super) fn browser_recipes_press(
&mut self,
layout: &Layout,
owner: usize,
right: bool,
) -> bool {
let Some(pages) = &self.mods.browser.recipes else {
return false;
};
let cursor = self.cursor;
let starts = Self::recipe_pages(pages, layout);
let page = pages.page.min(starts.len() - 1);
let [back_arrow, forward] = layout.arrows();
let turn = if page > 0 && inside(cursor, [back_arrow.0, back_arrow.1, 12.0, 17.0]) {
Some(page - 1)
} else if page + 1 < starts.len() && inside(cursor, [forward.0, forward.1, 12.0, 17.0]) {
Some(page + 1)
} else {
None
};
if let Some(to) = turn {
if let Some(p) = self.mods.browser.recipes.as_mut() {
p.page = to;
}
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Page(starts[to] as u32));
return true;
}
if let Some((tab, _, _)) = self.recipe_tab_hovered(layout) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Tab(tab as u32));
return true;
}
if inside(cursor, self.back_button(layout).0) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods.mods.browser_event(owner, BrowserEvent::Back);
return true;
}
if let Some((recipe, slot, stack, _)) = self.recipe_slot_hovered(layout) {
let event = BrowserEvent::SlotClicked(BrowserSlotClick {
recipe: recipe as u32,
slot: slot as u32,
stack,
right,
});
self.mods.mods.browser_event(owner, event);
return true;
}
let action = self.recipes_shown(layout).into_iter().find(|&(i, (x, y))| {
let r = &pages.recipes[i];
let (_, _, (ax, ay)) = r.places(layout.width());
r.action.is_some() && inside(cursor, [x + ax, y + ay, 12.0, 12.0])
});
if let Some((i, _)) = action {
if pages.recipes[i].action == Some(true) {
self.audio
.play("minecraft:ui.button.click", None, 0.25, 1.0);
self.mods
.mods
.browser_event(owner, BrowserEvent::Action(i as u32));
}
return true;
}
false
}
}
@@ -111,6 +111,18 @@ impl Game<'_> {
if repeat || !self.mods.mods.has_keys() { if repeat || !self.mods.mods.has_keys() {
return; return;
} }
// Over an item on a container screen, the mods' keys are `browser`
// events (a recipe viewer's R and U).
if pressed
&& self.screen == Screen::Inventory
&& self.title.is_none()
&& !self.mod_browser_typing()
&& let Some(name) = horizon_client::keybinds::key_name(key)
&& let Some(stack) = self.mod_browser_pointed()
{
self.mods.mods.browser_key(name, &stack);
return;
}
if pressed && (self.screen != Screen::Playing || self.title.is_some()) { if pressed && (self.screen != Screen::Playing || self.title.is_some()) {
return; return;
} }
@@ -0,0 +1,274 @@
//! Capability `recipes` (docs/mods.md): every item and recipe the game
//! knows, made once for the mods that read them, and the recipe book's
//! known displays. The recipes are the window's own data: the world's in
//! single player, vanilla's on a server (a client is sent no others), while
//! the known displays follow the server's book as the recipe book does.
use super::Game;
use horizon_client::{
crafting::Ingredient,
items::ItemStack,
recipe_book::{Category, Display},
stations::Smithing,
};
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
use std::{collections::HashMap, sync::Arc};
/// Item id -> its index in [`Recipes::items`].
struct Index(HashMap<Arc<str>, u32>);
impl Index {
fn stack(&self, item: &str, count: u32, components: String) -> Option<RecipeStack> {
Some(RecipeStack {
item: *self.0.get(item)?,
count,
components,
})
}
fn of(&self, s: &ItemStack) -> Option<RecipeStack> {
self.stack(&s.item, s.count, components(s))
}
fn any(&self, i: &Ingredient) -> Vec<RecipeStack> {
i.1.iter()
.filter_map(|id| self.stack(id, 1, String::new()))
.collect()
}
}
/// A stack's components beyond its item's, as vanilla's item syntax writes
/// them (`[minecraft:potion_contents={potion:"minecraft:swiftness"}]`), or "".
pub(super) fn components(s: &ItemStack) -> String {
use horizon_world::nbt::Tag;
let Some(Tag::Compound(entries)) = horizon_client::item_data::encode_components(s) else {
return String::new();
};
let parts: Vec<String> = entries
.iter()
.map(|(k, v)| {
format!(
"{}={}",
k.to_string_lossy(),
horizon_client::snbt::to_snbt(v)
)
})
.collect();
format!("[{}]", parts.join(","))
}
fn recipe(id: String, kind: RecipeKind) -> Recipe {
Recipe {
id,
kind,
category: String::new(),
group: String::new(),
width: 0,
height: 0,
slots: Vec::new(),
results: Vec::new(),
cooking_time: 0,
experience: 0.0,
book_id: -1,
}
}
impl Game<'_> {
/// `recipes.give`: a creative player takes the stack as from the
/// creative inventory; a server hears it as `SetCreativeModeSlot`
/// through the inventory's sync, and refuses it unless creative.
pub(super) fn mod_give(&mut self, item: &str, count: u32, components: &str) {
let Some(max) = self.res.items().get(item).map(|i| i.max_stack) else {
return;
};
if !self.creative {
return;
}
let (damage, extra) = horizon_client::item_data::command_components(components)
.map_or((0, None), |tag| {
horizon_client::item_data::decode_components(Some(&tag))
});
let _ = self.give(ItemStack {
item: item.into(),
// One stack at most, as the creative inventory hands out.
count: count.min(max),
damage,
extra,
});
}
/// Capability `recipes`'s tables and known displays for this tick's
/// snapshot; nothing while no running mod reads them.
pub(super) fn mod_recipes(&mut self) -> (Option<Arc<Recipes>>, Arc<[i32]>) {
if !self.mods.mods.wants_recipes() {
return (None, Arc::from([]));
}
if self.mods.recipes.is_none() {
self.mods.recipes = Some(Arc::new(self.make_mod_recipes()));
}
let (version, known) = self.recipe_book_displays();
if self.mods.known_recipes.0 != Some(version) {
self.mods.known_recipes = (Some(version), known.into());
}
(self.mods.recipes.clone(), self.mods.known_recipes.1.clone())
}
fn make_mod_recipes(&mut self) -> Recipes {
let names = &self.pack.names;
let items = self.res.items();
let mut tags: HashMap<&str, Vec<String>> = HashMap::new();
for (tag, members) in &items.item_tags {
for m in members {
tags.entry(m).or_default().push(tag.clone());
}
}
let table: Vec<RecipeItem> = items
.registry_order
.iter()
.map(|id| RecipeItem {
id: id.to_string(),
name: names.display_item(id),
tags: tags.remove(&**id).map_or_else(Vec::new, |mut t| {
t.sort();
t
}),
})
.collect();
let index = Index(
items
.registry_order
.iter()
.enumerate()
.map(|(i, id)| (id.clone(), i as u32))
.collect(),
);
let mut out = Vec::new();
let cooking: HashMap<String, (u32, f32)> = self
.res
.recipes()
.cooking
.iter()
.map(|c| (format!("minecraft:{}", c.id), (c.time, c.experience)))
.collect();
for e in self.recipe_book_entries() {
let furnace = |c: Category| match c.name().split('_').next() {
Some("blast") => RecipeKind::Blasting,
Some("smoker") => RecipeKind::Smoking,
_ => RecipeKind::Smelting,
};
let kind = match &e.display {
Display::Shaped { .. } => RecipeKind::CraftingShaped,
Display::Shapeless(_) => RecipeKind::CraftingShapeless,
Display::Furnace(_) => furnace(e.category),
};
let mut r = recipe(e.id.clone(), kind);
r.category = e.category.name().to_owned();
r.group = e.group.clone().unwrap_or_default();
r.book_id = e.display_id;
r.slots = match &e.display {
Display::Shaped {
width,
height,
cells,
} => {
(r.width, r.height) = (*width as u32, *height as u32);
cells
.iter()
.map(|c| c.as_ref().map_or_else(Vec::new, |i| index.any(i)))
.collect()
}
Display::Shapeless(list) => list.iter().map(|i| index.any(i)).collect(),
Display::Furnace(i) => vec![index.any(i)],
};
// Requirements shown as other stacks (an arrow's potions): the
// requirement's index counts the filled slots only.
let filled: Vec<usize> = (0..r.slots.len())
.filter(
|&k| !matches!(&e.display, Display::Shaped { cells, .. } if cells[k].is_none()),
)
.collect();
for (req, stacks) in &e.stacks {
if let Some(&k) = filled.get(*req) {
r.slots[k] = stacks.iter().filter_map(|s| index.of(s)).collect();
}
}
r.results = e.results().iter().filter_map(|s| index.of(s)).collect();
if let Some(&(time, xp)) = cooking.get(&e.id) {
(r.cooking_time, r.experience) = (time, xp);
}
out.push(r);
}
for c in &self.res.recipes().cooking {
if c.kind == "minecraft:campfire_cooking" {
let mut r = recipe(format!("minecraft:{}", c.id), RecipeKind::Campfire);
r.group = c.group.clone();
r.slots = vec![index.any(&c.ingredient)];
r.results = index.of(&c.result).into_iter().collect();
(r.cooking_time, r.experience) = (c.time, c.experience);
out.push(r);
}
}
let stations = self.res.stations();
for s in &stations.recipes.stonecutting {
let mut r = recipe(s.id.clone(), RecipeKind::Stonecutting);
r.slots = vec![index.any(&s.input)];
r.results = index.of(&s.result).into_iter().collect();
out.push(r);
}
for s in &stations.recipes.smithing {
let (id, template, base, addition, results) = match s {
Smithing::Transform {
id,
template,
base,
addition,
result,
} => (
id,
template,
base,
addition,
index.stack(result, 1, String::new()).into_iter().collect(),
),
Smithing::Trim {
id,
template,
base,
addition,
..
} => (id, template, base, addition, index.any(base)),
};
let mut r = recipe(id.clone(), RecipeKind::Smithing);
r.slots = vec![index.any(template), index.any(base), index.any(addition)];
r.results = results;
out.push(r);
}
for b in &stations.brewing.recipes {
let potion = |p: &horizon_client::brewing::PotionIngredient| -> Vec<RecipeStack> {
let mut item_ids: Vec<&String> = p.items.iter().collect();
item_ids.sort();
let mut potions: Vec<&String> = p.potions.iter().flatten().collect();
potions.sort();
item_ids
.into_iter()
.flat_map(|item| {
let one = |c: String| index.stack(item, 1, c);
if potions.is_empty() {
one(String::new()).into_iter().collect::<Vec<_>>()
} else {
potions
.iter()
.filter_map(|p| {
one(format!("[minecraft:potion_contents={{potion:\"{p}\"}}]"))
})
.collect()
}
})
.collect()
};
let mut r = recipe(b.id.clone(), RecipeKind::Brewing);
r.slots = vec![potion(&b.input), potion(&b.reagent)];
r.results = index.of(&b.output).into_iter().collect();
out.push(r);
}
Recipes {
items: table,
recipes: out,
}
}
}
+41 -2
View File
@@ -63,6 +63,14 @@ pub(super) struct ModsState {
/// What players did this tick, for server mods at its end. /// What players did this tick, for server mods at its end.
#[cfg(feature = "mods")] #[cfg(feature = "mods")]
pub(super) events: Vec<ModEvent>, pub(super) events: Vec<ModEvent>,
/// A running server mod has capability `world`: its calls get the
/// levels' chunks to read.
#[cfg(feature = "mods")]
pub(super) world: bool,
/// Blocks server mods set, by dimension, made before that level's next
/// tick.
#[cfg(feature = "mods")]
pub(super) block_writes: Vec<(String, horizon_mods::BlockChange)>,
/// `command.run` lines for this window's own world, run on the next tick: /// `command.run` lines for this window's own world, run on the next tick:
/// run at once, their chat lines would reach the mods while their output /// run at once, their chat lines would reach the mods while their output
/// is still being shown, and a mod answering its own lines would recurse. /// is still being shown, and a mod answering its own lines would recurse.
@@ -81,6 +89,15 @@ pub(super) struct ModsState {
/// The HUD font's advances for `render.text-width`, made once. /// The HUD font's advances for `render.text-width`, made once.
#[cfg(feature = "mods")] #[cfg(feature = "mods")]
font_widths: std::sync::Arc<[f32]>, font_widths: std::sync::Arc<[f32]>,
/// Capability `recipes`'s tables, made once a mod reads them.
#[cfg(feature = "mods")]
pub(super) recipes: Option<std::sync::Arc<horizon_mods::Recipes>>,
/// The recipe book's known displays, and the book's version they are of.
#[cfg(feature = "mods")]
pub(super) known_recipes: (Option<u64>, std::sync::Arc<[i32]>),
/// Capability `ui`'s item panel beside container screens.
#[cfg(feature = "mods")]
pub(super) browser: super::mod_browser::Browser,
/// Extras that are official mods now, being installed. /// Extras that are official mods now, being installed.
#[cfg(feature = "mods")] #[cfg(feature = "mods")]
pub(super) moved: super::moved_extras::MovedState, pub(super) moved: super::moved_extras::MovedState,
@@ -293,6 +310,8 @@ impl Game<'_> {
self.mods.mods.set_bindings(|id| chosen.keys_of(id)); self.mods.mods.set_bindings(|id| chosen.keys_of(id));
// Entries were replaced wholesale: a screen's owner index is stale. // Entries were replaced wholesale: a screen's owner index is stale.
self.mods.screen = None; self.mods.screen = None;
// Content mods may have changed the items: remade on the next read.
self.mods.recipes = None;
self.list_mods(); self.list_mods();
self.sync_mod_commands(); self.sync_mod_commands();
self.show_mod_output(); self.show_mod_output();
@@ -309,6 +328,7 @@ impl Game<'_> {
/// The Mods page's rows, from what loaded. /// The Mods page's rows, from what loaded.
fn list_mods(&mut self) { fn list_mods(&mut self) {
self.mods.server = self.mods.mods.runs_server(); self.mods.server = self.mods.mods.runs_server();
self.mods.world = self.mods.mods.wants_world();
let dev = &self.mods.dev; let dev = &self.mods.dev;
self.settings.mods.installed = self self.settings.mods.installed = self
.mods .mods
@@ -440,6 +460,7 @@ impl Game<'_> {
.map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1)) .map(|c| char::from_u32(c).map_or(6.0, |c| atlas.glyph_cell(c).1))
.collect(); .collect();
} }
let (recipes, known_recipes) = self.mod_recipes();
Snapshot { Snapshot {
player, player,
clock, clock,
@@ -451,6 +472,10 @@ impl Game<'_> {
font_widths: self.mods.font_widths.clone(), font_widths: self.mods.font_widths.clone(),
players, players,
view_hit: self.mod_view_hit(), view_hit: self.mod_view_hit(),
recipes,
known_recipes,
placing: self.mod_recipe_screen(),
creative: self.creative,
} }
} }
/// The first block along the player's view within /// The first block along the player's view within
@@ -673,8 +698,10 @@ impl Game<'_> {
} }
Text::literal(line).with_color(text::RED) Text::literal(line).with_color(text::RED)
} }
server server @ (Output::Tell { .. }
@ (Output::Tell { .. } | Output::Broadcast { .. } | Output::Reply { .. }) => { | Output::Broadcast { .. }
| Output::Reply { .. }
| Output::SetBlocks { .. }) => {
self.route_server_output(host.as_deref_mut(), server); self.route_server_output(host.as_deref_mut(), server);
continue; continue;
} }
@@ -686,6 +713,18 @@ impl Game<'_> {
self.mods.shake.add(strength, seconds); self.mods.shake.add(strength, seconds);
continue; continue;
} }
Output::PlaceRecipe { book_id, all } => {
self.mod_place_recipe(book_id, all);
continue;
}
Output::Give {
item,
count,
components,
} => {
self.mod_give(&item, count, &components);
continue;
}
Output::CloseScreen { owner } => { Output::CloseScreen { owner } => {
if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) { if self.mods.screen.as_ref().is_some_and(|s| s.owner == owner) {
self.close_mod_screen(false); self.close_mod_screen(false);
@@ -338,6 +338,25 @@ impl Game<'_> {
ui.client_known = Some(known.clone()); ui.client_known = Some(known.clone());
ui.client_version += 1; ui.client_version += 1;
} }
/// Every entry of the book, in its order (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_entries(&mut self) -> Vec<Entry> {
self.ensure_book();
self.recipe_ui
.book
.as_ref()
.map_or_else(Vec::new, |b| b.entries.clone())
}
/// The display ids the player's book holds, and a number that changes
/// whenever they do (capability `recipes`).
#[cfg(feature = "mods")]
pub(super) fn recipe_book_displays(&mut self) -> (u64, Vec<i32>) {
self.sync_client_book();
(
self.recipe_ui.client_version,
self.recipe_ui.client.displays(),
)
}
fn ensure_book(&mut self) { fn ensure_book(&mut self) {
if self.recipe_ui.book.is_none() { if self.recipe_ui.book.is_none() {
let mut book = Book::build(self.res.recipes(), self.res.items()); let mut book = Book::build(self.res.recipes(), self.res.items());
@@ -826,6 +845,34 @@ impl Game<'_> {
self.recipe_ui.ghost.clear(); self.recipe_ui.ghost.clear();
self.place_recipe(book_type, entry_index, use_max); self.place_recipe(book_type, entry_index, use_max);
} }
/// Whether the open screen takes `recipes.place`: a crafting grid's
/// book (the inventory's or a crafting table's).
#[cfg(feature = "mods")]
pub(super) fn mod_recipe_screen(&self) -> bool {
self.screen == Screen::Inventory
&& self.active_book() == Some(BookType::Crafting)
&& !self.spectator()
}
/// `recipes.place`: the book's click on the recipe with this display
/// id, refused as `handlePlaceRecipe` refuses it (no crafting screen,
/// not in the player's book; an impossible one in `place_recipe`).
#[cfg(feature = "mods")]
pub(super) fn mod_place_recipe(&mut self, display_id: i32, all: bool) {
if !self.mod_recipe_screen() || !self.recipe_ui.client.displays().contains(&display_id) {
return;
}
self.ensure_book();
let Some(index) = self
.recipe_ui
.book
.as_ref()
.and_then(|b| b.entries.iter().position(|e| e.display_id == display_id))
else {
return;
};
self.recipe_ui.ghost.clear();
self.place_recipe(BookType::Crafting, index, all);
}
/// `ServerboundPlaceRecipePacket`: the server places the recipe /// `ServerboundPlaceRecipePacket`: the server places the recipe
/// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost /// (`ServerPlaceRecipe` on the menu engine) and answers with a ghost
/// recipe when the items are missing. /// recipe when the items are missing.
@@ -19,33 +19,7 @@ pub const HELP: &[&str] = &[
impl Game<'_> { impl Game<'_> {
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties). /// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
fn parse_state(&self, text: &str) -> Result<BlockStateId> { fn parse_state(&self, text: &str) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') { parse_state(self.pack.assets.registry, text)
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let registry = &self.pack.assets.registry;
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
} }
pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> { pub(super) fn render_command(&mut self, words: &[&str]) -> Result<Option<Value>> {
let int = |i: usize| -> Result<i32> { let int = |i: usize| -> Result<i32> {
@@ -137,3 +111,36 @@ impl Game<'_> {
} }
} }
} }
/// Parse `name[k=v,...]` into a registry state (defaults for missing properties).
pub(super) fn parse_state(
registry: &horizon_world::registry::BlockRegistry,
text: &str,
) -> Result<BlockStateId> {
let (name, props) = match text.split_once('[') {
Some((n, rest)) => (n, rest.trim_end_matches(']')),
None => (text, ""),
};
let name = if name.contains(':') {
name.to_owned()
} else {
format!("minecraft:{name}")
};
let default = registry
.default_state(&name)
.ok_or_else(|| format!("unknown block {name}"))?;
let mut state = registry
.state(default)
.ok_or("missing default state")?
.clone();
for pair in props.split(',').filter(|p| !p.is_empty()) {
let (k, v) = pair
.split_once('=')
.ok_or_else(|| format!("bad property {pair}"))?;
if !state.properties.contains_key(k) {
return Err(format!("{name} has no property {k}").into());
}
state.properties.insert(k.to_owned(), v.to_owned());
}
Ok(registry.resolve(&state)?)
}
+151 -3
View File
@@ -47,19 +47,72 @@ impl Game<'_> {
) -> bool { ) -> bool {
false false
} }
pub(super) fn apply_mod_block_writes(&mut self) {}
} }
#[cfg(feature = "mods")] #[cfg(feature = "mods")]
mod run { mod run {
use super::{Game, LanHost, ModEvent, Who}; use super::{Game, LanHost, ModEvent, Who};
use horizon_client::chunk_map::ChunkMap;
use horizon_client::{ use horizon_client::{
command::args::GameMode as Mode, command::args::GameMode as Mode,
lan::data::component_nbt, lan::data::component_nbt,
text::{self, Text}, text::{self, Text},
}; };
use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer}; use horizon_mods::{BlockPos, GameMode, Output, ServerPlayer, WorldView};
use horizon_protocol::packets::play::{self, Clientbound as C}; use horizon_protocol::packets::play::{self, Clientbound as C};
use horizon_world::registry::BlockStateId; use horizon_world::registry::{BlockRegistry, BlockStateId};
/// Blocks queued for levels that don't tick (another dimension, in-frame)
/// are kept up to this many; the oldest go first.
const MAX_QUEUED_WRITES: usize = 1 << 16;
/// Capability `world`'s view during a call: the levels' chunks, moved out
/// of the game for the call and back after it (no copy).
struct LentWorld {
registry: &'static BlockRegistry,
biomes: std::sync::Arc<horizon_client::biome::Biomes>,
dims: Vec<(&'static str, ChunkMap)>,
}
impl WorldView for LentWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(state_string(self.registry, chunk.block(x & 15, y, z & 15)))
}
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let (_, chunks) = self.dims.iter().find(|(d, _)| *d == dimension)?;
let chunk = chunks.get(&(x >> 4, z >> 4))?;
Some(self.biomes.get(chunk.biome(x, y, z)).name.clone())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
crate::game::render_control::parse_state(self.registry, state)
.map(drop)
.map_err(|e| format!("{state}: {e}"))
}
}
/// `minecraft:oak_log[axis=y]`.
fn state_string(registry: &BlockRegistry, state: BlockStateId) -> String {
let Some(s) = registry.state(state) else {
return "minecraft:air".into();
};
if s.properties.is_empty() {
return s.name.clone();
}
let props: Vec<String> = s
.properties
.iter()
.map(|(k, v)| format!("{k}={v}"))
.collect();
format!("{}[{}]", s.name, props.join(","))
}
/// `UUID.toString()`. /// `UUID.toString()`.
fn uuid_string(u: u128) -> String { fn uuid_string(u: u128) -> String {
@@ -144,6 +197,7 @@ mod run {
let players = self.server_players(None); let players = self.server_players(None);
let snapshot = self.mod_snapshot_with(players.clone()); let snapshot = self.mod_snapshot_with(players.clone());
self.mods.mods.set_snapshot(snapshot); self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let before = std::mem::take(&mut self.mods.players); let before = std::mem::take(&mut self.mods.players);
for p in before for p in before
.iter() .iter()
@@ -197,8 +251,80 @@ mod run {
} }
} }
self.mods.mods.server_tick(self.ticks); self.mods.mods.server_tick(self.ticks);
self.return_world();
self.mods.players = players; self.mods.players = players;
self.show_mod_output(); self.show_mod_output();
self.apply_mod_block_writes();
}
/// Lends the levels' chunks to capability `world` for the calls up to
/// [`Game::return_world`], when a running server mod has it.
fn lend_world(&mut self) {
if !self.mods.world {
return;
}
let mut dims = vec![(self.dim.id(), std::mem::take(&mut self.world.chunks))];
for (dim, chunks) in self.levels.parked_chunks() {
dims.push((dim.id(), std::mem::take(chunks)));
}
let registry = self.pack.assets.registry;
let biomes = self.res.biomes().clone();
self.mods.mods.lend_world(Box::new(LentWorld {
registry,
biomes,
dims,
}));
}
/// Puts back the chunks [`Game::lend_world`] lent.
fn return_world(&mut self) {
let Some(view) = self.mods.mods.take_world() else {
return;
};
let view: Box<dyn std::any::Any> = view;
let Ok(lent) = view.downcast::<LentWorld>() else {
return;
};
let mut dims = lent.dims;
if let Some(i) = dims.iter().position(|(d, _)| *d == self.dim.id()) {
self.world.chunks = dims.swap_remove(i).1;
}
for (dim, chunks) in self.levels.parked_chunks() {
if let Some(i) = dims.iter().position(|(d, _)| *d == dim.id()) {
*chunks = dims.swap_remove(i).1;
}
}
}
/// Makes the blocks server mods set in the level in place, in order,
/// as `/setblock` does. Those of other dimensions wait for their level.
pub(in crate::game) fn apply_mod_block_writes(&mut self) {
if self.mods.block_writes.is_empty() {
return;
}
let dim = self.dim.id();
let (now, later): (Vec<_>, Vec<_>) = std::mem::take(&mut self.mods.block_writes)
.into_iter()
.partition(|(d, _)| d == dim);
self.mods.block_writes = later;
let registry = self.pack.assets.registry;
for (_, b) in now {
let state = match crate::game::render_control::parse_state(registry, &b.state) {
Ok(state) => state,
Err(e) => {
log::warn!("Horizon: a server mod set {}: {e}", b.state);
continue;
}
};
if let Err(e) = self.place_state([b.x, b.y, b.z], state, false) {
log::debug!(
"Horizon: a server mod's block at {} {} {}: {e:?}",
b.x,
b.y,
b.z
);
}
}
} }
/// A player broke (or placed) `state` at `pos`: the player acting now. /// A player broke (or placed) `state` at `pos`: the player acting now.
@@ -240,8 +366,11 @@ mod run {
}; };
let snapshot = self.mod_snapshot_with(players); let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot); self.mods.mods.set_snapshot(snapshot);
self.lend_world();
let owned = self.mods.mods.server_command(&me, line); let owned = self.mods.mods.server_command(&me, line);
self.return_world();
self.show_mod_output(); self.show_mod_output();
self.apply_mod_block_writes();
owned owned
} }
@@ -266,10 +395,14 @@ mod run {
}; };
let snapshot = self.mod_snapshot_with(players); let snapshot = self.mod_snapshot_with(players);
self.mods.mods.set_snapshot(snapshot); self.mods.mods.set_snapshot(snapshot);
if !self.mods.mods.server_command(&me, line) { self.lend_world();
let owned = self.mods.mods.server_command(&me, line);
self.return_world();
if !owned {
return false; return false;
} }
self.route_mod_output(Some(host)); self.route_mod_output(Some(host));
self.apply_mod_block_writes();
true true
} }
@@ -349,6 +482,21 @@ mod run {
self.tell_server_player(host.as_deref_mut(), &p.id, line); self.tell_server_player(host.as_deref_mut(), &p.id, line);
} }
} }
Output::SetBlocks {
name,
dimension,
blocks,
} => {
let queued = &mut self.mods.block_writes;
queued.extend(blocks.into_iter().map(|b| (dimension.clone(), b)));
if queued.len() > MAX_QUEUED_WRITES {
let over = queued.len() - MAX_QUEUED_WRITES;
queued.drain(..over);
log::warn!(
"Horizon: mod {name} set more blocks than wait for their level: {over} dropped"
);
}
}
_ => {} _ => {}
} }
} }
@@ -196,6 +196,82 @@ impl WorldLoader {
} }
} }
/// How long the preloaded world data outlives the world screens: a player
/// who goes back to the title or to Multiplayer and opens no world for this
/// long gets the memory back.
const PRELOAD_KEPT: std::time::Duration = std::time::Duration::from_secs(60);
enum Preload {
Idle,
/// Read, or being read, on the "World data preload" thread. `left`: when
/// the player last left the world screens.
Started {
thread: std::thread::JoinHandle<()>,
left: Option<std::time::Instant>,
},
/// A world opened: the data is the world's now, and stays.
Used,
}
static PRELOAD: std::sync::Mutex<Preload> = std::sync::Mutex::new(Preload::Idle);
/// Each frame of the title: read what every world opening loads and keeps
/// for the rest of the process (the worldgen bundle, the loot tables and the
/// registries the server sends) on a helper thread while the player is on the
/// world screens (`on_world_screens`: Singleplayer, Create World and their
/// dialogs), so it overlaps the time spent choosing a world. A world opened
/// meanwhile waits for the part being read instead of reading it again. Not
/// at the title screen itself: many players only go to Multiplayer, and
/// small machines need the memory. Dropped after `PRELOAD_KEPT` away from
/// the world screens without a world opening.
pub(super) fn preload_world_data(
on_world_screens: bool,
resources: &std::path::Path,
registry: &'static horizon_world::registry::BlockRegistry,
) {
let mut preload = PRELOAD.lock().unwrap_or_else(|e| e.into_inner());
match &mut *preload {
Preload::Used => {}
Preload::Idle if on_world_screens => {
let resources = resources.to_owned();
let spawned = std::thread::Builder::new()
.name("World data preload".into())
.spawn(move || {
horizon_threads::behind_server();
// Errors are left for the world opening to report.
let _ = horizon_client::vanillagen::shared_data(
&resources.join("worldgen"),
registry,
);
let _ = horizon_client::structure_blocks::loot_data(&resources);
let _ = super::lan::sync_data(&resources);
});
match spawned {
Ok(thread) => *preload = Preload::Started { thread, left: None },
Err(e) => log::warn!("Horizon: world data preload: {e}"),
}
}
Preload::Idle => {}
Preload::Started { left, .. } if on_world_screens => *left = None,
Preload::Started { thread, left } => {
let left = *left.get_or_insert_with(std::time::Instant::now);
if left.elapsed() >= PRELOAD_KEPT && thread.is_finished() {
horizon_client::vanillagen::forget_shared_data();
horizon_client::structure_blocks::forget_loot_data();
super::lan::forget_sync_data();
horizon_threads::release_free_memory();
*preload = Preload::Idle;
log::info!("Horizon: preloaded world data dropped, no world opened");
}
}
}
}
/// A world opens: what `preload_world_data` read is the world's from now on.
pub(super) fn world_data_used() {
*PRELOAD.lock().unwrap_or_else(|e| e.into_inner()) = Preload::Used;
}
pub(super) fn make_streaming( pub(super) fn make_streaming(
res: &Resources, res: &Resources,
pack: &PackResources, pack: &PackResources,
+1 -35
View File
@@ -2,7 +2,6 @@
//! defaults, `key_<name>:key.keyboard.x` persistence, display names, and the //! defaults, `key_<name>:key.keyboard.x` persistence, display names, and the
//! translation of rebound physical keys back to the default keys the game //! translation of rebound physical keys back to the default keys the game
//! logic listens for. //! logic listens for.
use crate::text::Text;
use std::collections::BTreeMap; use std::collections::BTreeMap;
use winit::{event::MouseButton, keyboard::KeyCode}; use winit::{event::MouseButton, keyboard::KeyCode};
@@ -225,40 +224,7 @@ pub fn mouse_button(name: &str) -> Option<MouseButton> {
_ => return None, _ => return None,
}) })
} }
/// InputConstants.Key.getDisplayName: one-character keys as the upper-case pub use horizon_client_core::key_display::display_name;
/// character, others by translation.
pub fn display_name(key: &str) -> Text {
if let Some(rest) = key.strip_prefix("key.keyboard.")
&& rest.chars().count() == 1
{
let c = rest.to_uppercase();
return Text::literal(c);
}
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()
&& !crate::lang::has(key)
{
return Text::translate("key.mouse", &[Text::literal(n)]);
}
Text::translate(key, &[])
}
/// Current bindings by mapping name. /// Current bindings by mapping name.
#[derive(Clone, Debug, PartialEq, Eq)] #[derive(Clone, Debug, PartialEq, Eq)]
+12 -12
View File
@@ -19,13 +19,11 @@ pub mod biome;
pub mod block_entities; pub mod block_entities;
pub mod block_entity_anim; pub mod block_entity_anim;
pub mod block_entity_item; pub mod block_entity_item;
pub mod block_entity_nbt;
pub mod block_entity_render; pub mod block_entity_render;
pub mod block_transform; pub mod block_transform;
pub mod blocks; pub mod blocks;
pub mod border_render; pub mod border_render;
pub mod boss_overlay; pub mod boss_overlay;
pub mod bossbar;
pub mod breaking; pub mod breaking;
pub mod brewing; pub mod brewing;
pub mod bundle; pub mod bundle;
@@ -38,10 +36,8 @@ pub mod clipboard;
pub mod clock; pub mod clock;
pub mod clouds; pub mod clouds;
pub mod collisions; pub mod collisions;
pub mod command;
pub mod command_block; pub mod command_block;
pub mod command_storage; pub mod command_storage;
pub mod component;
pub mod confirm_screen; pub mod confirm_screen;
pub mod container_screen; pub mod container_screen;
pub mod containers; pub mod containers;
@@ -71,7 +67,6 @@ pub mod extras;
pub mod extras_hud; pub mod extras_hud;
pub mod falling_block; pub mod falling_block;
pub mod fast_hash; pub mod fast_hash;
pub mod fastutil_order;
pub mod fire_render; pub mod fire_render;
pub mod first_person; pub mod first_person;
pub mod flatgen; pub mod flatgen;
@@ -80,7 +75,6 @@ pub mod font;
pub mod friends_screen; pub mod friends_screen;
pub mod game_mode_switcher; pub mod game_mode_switcher;
pub mod gamepad; pub mod gamepad;
pub mod gamerules;
pub mod gfx; pub mod gfx;
pub mod gizmos; pub mod gizmos;
pub mod gossip; pub mod gossip;
@@ -109,7 +103,6 @@ pub mod keybinds;
pub mod keymapping; pub mod keymapping;
pub mod lan; pub mod lan;
pub mod landing; pub mod landing;
pub mod lang;
pub mod level_loading; pub mod level_loading;
pub mod light; pub mod light;
pub mod locator_bar; pub mod locator_bar;
@@ -131,7 +124,6 @@ pub mod mouse;
pub mod moved_extras; pub mod moved_extras;
pub mod multiplayer; pub mod multiplayer;
pub mod music; pub mod music;
pub mod nbt_path;
pub mod net; pub mod net;
pub mod nether_portal; pub mod nether_portal;
pub mod offline_name; pub mod offline_name;
@@ -160,7 +152,6 @@ pub mod recipe_book;
pub mod recipe_book_screen; pub mod recipe_book_screen;
pub mod reconnect; pub mod reconnect;
pub mod save; pub mod save;
pub mod scoreboard;
pub mod scoreboard_cmd; pub mod scoreboard_cmd;
pub mod screen_draw; pub mod screen_draw;
pub mod screen_effects; pub mod screen_effects;
@@ -173,7 +164,6 @@ pub mod shader_pack_list;
pub mod shadows; pub mod shadows;
pub mod signs; pub mod signs;
pub mod skins; pub mod skins;
pub mod snbt;
pub mod sound_engine; pub mod sound_engine;
pub mod sound_events; pub mod sound_events;
pub mod spans; pub mod spans;
@@ -186,7 +176,6 @@ pub mod structure_blocks;
pub mod tab_list; pub mod tab_list;
pub mod telemetry; pub mod telemetry;
pub mod testgen; pub mod testgen;
pub mod text;
pub mod text_display; pub mod text_display;
pub mod tick_chunk_membership; pub mod tick_chunk_membership;
pub mod ticket_levels; pub mod ticket_levels;
@@ -206,4 +195,15 @@ pub mod world;
pub mod world_spawn; pub mod world_spawn;
pub mod worldborder; pub mod worldborder;
pub mod zip; pub mod zip;
pub type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>; 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_command as command;
+21 -1
View File
@@ -69,6 +69,7 @@ pub mod tame;
pub mod trader; pub mod trader;
pub mod transport_items; pub mod transport_items;
pub mod trial_spawner; pub mod trial_spawner;
pub mod turtle;
pub mod undead; pub mod undead;
pub mod vex; pub mod vex;
pub mod villager; pub mod villager;
@@ -516,6 +517,8 @@ pub enum DamageKind {
InFire, InFire,
Lava, Lava,
Drown, Drown,
/// `dry_out`: an axolotl out of water for too long.
DryOut,
Magic, Magic,
Sting, Sting,
Cactus, Cactus,
@@ -574,7 +577,11 @@ impl Damage {
pub fn causes_panic(&self) -> bool { pub fn causes_panic(&self) -> bool {
!matches!( !matches!(
self.kind, self.kind,
DamageKind::Fall | DamageKind::Drown | DamageKind::Generic | DamageKind::InWall DamageKind::Fall
| DamageKind::Drown
| DamageKind::DryOut
| DamageKind::Generic
| DamageKind::InWall
) )
} }
/// DamageTypeTags.BYPASSES_ARMOR /// DamageTypeTags.BYPASSES_ARMOR
@@ -607,6 +614,7 @@ impl Damage {
| DamageKind::InFire | DamageKind::InFire
| DamageKind::Lava | DamageKind::Lava
| DamageKind::Drown | DamageKind::Drown
| DamageKind::DryOut
| DamageKind::Magic | DamageKind::Magic
| DamageKind::Cactus | DamageKind::Cactus
| DamageKind::Generic | DamageKind::Generic
@@ -1203,6 +1211,12 @@ pub enum MobEvent {
mob: u32, mob: u32,
target: Who, target: Who,
}, },
/// `LevelEvent.PARTICLES_DESTROY_BLOCK` (2001) at `pos` for the block at
/// `block`: a turtle's digging.
BlockBreakEffect {
pos: [i32; 3],
block: [i32; 3],
},
/// `Warden.applyDarknessAround`: darkness for survival players nearby. /// `Warden.applyDarknessAround`: darkness for survival players nearby.
Darkness { Darkness {
at: [f64; 3], at: [f64; 3],
@@ -1873,6 +1887,12 @@ impl Mob {
} }
} }
} }
// Squid.hurtServer: a squid hurt after a living entity hit it squirts ink.
if matches!(self.species(), Species::Squid | Species::GlowSquid)
&& self.ai.last_hurt_by.is_some()
{
aquatic::spawn_ink(self);
}
true true
} }
/// LivingEntity.knockback(power, xd, zd) towards the negative direction. /// LivingEntity.knockback(power, xd, zd) towards the negative direction.
+43 -1
View File
@@ -183,6 +183,9 @@ pub fn register(m: &mut Mob) {
if m.species() == Species::Rabbit { if m.species() == Species::Rabbit {
super::rabbit::register(m); super::rabbit::register(m);
} }
if m.species() == Species::Turtle {
super::turtle::register(m);
}
} }
Family::Inert => {} Family::Inert => {}
Family::Witch => super::witch::register(m), Family::Witch => super::witch::register(m),
@@ -441,6 +444,34 @@ pub fn tick_swing(m: &mut Mob) {
} }
m.anim.attack_anim = m.ai.swing_time as f32 / 6.0; m.anim.attack_anim = m.ai.swing_time as f32 / 6.0;
} }
/// `LivingEntity.baseTick` refills a breather's air by 4, then
/// `Axolotl.handleAirSupply` (unless the mob has no AI): water or rain fills
/// it, anywhere else it runs down from the pre-tick value, and at -20 the
/// axolotl dries out.
fn axolotl_air_supply(m: &mut Mob, w: &MobWorld) {
let before = m.air;
m.air = (m.air + 4).min(super::axolotl::MAX_AIR);
if m.no_ai {
return;
}
// Entity.isInRain: rain at the block, or at the top of the box.
let (x, y, z) = (
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
);
let top = (m.position.y + f64::from(m.height())).floor() as i32;
let in_rain = w.raining_at(x, y, z) || w.raining_at(x, top, z);
if m.fluids.in_water || in_rain {
m.air = super::axolotl::MAX_AIR;
} else {
m.air = before - 1;
if m.air <= -20 {
m.air = 0;
m.damage(2.0, Damage::of(DamageKind::DryOut));
}
}
}
/// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick. /// Entity.baseTick + LivingEntity.baseTick + Mob.baseTick.
fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) { fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.was_eye_in_water = m.fluids.eye_in_water; m.was_eye_in_water = m.fluids.eye_in_water;
@@ -500,7 +531,9 @@ fn base_tick(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
m.damage(1.0, Damage::of(DamageKind::InWall)); m.damage(1.0, Damage::of(DamageKind::InWall));
} }
// Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs). // Air supply and drowning (WaterAnimal.handleAirSupply for aquatic mobs).
if m.kind.flags.needs_water { if m.species() == Species::Axolotl {
axolotl_air_supply(m, w);
} else if m.kind.flags.needs_water {
if !m.fluids.in_water { if !m.fluids.in_water {
m.air -= 1; m.air -= 1;
if m.air == -20 { if m.air == -20 {
@@ -712,6 +745,14 @@ fn ai_step(m: &mut Mob, w: &MobWorld, level_random: &mut LegacyRandom, events: &
// setAge at the age boundary: refreshDimensions. // setAge at the age boundary: refreshDimensions.
if m.extra.age >= 0 { if m.extra.age >= 0 {
m.fudge_position_after_size_change(w, bw, bh); m.fudge_position_after_size_change(w, bw, bh);
// Turtle.ageBoundaryReached: a grown turtle drops a scute.
if m.species() == Species::Turtle {
events.push(MobEvent::GiftLoot {
mob: m.id,
table: "minecraft:gameplay/turtle_grow",
at: [m.position.x, m.position.y, m.position.z],
});
}
} }
} else if m.extra.age > 0 { } else if m.extra.age > 0 {
m.extra.age -= 1; m.extra.age -= 1;
@@ -1005,6 +1046,7 @@ fn species_ai_step(
} }
Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events), Species::Nautilus | Species::ZombieNautilus => super::nautilus::ai_step(m, w, events),
Species::Chicken => farm::chicken_ai_step(m, w, events), Species::Chicken => farm::chicken_ai_step(m, w, events),
Species::Turtle => super::turtle::ai_step(m, w, events),
Species::Sheep if m.extra.anim_ticks > 0 => { Species::Sheep if m.extra.anim_ticks > 0 => {
m.extra.anim_ticks -= 1; m.extra.anim_ticks -= 1;
} }
+53
View File
@@ -24,6 +24,58 @@ const Z_BODY_ROT: usize = 3;
const TENTACLE_SPEED: usize = 4; const TENTACLE_SPEED: usize = 4;
const ROTATE_SPEED: usize = 5; const ROTATE_SPEED: usize = 5;
/// `Squid.spawnInk`: the squirt sound and 30 ink particles shot from under
/// the squid, turned by its body rotation.
pub fn spawn_ink(m: &mut Mob) {
let sound = if m.species() == Species::GlowSquid {
"entity.glow_squid.squirt"
} else {
"entity.squid.squirt"
};
let kind = if m.species() == Species::GlowSquid {
"glow_squid_ink"
} else {
"squid_ink"
};
// makeSound draws the voice pitch even for a silent squid.
let pitch = m.voice_pitch();
if !m.silent {
let at = [m.position.x, m.position.y, m.position.z];
m.outbox.push(MobEvent::Sound(
sound,
at,
super::ai::sound_volume(m),
pitch,
));
}
// rotateVector: xRot(xBodyRotO), then yRot(-yBodyRotO).
let to_radians = (std::f64::consts::PI / 180.0) as f32;
let (x_rot, y_rot) = (
m.anim.vo[X_BODY_ROT] * to_radians,
-m.previous_body_yaw * to_radians,
);
let rotate = |v: Vec3| v.rotate_x(x_rot).rotate_y(y_rot);
let pos = rotate(Vec3::new(0.0, -1.0, 0.0)).add_vector(m.position);
let offset_scale: f32 = if m.is_baby() { 0.1 } else { 0.3 };
for _ in 0..30 {
let x = f64::from(m.random.next_float()) * 0.6 - 0.3;
let z = f64::from(m.random.next_float()) * 0.6 - 0.3;
let dir = rotate(Vec3::new(x, -1.0, z));
let d = dir.scale(f64::from(offset_scale + m.random.next_float() * 2.0));
// ServerLevel.sendParticles with a count of 0 and speed 0.1: one
// particle moving at the float offset times the float speed.
let speed = f64::from(0.1f32);
m.outbox.push(MobEvent::ParticleAt {
kind,
at: [pos.x, pos.y + 0.5, pos.z],
velocity: [
speed * f64::from(d.x as f32),
speed * f64::from(d.y as f32),
speed * f64::from(d.z as f32),
],
});
}
}
pub fn register(m: &mut Mob) { pub fn register(m: &mut Mob) {
use Species as S; use Species as S;
match m.species() { match m.species() {
@@ -36,6 +88,7 @@ pub fn register(m: &mut Mob) {
m.anim.v[TENTACLE_SPEED] = speed; m.anim.v[TENTACLE_SPEED] = speed;
} }
S::Axolotl => { S::Axolotl => {
m.air = super::axolotl::MAX_AIR;
// Native controller scaling is essential: the base speed attribute is 1.0. // Native controller scaling is essential: the base speed attribute is 1.0.
m.ai.mov.kind = MoveKind::SmoothSwimming { m.ai.mov.kind = MoveKind::SmoothSwimming {
max_turn_x: 85.0, max_turn_x: 85.0,
@@ -3,6 +3,8 @@ use super::{Mob, MobEvent, MobWorld, Species, Who, animal_brain, keyframes::Anim
use horizon_core::random::RandomSource; use horizon_core::random::RandomSource;
pub const PLAY_DEAD_TICKS: i32 = 200; pub const PLAY_DEAD_TICKS: i32 = 200;
pub const HUNTING_COOLDOWN: i64 = 2400; pub const HUNTING_COOLDOWN: i64 = 2400;
/// `Axolotl.getMaxAirSupply`.
pub const MAX_AIR: i32 = 6000;
/// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown. /// AxolotlAttackablesSensor: always-hostile targets bypass the hunting cooldown.
pub fn prey_eligible( pub fn prey_eligible(
+2 -2
View File
@@ -969,8 +969,8 @@ pub fn anim(m: &Mob, s: &State, p: &mut Poses, a: &Animations) -> bool {
s, s,
&Turtle { &Turtle {
on_land: !m.fluids.in_water && m.on_ground, on_land: !m.fluids.in_water && m.on_ground,
laying_egg: false, laying_egg: m.extra.flag2,
has_egg: false, has_egg: m.extra.flag,
}, },
), ),
Species::Strider => strider(p, s, m.rider.is_some()), Species::Strider => strider(p, s, m.rider.is_some()),
+8
View File
@@ -1791,6 +1791,10 @@ impl Goal for Breed {
if tamable && (!m.extra.tame || m.extra.sitting) { if tamable && (!m.extra.tame || m.extra.sitting) {
return false; return false;
} }
// TurtleBreedGoal.canUse: not while carrying an egg.
if species == Species::Turtle && super::turtle::has_egg(m) {
return false;
}
let id = m.id; let id = m.id;
// Horses and donkeys breed together (AbstractHorse.canParent: tame). // Horses and donkeys breed together (AbstractHorse.canParent: tame).
// Sniffer.canMate: calm states only. // Sniffer.canMate: calm states only.
@@ -1869,6 +1873,10 @@ impl Goal for Breed {
}); });
m.extra.in_love = 0; m.extra.in_love = 0;
m.extra.age = 6000; m.extra.age = 6000;
// TurtleBreedGoal.breed: the mother carries an egg, not a baby.
if m.species() == Species::Turtle {
m.extra.flag = true;
}
cx.events.push(MobEvent::Breed { cx.events.push(MobEvent::Breed {
parent: m.id, parent: m.id,
partner: p.id, partner: p.id,
@@ -153,6 +153,14 @@ pub fn finalize(m: &mut Mob, biome: &BiomeFacts, difficulty: &LocalDifficulty) {
S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index, S::Pig | S::Cow | S::Chicken => m.extra.variant = climate_index,
S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random), S::Sheep => m.extra.color = super::farm::sheep_color(biome.climate, &mut m.random),
S::Mooshroom => m.extra.variant = 0, S::Mooshroom => m.extra.variant = 0,
// Turtle.finalizeSpawn: home is where it spawned.
S::Turtle => {
m.extra.home = Some([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
])
}
S::Frog => m.extra.variant = biome.frog, S::Frog => m.extra.variant = biome.frog,
S::Wolf => m.extra.variant = biome.wolf, S::Wolf => m.extra.variant = biome.wolf,
S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon), S::Cat => m.extra.variant = super::tame::cat_variant(m, biome.full_moon),
+209
View File
@@ -0,0 +1,209 @@
//! Turtles (`Turtle`): the egg a bred mother carries (`TurtleBreedGoal`), her
//! walk home (`TurtleGoHomeGoal`) and the egg she digs into the sand
//! (`TurtleLayEggGoal`). `extra.flag` is `hasEgg`, `extra.flag2` `isLayingEgg`,
//! `extra.counter` `layEggCounter` and `extra.home` `homePos`.
use super::{
Mob, MobEvent, MobWorld,
goals::{Breed, Cx, Goal, JUMP, MOVE, MoveToBlock, goal_clone, reduced},
};
use horizon_core::random::RandomSource;
pub fn register(m: &mut Mob) {
let g = &mut m.ai.goals;
g.add(1, Breed::new(1.0));
g.add(1, LayEgg(MoveToBlock::new(1.0, 16, 1)));
g.add(4, GoHome::default());
}
/// `Turtle.hasEgg`.
pub fn has_egg(m: &Mob) -> bool {
m.extra.flag
}
/// `Turtle.setLayingEgg`.
fn set_laying_egg(m: &mut Mob, on: bool) {
m.extra.counter = i32::from(on);
m.extra.flag2 = on;
}
/// `homePos.closerToCenterThan(position, distance)`. Spawning, hatching and
/// loading all set a home; one made any other way is at home where it stands.
fn close_to_home(m: &Mob, distance: f64) -> bool {
let home = m.extra.home.unwrap_or([
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]);
let d = [
f64::from(home[0]) + 0.5 - m.position.x,
f64::from(home[1]) + 0.5 - m.position.y,
f64::from(home[2]) + 0.5 - m.position.z,
];
d[0] * d[0] + d[1] * d[1] + d[2] * d[2] < distance * distance
}
fn block_of(m: &Mob) -> [i32; 3] {
[
m.position.x.floor() as i32,
m.position.y.floor() as i32,
m.position.z.floor() as i32,
]
}
/// `TurtleEggBlock.isSand`.
fn is_sand(w: &MobWorld, p: [i32; 3]) -> bool {
w.has_tag("minecraft:sand", w.block_name(p[0], p[1], p[2]))
}
/// `Turtle.aiStep`: while digging, sand crumbs fly every fifth tick.
pub fn ai_step(m: &mut Mob, w: &MobWorld, events: &mut Vec<MobEvent>) {
if m.alive() && m.extra.flag2 && m.extra.counter >= 1 && m.extra.counter % 5 == 0 {
let at = block_of(m);
let below = [at[0], at[1] - 1, at[2]];
if is_sand(w, below) {
events.push(MobEvent::BlockBreakEffect {
pos: at,
block: below,
});
}
}
}
/// `Turtle.TurtleLayEggGoal`: a mother with an egg within 9 blocks of home
/// walks to sand with air above, digs for 200 ticks and lays it.
#[derive(Clone, Debug)]
struct LayEgg(MoveToBlock);
impl LayEgg {
/// `isValidTarget`: sand with air above it.
fn valid(w: &MobWorld, p: [i32; 3]) -> bool {
w.facts.is_air(w.world.block(p[0], p[1] + 1, p[2])) && is_sand(w, p)
}
}
impl Goal for LayEgg {
goal_clone!();
fn flags(&self) -> u8 {
MOVE | JUMP
}
fn name(&self) -> &'static str {
"TurtleLayEggGoal"
}
fn every_tick(&self) -> bool {
true
}
fn can_use(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
if !(has_egg(m) && close_to_home(m, 9.0)) {
return false;
}
// MoveToBlockGoal.canUse.
if self.0.next_start > 0 {
self.0.next_start -= 1;
return false;
}
self.0.next_start = reduced(200 + m.random.next_int_bound(200).unwrap_or(0));
self.0.find_nearest(m, cx.w, Self::valid)
}
fn can_continue(&mut self, m: &mut Mob, cx: &mut Cx) -> bool {
self.0.can_continue(cx.w, Self::valid) && has_egg(m) && close_to_home(m, 9.0)
}
fn start(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.start(m, cx.w);
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
self.0.tick(m, cx.w);
if m.fluids.in_water || !self.0.reached {
return;
}
if m.extra.counter < 1 {
set_laying_egg(m, true);
} else if m.extra.counter > 200 {
let at = [m.position.x, m.position.y, m.position.z];
let pitch = 0.9 + m.random.next_float() * 0.2;
cx.events
.push(MobEvent::Sound("entity.turtle.lay_egg", at, 0.3, pitch));
// Blocks.TURTLE_EGG with EGGS = nextInt(4) + 1 above the sand.
let eggs = m.random.next_int_bound(4).unwrap_or(0) + 1;
let registry = cx.w.registry;
let state = registry
.default_state("minecraft:turtle_egg")
.and_then(|d| registry.state(d).cloned())
.and_then(|mut s| {
s.properties.insert("eggs".into(), eggs.to_string());
registry.resolve(&s).ok()
});
let b = self.0.block;
if let Some(state) = state {
cx.events.push(MobEvent::SetBlock {
pos: [b[0], b[1] + 1, b[2]],
state,
});
}
m.extra.flag = false;
set_laying_egg(m, false);
m.extra.in_love = 600;
}
if m.extra.flag2 {
m.extra.counter += 1;
}
}
}
/// `Turtle.TurtleGoHomeGoal`: a mother with an egg heads home; any adult
/// that strayed 64 blocks away does now and then.
#[derive(Clone, Debug, Default)]
struct GoHome {
stuck: bool,
close_to_home_try_ticks: i32,
}
impl Goal for GoHome {
goal_clone!();
fn flags(&self) -> u8 {
0
}
fn name(&self) -> &'static str {
"TurtleGoHomeGoal"
}
fn can_use(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
if m.is_baby() {
false
} else if has_egg(m) {
true
} else {
m.random.next_int_bound(reduced(700)).unwrap_or(1) == 0 && !close_to_home(m, 64.0)
}
}
fn start(&mut self, _m: &mut Mob, _cx: &mut Cx) {
self.stuck = false;
self.close_to_home_try_ticks = 0;
}
fn can_continue(&mut self, m: &mut Mob, _cx: &mut Cx) -> bool {
!close_to_home(m, 7.0) && !self.stuck && self.close_to_home_try_ticks <= reduced(600)
}
fn tick(&mut self, m: &mut Mob, cx: &mut Cx) {
let home = m.extra.home.unwrap_or(block_of(m));
let close = close_to_home(m, 16.0);
if close {
self.close_to_home_try_ticks += 1;
}
if !m.ai.nav.is_done() {
return;
}
let to = [
f64::from(home[0]) + 0.5,
f64::from(home[1]),
f64::from(home[2]) + 0.5,
];
let mut next = m
.default_random_pos_towards(cx.w, 16, 3, to, std::f64::consts::PI / 10.0)
.or_else(|| m.default_random_pos_towards(cx.w, 8, 7, to, std::f64::consts::FRAC_PI_2));
if let Some(at) = next
&& !close
&& cx.w.block_name(
at[0].floor() as i32,
at[1].floor() as i32,
at[2].floor() as i32,
) != "minecraft:water"
{
next = m.default_random_pos_towards(cx.w, 16, 5, to, std::f64::consts::FRAC_PI_2);
}
match next {
Some(at) => {
m.nav_move_to(cx.w, at, 1.0);
}
None => self.stuck = true,
}
}
}
+13
View File
@@ -206,6 +206,19 @@ impl MobWorld<'_> {
} }
self.world.light(x, y, z) >> 4 == 15 self.world.light(x, y, z) >> 4 == 15
} }
/// Level.isRainingAt: raining, open to the sky, nothing motion blocking
/// above, and the biome's precipitation at the position is rain, not snow
/// or none.
pub fn raining_at(&self, x: i32, y: i32, z: i32) -> bool {
if !self.raining || !self.can_see_sky(x, y, z) || self.motion_blocking_height(x, z) > y {
return false;
}
let Some(chunk) = self.world.chunks.get(&(x >> 4, z >> 4)) else {
return false;
};
let biome = self.biomes.get(chunk.biome(x, y, z));
biome.precipitation && biome.temperature_at(BlockPos::new(x, y, z), self.sea_level) >= 0.15
}
/// Level.getLightLevelDependentMagicValue: the dimension's brightness curve /// Level.getLightLevelDependentMagicValue: the dimension's brightness curve
/// at the raw (sky darkened) light level. /// at the raw (sky darkened) light level.
pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 { pub fn brightness(&self, x: i32, y: i32, z: i32) -> f32 {
+44
View File
@@ -52,6 +52,8 @@ pub struct MotionResources {
pub climbable: BTreeSet<String>, pub climbable: BTreeSet<String>,
/// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes. /// `BlockTags.CAN_GLIDE_THROUGH`: climbable blocks a gliding player passes.
pub glide_through: BTreeSet<String>, pub glide_through: BTreeSet<String>,
/// `BlockTags.SOUL_SPEED_BLOCKS`: what Soul Speed's effects look for.
pub soul_speed_blocks: BTreeSet<String>,
pub fall_reset: BTreeSet<String>, pub fall_reset: BTreeSet<String>,
pub landing: BlockLandingRegistry, pub landing: BlockLandingRegistry,
pub health: crate::health::HealthResources, pub health: crate::health::HealthResources,
@@ -111,11 +113,29 @@ impl MotionResources {
})?, })?,
climbable: tag("minecraft:climbable")?, climbable: tag("minecraft:climbable")?,
glide_through: tag("minecraft:can_glide_through")?, glide_through: tag("minecraft:can_glide_through")?,
soul_speed_blocks: tag("minecraft:soul_speed_blocks")?,
fall_reset: tag("minecraft:fall_damage_resetting")?, fall_reset: tag("minecraft:fall_damage_resetting")?,
}) })
} }
} }
/// What the `location_changed` enchantment effects (Soul Speed) need to know
/// between ticks.
#[derive(Clone, Debug, Default)]
pub struct LocationEffects {
/// `MovementAffectedByPredicate`: the block under the player
/// (`getBlockPosBelowThatAffectsMyMovement`) is in `#minecraft:soul_speed_blocks`.
pub on_soul_speed_block: bool,
/// `LivingEntity.lastPos`: the block the player was in last tick.
pub block: Option<BlockPos>,
/// A landing ran `onChangedBlock` (`LivingEntity.checkFallDamage`).
pub landed: bool,
/// The Soul Speed level of the boots seen last tick (0: none).
pub boots_level: u32,
/// The Soul Speed level whose attribute modifiers are on the player (0: none).
pub applied_level: u32,
}
/// Ordered requests and phase records for world/audio/network consumers. Landing /// Ordered requests and phase records for world/audio/network consumers. Landing
/// hurt dispatch updates stored health synchronously before these are drained. /// hurt dispatch updates stored health synchronously before these are drained.
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]
@@ -258,6 +278,8 @@ pub struct PlayerMotion {
pub glide_ending: bool, pub glide_ending: bool,
/// Glider durability to take this tick (updateFallFlying). /// Glider durability to take this tick (updateFallFlying).
pub glider_wear: u32, pub glider_wear: u32,
/// Soul Speed's `location_changed` bookkeeping.
pub location_effects: LocationEffects,
/// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's /// `LivingEntity.autoSpinAttackTicks` and `autoSpinAttackDmg`: Riptide's
/// spin. The damage stays until the game has dealt the hit. /// spin. The damage stays until the game has dealt the hit.
pub auto_spin_attack_ticks: i32, pub auto_spin_attack_ticks: i32,
@@ -449,6 +471,7 @@ impl PlayerMotion {
fall_fly_ticks: 0, fall_fly_ticks: 0,
glide_ending: false, glide_ending: false,
glider_wear: 0, glider_wear: 0,
location_effects: LocationEffects::default(),
auto_spin_attack_ticks: 0, auto_spin_attack_ticks: 0,
auto_spin_attack_dmg: 0.0, auto_spin_attack_dmg: 0.0,
spin_targets: Vec::new(), spin_targets: Vec::new(),
@@ -1006,6 +1029,7 @@ impl MotionWorld<'_, '_, '_> {
) )
}); });
self.player.try_add_frost(on_air)?; self.player.try_add_frost(on_air)?;
self.update_soul_speed_block()?;
if self.player.health.tick_count % 40 == 0 if self.player.health.tick_count % 40 == 0
&& self.player.is_fully_frozen() && self.player.is_fully_frozen()
&& self.player.can_freeze() && self.player.can_freeze()
@@ -1018,6 +1042,22 @@ impl MotionWorld<'_, '_, '_> {
} }
Ok(()) Ok(())
} }
/// Refresh whether the player stands on a soul speed block, for the
/// `location_changed` enchantment effects (a server's player too, whose
/// client does the walking).
pub fn update_soul_speed_block(&mut self) -> Result<()> {
self.player.location_effects.on_soul_speed_block = self.on_soul_speed_block()?;
Ok(())
}
/// `MovementAffectedByPredicate` for `#minecraft:soul_speed_blocks`.
fn on_soul_speed_block(&mut self) -> Result<bool> {
let on = self.support(movement_support::MOVEMENT_SUPPORT_OFFSET)?;
Ok(self
.assets
.registry
.state(self.block(on))
.is_some_and(|s| self.resources.soul_speed_blocks.contains(&s.name)))
}
/// Player.travel: swim steering, then LivingEntity.travel (fluids first, /// Player.travel: swim steering, then LivingEntity.travel (fluids first,
/// then gliding, then air), keeping 0.6 of the vertical speed while flying. /// then gliding, then air), keeping 0.6 of the vertical speed while flying.
fn player_travel(&mut self, input: Vec3) -> Result<()> { fn player_travel(&mut self, input: Vec3) -> Result<()> {
@@ -1915,6 +1955,10 @@ impl EntityMoveWorld for MotionWorld<'_, '_, '_> {
if self.player.status.slow_falling || self.player.status.levitation.is_some() { if self.player.status.slow_falling || self.player.status.levitation.is_some() {
self.player.fall_distance = 0.0; self.player.fall_distance = 0.0;
} }
// LivingEntity.checkFallDamage: a landing runs onChangedBlock.
if grounded && self.player.fall_distance > 0.0 {
self.player.location_effects.landed = true;
}
if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0 if self.player.spawn_extra_particles_on_fall && grounded && self.player.fall_distance > 0.0
{ {
self.player.events.push(MotionEvent::SmashLanding { self.player.events.push(MotionEvent::SmashLanding {
+1 -206
View File
@@ -23,212 +23,7 @@ use std::{
path::Path, path::Path,
}; };
macro_rules! particle_types { pub use horizon_client_core::particle_type::ParticleType;
($($variant:ident = $name:literal),* $(,)?) => {
/// Vanilla particle types with a client implementation here.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ParticleType { $($variant),* }
impl ParticleType {
pub const ALL: &'static [ParticleType] = &[$(ParticleType::$variant),*];
/// Registry path (`minecraft:<name>`), also the sprite-set file name.
pub fn name(self) -> &'static str {
match self { $(ParticleType::$variant => $name),* }
}
pub fn from_name(name: &str) -> Option<Self> {
let name = name.strip_prefix("minecraft:").unwrap_or(name);
match name { $($name => Some(ParticleType::$variant),)* _ => None }
}
}
};
}
particle_types! {
Block = "block",
BlockCrumble = "block_crumble",
Trail = "trail",
DustPillar = "dust_pillar",
FallingDust = "falling_dust",
Smoke = "smoke",
LargeSmoke = "large_smoke",
WhiteSmoke = "white_smoke",
Flame = "flame",
SoulFireFlame = "soul_fire_flame",
CopperFireFlame = "copper_fire_flame",
SmallFlame = "small_flame",
Lava = "lava",
DrippingWater = "dripping_water",
FallingWater = "falling_water",
DrippingLava = "dripping_lava",
FallingLava = "falling_lava",
LandingLava = "landing_lava",
DrippingHoney = "dripping_honey",
FallingHoney = "falling_honey",
LandingHoney = "landing_honey",
FallingNectar = "falling_nectar",
FallingSporeBlossom = "falling_spore_blossom",
SporeBlossomAir = "spore_blossom_air",
DrippingObsidianTear = "dripping_obsidian_tear",
FallingObsidianTear = "falling_obsidian_tear",
LandingObsidianTear = "landing_obsidian_tear",
DrippingDripstoneWater = "dripping_dripstone_water",
FallingDripstoneWater = "falling_dripstone_water",
DrippingDripstoneLava = "dripping_dripstone_lava",
FallingDripstoneLava = "falling_dripstone_lava",
Splash = "splash",
Rain = "rain",
Bubble = "bubble",
SulfurBubbles = "sulfur_bubbles",
BubblePop = "bubble_pop",
BubbleColumnUp = "bubble_column_up",
CurrentDown = "current_down",
Underwater = "underwater",
Portal = "portal",
ReversePortal = "reverse_portal",
Enchant = "enchant",
Nautilus = "nautilus",
VaultConnection = "vault_connection",
Crit = "crit",
EnchantedHit = "enchanted_hit",
DamageIndicator = "damage_indicator",
Heart = "heart",
AngryVillager = "angry_villager",
HappyVillager = "happy_villager",
Composter = "composter",
Mycelium = "mycelium",
Dolphin = "dolphin",
EggCrack = "egg_crack",
Poof = "poof",
Explosion = "explosion",
ExplosionEmitter = "explosion_emitter",
CampfireCosySmoke = "campfire_cosy_smoke",
CampfireSignalSmoke = "campfire_signal_smoke",
Note = "note",
Dust = "dust",
TotemOfUndying = "totem_of_undying",
Firework = "firework",
EndRod = "end_rod",
Ash = "ash",
WhiteAsh = "white_ash",
CrimsonSpore = "crimson_spore",
WarpedSpore = "warped_spore",
CherryLeaves = "cherry_leaves",
PaleOakLeaves = "pale_oak_leaves",
TintedLeaves = "tinted_leaves",
Effect = "effect",
InstantEffect = "instant_effect",
EntityEffect = "entity_effect",
Witch = "witch",
Infested = "infested",
Cloud = "cloud",
Sneeze = "sneeze",
Snowflake = "snowflake",
Soul = "soul",
SculkSoul = "sculk_soul",
DragonBreath = "dragon_breath",
Gust = "gust",
SmallGust = "small_gust",
GustEmitterLarge = "gust_emitter_large",
GustEmitterSmall = "gust_emitter_small",
DustColorTransition = "dust_color_transition",
SculkCharge = "sculk_charge",
SculkChargePop = "sculk_charge_pop",
Shriek = "shriek",
SonicBoom = "sonic_boom",
Vibration = "vibration",
SweepAttack = "sweep_attack",
Glow = "glow",
WaxOn = "wax_on",
WaxOff = "wax_off",
ElectricSpark = "electric_spark",
Scrape = "scrape",
SquidInk = "squid_ink",
GlowSquidInk = "glow_squid_ink",
Item = "item",
ItemSlime = "item_slime",
ItemSnowball = "item_snowball",
ItemCobweb = "item_cobweb",
SulfurCubeGoo = "sulfur_cube_goo",
Flash = "flash",
Firefly = "firefly",
TrialSpawnerDetection = "trial_spawner_detection",
TrialSpawnerDetectionOminous = "trial_spawner_detection_ominous",
TrialOmen = "trial_omen",
RaidOmen = "raid_omen",
OminousSpawning = "ominous_spawning",
Spit = "spit",
Fishing = "fishing",
DustPlume = "dust_plume",
RedPoplarLeaves = "red_poplar_leaves",
OrangePoplarLeaves = "orange_poplar_leaves",
YellowPoplarLeaves = "yellow_poplar_leaves",
PauseMobGrowth = "pause_mob_growth",
ResetMobGrowth = "reset_mob_growth",
BlockMarker = "block_marker",
}
impl ParticleType {
/// `ParticleType.getOverrideLimiter` (`ParticleTypes.register(name, true)`):
/// spawned regardless of distance.
pub fn override_limiter(self) -> bool {
matches!(
self,
Self::BlockMarker
| Self::DamageIndicator
| Self::ExplosionEmitter
| Self::Explosion
| Self::Gust
| Self::GustEmitterLarge
| Self::GustEmitterSmall
| Self::SonicBoom
| Self::SculkCharge
| Self::SculkChargePop
| Self::Vibration
| Self::Poof
| Self::Spit
| Self::SquidInk
| Self::SweepAttack
| Self::CampfireCosySmoke
| Self::CampfireSignalSmoke
| Self::GlowSquidInk
| Self::Glow
| Self::WaxOn
| Self::WaxOff
| Self::ElectricSpark
| Self::Scrape
| Self::TrialSpawnerDetection
| Self::TrialSpawnerDetectionOminous
| Self::VaultConnection
| Self::OminousSpawning
)
}
/// `SingleQuadParticle.Layer.translucent`: types whose vanilla particle class
/// hardcodes the translucent layer, drawn after translucent terrain.
/// `TerrainParticle`, `BreakingItemParticle` and `BlockMarker` resolve their
/// layer from the sprite instead (`Layer.bySprite`); see the `translucent`
/// sprite set on the engine.
pub fn translucent_layer(self) -> bool {
match self {
// CampfireSmokeParticle.
Self::CampfireCosySmoke | Self::CampfireSignalSmoke
// PlayerCloudParticle.
| Self::Cloud | Self::Sneeze
// SpellParticle.
| Self::Effect | Self::InstantEffect | Self::EntityEffect
| Self::Witch | Self::Infested | Self::TrialOmen | Self::RaidOmen
// EmissiveRisingParticle.
| Self::Soul | Self::SculkSoul
// SculkChargeParticle, SculkChargePopParticle, ShriekParticle,
// VibrationSignalParticle, FireflyParticle, OverlayParticle.
| Self::SculkCharge | Self::SculkChargePop | Self::Shriek
| Self::Vibration | Self::Firefly | Self::Flash
// SimpleAnimatedParticle and its subclasses: EndRodParticle,
// SparkParticle (firework), SquidInkParticle, TotemParticle.
| Self::EndRod | Self::Firework | Self::SquidInk | Self::GlowSquidInk
| Self::TotemOfUndying
// FlyTowardsPositionParticle: its LifetimeAlpha(0, 0.6, 0.25, 1) is not opaque.
| Self::VaultConnection => true,
_ => false,
}
}
}
/// `ParticleOptions` with the parameters of the option classes used here. /// `ParticleOptions` with the parameters of the option classes used here.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
+25 -22
View File
@@ -2435,28 +2435,7 @@ fn write_saved_data(world: &Path, name: &str, data: Tag) -> Result<()> {
Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]), Tag::compound([("data", data), ("DataVersion", Tag::Int(DATA_VERSION))]),
) )
} }
pub fn uuid_text(u: [i32; 4]) -> String { pub use horizon_client_core::uuid::{uuid_from_text, uuid_text};
let hex: String = u.iter().map(|v| format!("{:08x}", *v as u32)).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
)
}
pub fn uuid_from_text(s: &str) -> Option<[i32; 4]> {
let hex: String = s.chars().filter(|c| *c != '-').collect();
if hex.len() != 32 {
return None;
}
let mut out = [0i32; 4];
for (i, v) in out.iter_mut().enumerate() {
*v = u32::from_str_radix(&hex[i * 8..i * 8 + 8], 16).ok()? as i32;
}
Some(out)
}
/// A random (version 4) UUID as vanilla's four-int form. /// A random (version 4) UUID as vanilla's four-int form.
pub fn random_uuid() -> [i32; 4] { pub fn random_uuid() -> [i32; 4] {
let t = std::time::SystemTime::now() let t = std::time::SystemTime::now()
@@ -5125,6 +5104,30 @@ mod tests {
}; };
assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3)); assert_eq!(back.recipes_used.get("minecraft:cooked_porkchop"), Some(&3));
} }
/// The world's save (Level.write) writes the rules as they are now, and a
/// world opened again reads them back (#74).
#[test]
fn level_save_keeps_changed_rules() {
use crate::gamerules::{GameRules, Value};
let dir =
std::env::temp_dir().join(format!("horizon-gamerules-level-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut level = super::Level::default();
level.write(&dir).unwrap();
// Rules changed while playing, then saved and loaded again.
let mut rules = GameRules::load(&dir);
assert_eq!(rules, GameRules::default());
assert!(rules.set("advance_time", Value::Bool(false)));
assert!(rules.set("advance_weather", Value::Bool(false)));
assert!(rules.set("random_tick_speed", Value::Int(0)));
level.game_rules = rules.by_name();
level.write(&dir).unwrap();
assert_eq!(GameRules::load(&dir), rules);
let read = super::Level::read(&dir).unwrap();
assert_eq!(read.game_rules, rules.by_name());
assert_eq!(read.game_rule("advance_time"), 0);
let _ = std::fs::remove_dir_all(dir);
}
/// A save written before the key was namespaced holds an id twice, once bare: vanilla /// A save written before the key was namespaced holds an id twice, once bare: vanilla
/// refuses such a furnace, so a load merges them under the full id. /// refuses such a furnace, so a load merges them under the full id.
+1 -5
View File
@@ -5,11 +5,7 @@ use crate::keybinds::KeyBinds;
use crate::options_file::{OptionsFile, V}; use crate::options_file::{OptionsFile, V};
use std::{fs, path::Path}; use std::{fs, path::Path};
/// SoundSource names in vanilla order. pub use horizon_client_core::sound_source::SOUND_SOURCES;
pub const SOUND_SOURCES: [&str; 11] = [
"master", "music", "record", "weather", "block", "hostile", "neutral", "player", "ambient",
"voice", "ui",
];
/// Per-source volumes for the mixer (soundCategory_* except master). /// Per-source volumes for the mixer (soundCategory_* except master).
static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]); static SOURCE_VOLUMES: std::sync::RwLock<[f32; 11]> = std::sync::RwLock::new([1.0; 11]);
+3
View File
@@ -448,6 +448,7 @@ pub fn grindstone_experience(
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum Smithing { pub enum Smithing {
Transform { Transform {
id: String,
template: Ingredient, template: Ingredient,
base: Ingredient, base: Ingredient,
addition: Ingredient, addition: Ingredient,
@@ -527,6 +528,7 @@ impl StationRecipes {
); );
match v["type"].as_str().unwrap_or("") { match v["type"].as_str().unwrap_or("") {
"minecraft:smithing_transform" => smithing.push(Smithing::Transform { "minecraft:smithing_transform" => smithing.push(Smithing::Transform {
id,
template: ingredient(&v["template"], items), template: ingredient(&v["template"], items),
base: ingredient(&v["base"], items), base: ingredient(&v["base"], items),
addition: ingredient(&v["addition"], items), addition: ingredient(&v["addition"], items),
@@ -630,6 +632,7 @@ impl StationRecipes {
base: b, base: b,
addition: a, addition: a,
result, result,
..
} => { } => {
if t.test(template) && b.test(base) && a.test(addition) { if t.test(template) && b.test(base) && a.test(addition) {
// SmithingTransformRecipe: transmute the base keeping its components. // SmithingTransformRecipe: transmute the base keeping its components.
+113 -9
View File
@@ -175,6 +175,11 @@ pub enum Done {
} }
struct Queued { struct Queued {
priority: i64, priority: i64,
/// The column the job is for and what it adds to the column's distance
/// (`Streaming::submit`): the priority is computed again from them when
/// the centre moves (`Streaming::requeue`). None for saves, which go first.
at: Option<(i32, i32)>,
bias: i64,
order: u64, order: u64,
job: Job, job: Job,
} }
@@ -222,6 +227,9 @@ pub struct Streaming {
/// radius it was last ranked for. /// radius it was last ranked for.
decoration_order: DecorationOrder, decoration_order: DecorationOrder,
order_area: Option<((i32, i32), i32)>, order_area: Option<((i32, i32), i32)>,
/// What the queued jobs' priorities were computed from (`requeue`): the
/// centre, the loading screen, the band, and the extra areas.
queue_basis: (((i32, i32), bool, Option<Band>), Vec<((i32, i32), i32)>),
finishing: FxHashSet<(i32, i32)>, finishing: FxHashSet<(i32, i32)>,
decorates: bool, decorates: bool,
lighting: FxHashMap<(i32, i32), u64>, lighting: FxHashMap<(i32, i32), u64>,
@@ -544,6 +552,7 @@ impl Streaming {
saving: 0, saving: 0,
decoration_order: DecorationOrder::default(), decoration_order: DecorationOrder::default(),
order_area: None, order_area: None,
queue_basis: Default::default(),
finishing: Default::default(), finishing: Default::default(),
decorates: generator.decorates(), decorates: generator.decorates(),
lighting: Default::default(), lighting: Default::default(),
@@ -648,15 +657,39 @@ impl Streaming {
world.dirty_sections.take_column(x, z); world.dirty_sections.take_column(x, z);
world.chunks.remove(&(x, z)) world.chunks.remove(&(x, z))
} }
fn submit(&mut self, priority: i64, job: Job) { /// Queue a job for the column `at`, nearest first: its distance (`distance`)
/// times four plus `bias`, which orders a column's jobs. A job without a
/// column (a save) goes ahead of every other.
fn submit(&mut self, at: Option<(i32, i32)>, bias: i64, job: Job) {
self.order += 1; self.order += 1;
let priority = at.map_or(i64::MIN, |(x, z)| self.distance(x, z) * 4 + bias);
self.shared.queue.lock().unwrap().push(Queued { self.shared.queue.lock().unwrap().push(Queued {
priority, priority,
at,
bias,
order: self.order, order: self.order,
job, job,
}); });
self.shared.ready.notify_one(); self.shared.ready.notify_one();
} }
/// Rank the queued jobs again when what their priorities were computed
/// from changed: the centre, the extra areas, the band, or the loading
/// screen (ring order, `Ranges::rings`, whose values are far above the
/// distances used after it). Vanilla's chunk task queue follows the
/// current ticket levels in the same way. Without it, generation queued
/// while the loading screen was up waited behind every job queued after
/// it, and with it the decoration of the chunks around the player: at
/// render distance 32 nothing was decorated until every proto chunk had
/// been generated.
fn requeue(&mut self) {
let basis = (self.center, self.loading, self.band);
if self.queue_basis.0 == basis && self.queue_basis.1 == self.extra {
return;
}
self.queue_basis = (basis, self.extra.clone());
let mut queue = self.shared.queue.lock().unwrap();
rank_again(&mut queue, |x, z| self.distance(x, z));
}
fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) { fn receive_decorated(&mut self, x: i32, z: i32, region: [Proto; 9]) {
self.generation_scan.exhausted = false; self.generation_scan.exhausted = false;
self.decorating -= 1; self.decorating -= 1;
@@ -686,7 +719,7 @@ impl Streaming {
self.saving += 1; self.saving += 1;
// Ahead of every other job: a column generated again meanwhile // Ahead of every other job: a column generated again meanwhile
// would not find them saved. // would not find them saved.
self.submit(i64::MIN, Job::Save(protos)); self.submit(None, 0, Job::Save(protos));
} }
} }
fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) { fn receive_generated(&mut self, mut chunk: Chunk, world: &mut World) {
@@ -829,6 +862,7 @@ impl Streaming {
return (uploads, Vec::new()); return (uploads, Vec::new());
} }
ExtraCover::refresh(&mut self.cover, &self.extra); ExtraCover::refresh(&mut self.cover, &self.extra);
self.requeue();
self.relight_edits(world); self.relight_edits(world);
let deferred = std::mem::take(&mut self.deferred); let deferred = std::mem::take(&mut self.deferred);
let received = std::iter::from_fn(|| self.results.try_recv().ok()); let received = std::iter::from_fn(|| self.results.try_recv().ok());
@@ -984,7 +1018,7 @@ impl Streaming {
.expect("present proto"); .expect("present proto");
self.finishing.insert((x, z)); self.finishing.insert((x, z));
self.written.remove(&(x, z)); self.written.remove(&(x, z));
self.submit(self.distance(x, z) * 4, Job::Finish(proto)); self.submit(Some((x, z)), 0, Job::Finish(proto));
} }
} }
// Decorate chunks whose 3x3 proto neighbourhood is available, in // Decorate chunks whose 3x3 proto neighbourhood is available, in
@@ -1052,7 +1086,7 @@ impl Streaming {
w.0 = self.decoration_order.rank_or_append(w.2, w.3); w.0 = self.decoration_order.rank_or_append(w.2, w.3);
} }
wanted.sort_unstable(); wanted.sort_unstable();
for (_, d, x, z) in wanted { for (_, _, x, z) in wanted {
if self.decorating >= workers * 2 { if self.decorating >= workers * 2 {
break; break;
} }
@@ -1091,7 +1125,7 @@ impl Streaming {
Err(_) => continue, Err(_) => continue,
}; };
self.decorating += 1; self.decorating += 1;
self.submit(d * 4 + 1, Job::Decorate(x, z, region)); self.submit(Some((x, z)), 1, Job::Decorate(x, z, region));
} }
} }
self.schedule_generation(world, workers); self.schedule_generation(world, workers);
@@ -1111,7 +1145,8 @@ impl Streaming {
self.light_snapshots self.light_snapshots
.insert((x, z), self.light_edit_sequence); .insert((x, z), self.light_edit_sequence);
self.submit( self.submit(
self.distance(x, z) * 4 + 1, Some((x, z)),
1,
Job::Light(x, z, region, self.sequence, self.sky_light), Job::Light(x, z, region, self.sequence, self.sky_light),
); );
} }
@@ -1183,7 +1218,8 @@ impl Streaming {
self.sequence += 1; self.sequence += 1;
self.meshing.insert((x, sy, z), self.sequence); self.meshing.insert((x, sy, z), self.sequence);
self.submit( self.submit(
self.distance(x, z) * 4 + if first { 2 } else { 0 }, Some((x, z)),
if first { 2 } else { 0 },
Job::Mesh( Job::Mesh(
x, x,
sy, sy,
@@ -1222,9 +1258,9 @@ impl Streaming {
loading: self.loading, loading: self.loading,
}; };
if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) { if let Some(wanted) = self.generation_scan.candidates(input, workers * 3) {
for (d, x, z) in wanted { for (_, x, z) in wanted {
self.generating.insert((x, z)); self.generating.insert((x, z));
self.submit(d * 4, Job::Generate(x, z)); self.submit(Some((x, z)), 0, Job::Generate(x, z));
} }
} }
} }
@@ -1738,10 +1774,78 @@ fn section_indexes(mut bits: u32) -> impl Iterator<Item = i32> {
}) })
}) })
} }
/// The queued jobs' priorities computed again from each one's column
/// `distance` (`Streaming::submit`).
fn rank_again(queue: &mut BinaryHeap<Queued>, distance: impl Fn(i32, i32) -> i64) {
if queue.is_empty() {
return;
}
let mut jobs = std::mem::take(queue).into_vec();
for job in &mut jobs {
if let Some((x, z)) = job.at {
job.priority = distance(x, z) * 4 + job.bias;
}
}
*queue = BinaryHeap::from(jobs);
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn queued_jobs_follow_the_centre_and_the_loading_screen() {
let forced = HashSet::new();
let ranges = |center| Ranges {
center,
radius: 32,
extra: &[],
forced: &forced,
cover: None,
band: None,
};
let generate = |x, z, priority, order| Queued {
priority,
at: Some((x, z)),
bias: 0,
order,
job: Job::Generate(x, z),
};
let loading = ranges((0, 0));
let queued = || {
BinaryHeap::from(vec![
// Queued while the loading screen was up: ring order.
generate(3, 1, loading.priority(3, 1, true) * 4, 1),
// Queued after it closed: plain distances, far below any ring past the first.
generate(20, 0, loading.priority(20, 0, false) * 4, 2),
Queued {
priority: i64::MIN,
at: None,
bias: 0,
order: 3,
job: Job::Save(Vec::new()),
},
])
};
let pops = |mut queue: BinaryHeap<Queued>| {
std::iter::from_fn(move || queue.pop())
.map(|q| q.at)
.collect::<Vec<_>>()
};
assert_eq!(
pops(queued()),
[None, Some((20, 0)), Some((3, 1))],
"the stale order"
);
let mut queue = queued();
rank_again(&mut queue, |x, z| loading.priority(x, z, false));
assert_eq!(pops(queue), [None, Some((3, 1)), Some((20, 0))]);
// The player moved: the job near the new centre goes first.
let mut queue = BinaryHeap::from(vec![generate(3, 1, 0, 1), generate(20, 0, 1, 2)]);
let moved = ranges((19, 0));
rank_again(&mut queue, |x, z| moved.priority(x, z, false));
assert_eq!(queue.pop().and_then(|q| q.at), Some((20, 0)));
}
#[test] #[test]
fn view_distance_is_vanillas_shape() { fn view_distance_is_vanillas_shape() {
// ChunkTrackingView.isInViewDistance at render distance 12: a column // ChunkTrackingView.isInViewDistance at render distance 12: a column
+15 -4
View File
@@ -9,7 +9,7 @@ use horizon_world::{
}; };
use std::{ use std::{
path::Path, path::Path,
sync::{Arc, OnceLock}, sync::{Arc, Mutex},
}; };
/// The `custom_data` key holding an exploration map's search until the game /// The `custom_data` key holding an exploration map's search until the game
@@ -114,11 +114,13 @@ pub fn has_pending_map(item: &ItemStack) -> bool {
}) })
} }
static LOOT: OnceLock<Option<Arc<LootData>>> = OnceLock::new(); /// None until `loot_data` runs; `Some(None)` when the tables failed to load.
static LOOT: Mutex<Option<Option<Arc<LootData>>>> = Mutex::new(None);
/// Loot data of the resource root, loaded once per process. /// Loot data of the resource root, loaded once per process.
pub fn loot_data(root: &Path) -> Option<Arc<LootData>> { pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
LOOT.get_or_init(|| match LootData::load(root) { let mut loot = LOOT.lock().unwrap_or_else(|e| e.into_inner());
loot.get_or_insert_with(|| match LootData::load(root) {
Ok(data) => Some(Arc::new(data)), Ok(data) => Some(Arc::new(data)),
Err(e) => { Err(e) => {
log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}"); log::warn!("Horizon: loot tables unavailable, structure containers stay empty: {e}");
@@ -130,7 +132,16 @@ pub fn loot_data(root: &Path) -> Option<Arc<LootData>> {
/// The loot data `loot_data` loaded, if it ran. /// The loot data `loot_data` loaded, if it ran.
pub fn loaded_loot_data() -> Option<Arc<LootData>> { pub fn loaded_loot_data() -> Option<Arc<LootData>> {
LOOT.get().cloned().flatten() LOOT.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
.flatten()
}
/// Let go of the loot data: for a preload no world used
/// (game/world_loading.rs). The next `loot_data` loads it again.
pub fn forget_loot_data() {
*LOOT.lock().unwrap_or_else(|e| e.into_inner()) = None;
} }
/// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table` /// `RandomizableContainer.unpackLootTable` of a container at `pos`: `table`
+11 -3
View File
@@ -333,15 +333,23 @@ impl VanillaTerrain {
u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX) u64::try_from(self.created.elapsed().as_millis()).unwrap_or(u64::MAX)
} }
} }
static SHARED_DATA: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> =
std::sync::Mutex::new(Vec::new());
/// Let go of the bundles `shared_data` loaded: for a preload no world used
/// (game/world_loading.rs). A generator that holds one keeps it.
pub fn forget_shared_data() {
SHARED_DATA
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
/// The worldgen bundle at `dir`, loaded once and shared by every generator /// The worldgen bundle at `dir`, loaded once and shared by every generator
/// and by live feature placement (sapling growth, bone meal). /// and by live feature placement (sapling growth, bone meal).
pub fn shared_data( pub fn shared_data(
dir: &Path, dir: &Path,
registry: &'static BlockRegistry, registry: &'static BlockRegistry,
) -> crate::Result<Arc<GeneratorData>> { ) -> crate::Result<Arc<GeneratorData>> {
static CACHE: std::sync::Mutex<Vec<(std::path::PathBuf, Arc<GeneratorData>)>> = let mut cache = SHARED_DATA.lock().unwrap_or_else(|e| e.into_inner());
std::sync::Mutex::new(Vec::new());
let mut cache = CACHE.lock().unwrap_or_else(|e| e.into_inner());
if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) { if let Some((_, data)) = cache.iter().find(|(path, _)| path == dir) {
return Ok(data.clone()); return Ok(data.clone());
} }
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "horizon-command"
version = "0.1.0"
edition.workspace = true
license.workspace = true
rust-version = "1.90"
description = "Commands (Brigadier): the vanilla command tree, argument types, selectors, parsing, suggestions and the network form of the tree"
[dependencies]
horizon-client-core = { path = "../horizon-client-core" }
horizon-protocol = { path = "../horizon-protocol" }
horizon-world = { path = "../horizon-world" }
[lints]
workspace = true
@@ -1,192 +1,8 @@
//! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with //! Argument types (Brigadier's and Minecraft's `ArgumentType`s): parsing with
//! the vanilla error messages and completion suggestions. //! the vanilla error messages and completion suggestions.
use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder}; use super::{CmdResult, CommandError, Context, Reader, SuggestionsBuilder};
use std::collections::BTreeMap;
/// Registry contents and source state used to validate and complete arguments. pub use horizon_client_core::registries::{Registries, RegistryIds};
#[derive(Clone, Debug, Default)]
pub struct Registries {
/// Permission level of the command source.
pub permission: u8,
pub items: Vec<String>,
pub item_tags: Vec<String>,
/// Block id -> (property, allowed values).
pub blocks: BTreeMap<String, Vec<(String, Vec<String>)>>,
pub block_tags: Vec<String>,
/// Entity types that `summon` can create.
pub summonable: Vec<String>,
/// Every entity type (selector `type=`).
pub entity_types: Vec<String>,
pub effects: Vec<String>,
pub enchantments: Vec<String>,
pub structures: Vec<String>,
pub biomes: Vec<String>,
pub dimensions: Vec<String>,
pub clocks: Vec<String>,
pub timelines: Vec<String>,
pub time_markers: Vec<String>,
pub advancements: Vec<String>,
/// Game rule name -> integer-valued.
pub game_rules: Vec<(String, bool)>,
pub players: Vec<String>,
/// Scoreboard objective names, team names and tracked score holders.
pub objectives: Vec<String>,
pub teams: Vec<String>,
pub tracked: Vec<String>,
/// Loaded datapack functions (`ns:path`) and function tags (`ns:path`).
pub functions: Vec<String>,
/// `/data ... storage` ids.
pub storages: Vec<String>,
/// Boss bar ids and datapack predicate ids.
pub bossbars: Vec<String>,
pub predicates: Vec<String>,
pub item_modifiers: Vec<String>,
pub schedules: Vec<String>,
pub stopwatches: Vec<String>,
pub recipes: Vec<String>,
pub sounds: Vec<String>,
pub damage_types: Vec<String>,
pub attributes: Vec<String>,
pub loot_tables: Vec<String>,
pub templates: Vec<String>,
pub random_sequences: Vec<String>,
pub datapacks_enabled: Vec<String>,
pub datapacks_disabled: Vec<String>,
pub function_tags: Vec<String>,
/// The block the source is looking at (relevant coordinates).
pub target_block: Option<[i32; 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>,
/// Blocks whose default state has a block entity.
pub block_entities: std::collections::BTreeSet<String>,
/// Block tag -> member blocks.
pub block_tag_members: BTreeMap<String, Vec<String>>,
/// Data component types with a codec (not transient).
pub persistent_components: Vec<String>,
/// Recipes `/recipe` can give (not special).
pub learnable_recipes: Vec<String>,
/// Advancement id -> criterion names.
pub advancement_criteria: BTreeMap<String, Vec<String>>,
/// World clock -> time markers shown in commands.
pub clock_time_markers: BTreeMap<String, Vec<String>>,
/// Trigger objectives the source may use (`/trigger` suggestions).
pub trigger_objectives: Vec<String>,
/// Objectives with the `trigger` criterion -> holder -> whether its score is locked.
pub trigger_scores: BTreeMap<String, BTreeMap<String, bool>>,
}
/// The ids and tag ids of one registry.
#[derive(Clone, Debug, Default)]
pub struct RegistryIds {
pub ids: Vec<String>,
pub tags: Vec<String>,
}
const EMPTY: &[String] = &[];
impl Registries {
/// 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
/// mob effects, data component types and dialogs, block entities and tag
/// members. Registries that data packs reload stay with the game.
pub fn fill_from_export(&mut self, r: &serde_json::Value) {
fn strings(v: &serde_json::Value) -> Vec<String> {
v.as_array()
.map(|a| {
a.iter()
.filter_map(|x| x.as_str().map(str::to_owned))
.collect()
})
.unwrap_or_default()
}
let fill = |field: &mut Vec<String>, key: &str| {
if field.is_empty() {
*field = strings(&r[key]);
}
};
fill(&mut self.effects, "effects");
fill(&mut self.enchantments, "enchantments");
fill(&mut self.attributes, "attributes");
fill(&mut self.damage_types, "damage_types");
fill(&mut self.templates, "templates");
fill(&mut self.persistent_components, "persistent_components");
fill(&mut self.learnable_recipes, "learnable_recipes");
const RELOADED: [&str; 5] = [
"minecraft:advancement",
"minecraft:recipe",
"minecraft:loot_table",
"minecraft:predicate",
"minecraft:item_modifier",
];
for (name, entry) in r["by_registry"].as_object().into_iter().flatten() {
if RELOADED.contains(&name.as_str()) || self.by_registry.contains_key(name) {
continue;
}
self.by_registry.insert(
name.clone(),
RegistryIds {
ids: strings(&entry["ids"]),
tags: strings(&entry["tags"]),
},
);
}
if self.block_entities.is_empty() {
self.block_entities = strings(&r["block_entities"]).into_iter().collect();
}
if self.block_tag_members.is_empty() {
for (tag, members) in r["block_tag_members"].as_object().into_iter().flatten() {
self.block_tag_members.insert(tag.clone(), strings(members));
}
}
if self.clock_time_markers.is_empty() {
for (clock, markers) in r["clock_time_markers"].as_object().into_iter().flatten() {
self.clock_time_markers
.insert(clock.clone(), strings(markers));
}
}
if self.advancement_criteria.is_empty() {
for (id, criteria) in r["advancement_criteria"].as_object().into_iter().flatten() {
self.advancement_criteria
.insert(id.clone(), strings(criteria));
}
}
}
/// The element ids of a registry (sorted).
pub fn ids(&self, registry: &str) -> &[String] {
if let Some(r) = self.by_registry.get(registry) {
return &r.ids;
}
match registry {
"minecraft:item" => &self.items,
"minecraft:entity_type" => &self.entity_types,
"minecraft:mob_effect" => &self.effects,
"minecraft:enchantment" => &self.enchantments,
"minecraft:worldgen/structure" => &self.structures,
"minecraft:worldgen/biome" => &self.biomes,
"minecraft:world_clock" => &self.clocks,
"minecraft:timeline" => &self.timelines,
"minecraft:attribute" => &self.attributes,
"minecraft:damage_type" => &self.damage_types,
"minecraft:sound_event" => &self.sounds,
"minecraft:predicate" => &self.predicates,
"minecraft:item_modifier" => &self.item_modifiers,
"minecraft:loot_table" => &self.loot_tables,
"minecraft:recipe" => &self.recipes,
"minecraft:advancement" => &self.advancements,
_ => EMPTY,
}
}
/// The tag ids of a registry (sorted).
pub fn tags(&self, registry: &str) -> &[String] {
if let Some(r) = self.by_registry.get(registry) {
return &r.tags;
}
match registry {
"minecraft:item" => &self.item_tags,
"minecraft:block" => &self.block_tags,
_ => EMPTY,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Resource { pub enum Resource {
@@ -637,22 +453,7 @@ pub fn read_identifier(reader: &mut Reader) -> CmdResult<String> {
} }
} }
} }
/// Identifier.parse: `ns:path` or `path`, validated. pub use horizon_client_core::identifier::parse_identifier;
pub fn parse_identifier(raw: &str) -> Option<String> {
let (ns, path) = match raw.split_once(':') {
Some(("", path)) => ("minecraft", path),
Some((ns, path)) => (ns, path),
None => ("minecraft", raw),
};
let ns_ok = ns != ".."
&& ns
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-'));
let path_ok = path.chars().all(|c| {
c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, '_' | '.' | '-' | '/')
});
(ns_ok && path_ok).then(|| format!("{ns}:{path}"))
}
pub fn normalize(id: &str) -> String { pub fn normalize(id: &str) -> String {
match id.split_once(':') { match id.split_once(':') {
Some(("", path)) => format!("minecraft:{path}"), Some(("", path)) => format!("minecraft:{path}"),
@@ -1220,7 +1021,10 @@ impl ArgType {
reader.cursor = start; reader.cursor = start;
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.float.low", "argument.float.low",
&[&crate::snbt::java_float(*min), &crate::snbt::java_float(v)], &[
&horizon_client_core::snbt::java_float(*min),
&horizon_client_core::snbt::java_float(v),
],
reader, reader,
)); ));
} }
@@ -1228,7 +1032,10 @@ impl ArgType {
reader.cursor = start; reader.cursor = start;
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.float.big", "argument.float.big",
&[&crate::snbt::java_float(*max), &crate::snbt::java_float(v)], &[
&horizon_client_core::snbt::java_float(*max),
&horizon_client_core::snbt::java_float(v),
],
reader, reader,
)); ));
} }
@@ -1241,8 +1048,8 @@ impl ArgType {
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.double.low", "argument.double.low",
&[ &[
&crate::snbt::java_double(*min), &horizon_client_core::snbt::java_double(*min),
&crate::snbt::java_double(v), &horizon_client_core::snbt::java_double(v),
], ],
reader, reader,
)); ));
@@ -1252,8 +1059,8 @@ impl ArgType {
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.double.big", "argument.double.big",
&[ &[
&crate::snbt::java_double(*max), &horizon_client_core::snbt::java_double(*max),
&crate::snbt::java_double(v), &horizon_client_core::snbt::java_double(v),
], ],
reader, reader,
)); ));
@@ -1597,7 +1404,7 @@ impl ArgType {
return Err(CommandError::tr_at(key, &[&m], reader)); return Err(CommandError::tr_at(key, &[&m], reader));
} }
let text = &reader.string[start..reader.cursor]; let text = &reader.string[start..reader.cursor];
match crate::component::parse_snbt(text) { match horizon_client_core::component::parse_snbt(text) {
Ok((v, _)) => Arg::Str(v.to_string()), Ok((v, _)) => Arg::Str(v.to_string()),
Err(_) => Arg::Str(text.to_owned()), Err(_) => Arg::Str(text.to_owned()),
} }
@@ -1645,7 +1452,7 @@ impl ArgType {
} }
let id = &reader.string[start..reader.cursor]; let id = &reader.string[start..reader.cursor];
// ObjectiveCriteria.byName: statistics resolve to their canonical name. // ObjectiveCriteria.byName: statistics resolve to their canonical name.
match crate::scoreboard::criteria_by_name(id, reg) { match horizon_client_core::scoreboard::criteria_by_name(id, reg) {
Ok(Some(canonical)) => Arg::Str(canonical), Ok(Some(canonical)) => Arg::Str(canonical),
Ok(None) => { Ok(None) => {
reader.cursor = start; reader.cursor = start;
@@ -1667,7 +1474,7 @@ impl ArgType {
} }
ArgType::ScoreboardSlot => { ArgType::ScoreboardSlot => {
let name = reader.read_unquoted_string(); let name = reader.read_unquoted_string();
if !crate::scoreboard::display_slot_valid(name) { if !horizon_client_core::scoreboard::display_slot_valid(name) {
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.scoreboardDisplaySlot.invalid", "argument.scoreboardDisplaySlot.invalid",
&[&name], &[&name],
@@ -1695,7 +1502,7 @@ impl ArgType {
} }
ArgType::TeamColor => { ArgType::TeamColor => {
let name = reader.read_unquoted_string(); let name = reader.read_unquoted_string();
if crate::scoreboard::team_color_rgb(name).is_none() { if horizon_client_core::scoreboard::team_color_rgb(name).is_none() {
return Err(CommandError::tr_at( return Err(CommandError::tr_at(
"argument.color.invalid", "argument.color.invalid",
&[&name], &[&name],
@@ -1743,7 +1550,7 @@ impl ArgType {
let id = read_identifier(reader)?; let id = read_identifier(reader)?;
let known = reg.ids("minecraft:particle_type"); let known = reg.ids("minecraft:particle_type");
let exists = if known.is_empty() { let exists = if known.is_empty() {
crate::particles::ParticleType::from_name(&id).is_some() horizon_client_core::particle_type::ParticleType::from_name(&id).is_some()
} else { } else {
known.contains(&id) known.contains(&id)
}; };
@@ -1931,15 +1738,16 @@ impl ArgType {
} }
ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)), ArgType::Team => builder.suggest_matching(reg.teams.iter().map(String::as_str)),
ArgType::Criteria => { ArgType::Criteria => {
let mut ids: Vec<String> = crate::scoreboard::CUSTOM_CRITERIA let mut ids: Vec<String> = horizon_client_core::scoreboard::CUSTOM_CRITERIA
.iter() .iter()
.map(|s| (*s).to_owned()) .map(|s| (*s).to_owned())
.collect(); .collect();
for c in crate::scoreboard::team_colors() { for c in horizon_client_core::scoreboard::team_colors() {
ids.push(format!("teamkill.{c}")); ids.push(format!("teamkill.{c}"));
ids.push(format!("killedByTeam.{c}")); ids.push(format!("killedByTeam.{c}"));
} }
let stat = |ty: &str, key: &str| crate::scoreboard::stat_criteria(ty, key); let stat =
|ty: &str, key: &str| horizon_client_core::scoreboard::stat_criteria(ty, key);
ids.extend(reg.blocks.keys().map(|b| stat("mined", b))); ids.extend(reg.blocks.keys().map(|b| stat("mined", b)));
for ty in ["crafted", "used", "broken", "picked_up", "dropped"] { for ty in ["crafted", "used", "broken", "picked_up", "dropped"] {
ids.extend(reg.items.iter().map(|i| stat(ty, i))); ids.extend(reg.items.iter().map(|i| stat(ty, i)));
@@ -1948,14 +1756,14 @@ impl ArgType {
ids.extend(reg.entity_types.iter().map(|e| stat(ty, e))); ids.extend(reg.entity_types.iter().map(|e| stat(ty, e)));
} }
ids.extend( ids.extend(
crate::scoreboard::CUSTOM_STATS horizon_client_core::scoreboard::CUSTOM_STATS
.iter() .iter()
.map(|c| stat("custom", &format!("minecraft:{c}"))), .map(|c| stat("custom", &format!("minecraft:{c}"))),
); );
builder.suggest_matching(ids.iter().map(String::as_str)); builder.suggest_matching(ids.iter().map(String::as_str));
} }
ArgType::ScoreboardSlot => { ArgType::ScoreboardSlot => {
let slots = crate::scoreboard::display_slots(); let slots = horizon_client_core::scoreboard::display_slots();
builder.suggest_matching(slots.iter().map(String::as_str)); builder.suggest_matching(slots.iter().map(String::as_str));
} }
ArgType::Operation => builder.suggest_matching(OPERATIONS), ArgType::Operation => builder.suggest_matching(OPERATIONS),
@@ -1963,7 +1771,7 @@ impl ArgType {
ArgType::Particle => { ArgType::Particle => {
let known = reg.ids("minecraft:particle_type"); let known = reg.ids("minecraft:particle_type");
if known.is_empty() { if known.is_empty() {
let names: Vec<String> = crate::particles::ParticleType::ALL let names: Vec<String> = horizon_client_core::particle_type::ParticleType::ALL
.iter() .iter()
.map(|t| format!("minecraft:{}", t.name())) .map(|t| format!("minecraft:{}", t.name()))
.collect(); .collect();
@@ -1999,7 +1807,9 @@ impl ArgType {
suggest_resources(builder, reg.ids("minecraft:slot_source"), ""); suggest_resources(builder, reg.ids("minecraft:slot_source"), "");
} }
ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""), ArgType::ResourceOrId(registry) => suggest_resources(builder, reg.ids(registry), ""),
ArgType::TeamColor => builder.suggest_matching(crate::scoreboard::team_colors()), ArgType::TeamColor => {
builder.suggest_matching(horizon_client_core::scoreboard::team_colors())
}
ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]), ArgType::Anchor => builder.suggest_matching(["eyes", "feet"]),
ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder), ArgType::Component | ArgType::Style | ArgType::NbtTag => super::snbt::suggest(builder),
ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {} ArgType::Swizzle | ArgType::Message | ArgType::Nbt => {}
@@ -6,7 +6,7 @@ use super::{CmdResult, CommandError, Reader};
use horizon_world::nbt::{Compound, JavaString, Tag}; use horizon_world::nbt::{Compound, JavaString, Tag};
pub fn snbt(t: &Tag) -> String { pub fn snbt(t: &Tag) -> String {
crate::snbt::to_snbt(t) horizon_client_core::snbt::to_snbt(t)
} }
pub fn not_map(t: &Tag) -> String { pub fn not_map(t: &Tag) -> String {
format!("Not a map: {}", snbt(t)) format!("Not a map: {}", snbt(t))
@@ -164,7 +164,7 @@ fn color(t: &Tag) -> R {
_ => partial(format!("Invalid color value: {s}")), _ => partial(format!("Invalid color value: {s}")),
}; };
} }
if crate::text::named_color(&s).is_some() { if horizon_client_core::text::named_color(&s).is_some() {
Ok(()) Ok(())
} else { } else {
partial(format!("Invalid color name: {s}")) partial(format!("Invalid color name: {s}"))
@@ -278,7 +278,7 @@ fn content(kind: &str, map: &Compound) -> bool {
"nbt" => { "nbt" => {
let path_ok = get(map, "nbt") let path_ok = get(map, "nbt")
.and_then(string_of) .and_then(string_of)
.is_some_and(|p| crate::nbt_path::NbtPath::parse(&p).is_ok()); .is_some_and(|p| horizon_client_core::nbt_path::NbtPath::parse(&p).is_ok());
let source = if let Some(e) = get(map, "entity") { let source = if let Some(e) = get(map, "entity") {
selector_string(e) selector_string(e)
} else if let Some(b) = get(map, "block") { } else if let Some(b) = get(map, "block") {
@@ -72,9 +72,9 @@ pub fn decode_component(id: &str, t: &Tag) -> Result<(), String> {
} else { } else {
format!("minecraft:{id}") format!("minecraft:{id}")
}; };
let known = crate::block_entity_nbt::TYPES let known = horizon_client_core::block_entity_nbt::TYPES
.iter() .iter()
.chain(&crate::block_entity_nbt::NEWEST) .chain(&horizon_client_core::block_entity_nbt::NEWEST)
.any(|k| *k == id); .any(|k| *k == id);
if known { if known {
Ok(()) Ok(())
@@ -3,6 +3,7 @@
//! relevant child and keeps the best result, completion suggestions, smart //! relevant child and keeps the best result, completion suggestions, smart
//! usage text and the vanilla error messages. Argument types live in //! usage text and the vanilla error messages. Argument types live in
//! [`args`]; the vanilla command tree in [`vanilla`]. //! [`args`]; the vanilla command tree in [`vanilla`].
#![forbid(unsafe_code)]
pub mod args; pub mod args;
pub mod block; pub mod block;
pub mod codec; pub mod codec;
@@ -21,8 +22,8 @@ pub mod tree_world;
pub mod vanilla; pub mod vanilla;
mod vanilla_order; mod vanilla_order;
use crate::text::Text;
pub use args::{Arg, ArgType, Registries}; pub use args::{Arg, ArgType, Registries};
use horizon_client_core::text::Text;
/// The command id of a mod's command (`Dispatcher::with_mod_commands`). /// The command id of a mod's command (`Dispatcher::with_mod_commands`).
pub const MOD_COMMAND: &str = "mod"; pub const MOD_COMMAND: &str = "mod";
@@ -623,8 +624,10 @@ impl Suggests {
for id in &reg.summonable { for id in &reg.summonable {
if args::resource_matches(&contents, id) { if args::resource_matches(&contents, id) {
let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id)); let (ns, path) = id.split_once(':').unwrap_or(("minecraft", id));
let name = let name = horizon_client_core::lang::get(&format!(
crate::lang::get(&format!("entity.{ns}.{}", path.replace('/', "."))); "entity.{ns}.{}",
path.replace('/', ".")
));
builder.suggest_tooltip(id.clone(), name); builder.suggest_tooltip(id.clone(), name);
} }
} }
@@ -402,7 +402,7 @@ impl<'g, V: Value> State<'g, V> {
Reason::Error(e) => e.clone(), Reason::Error(e) => e.clone(),
}; };
} }
CommandError::new(crate::text::Text::literal("Failed to parse")) CommandError::new(horizon_client_core::text::Text::literal("Failed to parse"))
} }
/// CachedParseState.parse: a named rule, memoised per position. /// CachedParseState.parse: a named rule, memoised per position.
pub fn parse(&mut self, rule: RuleId) -> Option<V> { pub fn parse(&mut self, rule: RuleId) -> Option<V> {
@@ -687,7 +687,7 @@ impl<'r, 'a> SelectorParser<'r, 'a> {
fn fill_selectors(builder: &mut SuggestionsBuilder) { fn fill_selectors(builder: &mut SuggestionsBuilder) {
for (s, tip) in SELECTOR_KINDS { for (s, tip) in SELECTOR_KINDS {
builder.suggest_tooltip(s, crate::lang::get(tip)); builder.suggest_tooltip(s, horizon_client_core::lang::get(tip));
} }
} }
@@ -785,7 +785,9 @@ impl<'r, 'a> SelectorParser<'r, 'a> {
if self.can_use(o) && o.starts_with(&lower) { if self.can_use(o) && o.starts_with(&lower) {
b.suggest_tooltip( b.suggest_tooltip(
format!("{o}="), format!("{o}="),
crate::lang::get(&format!("argument.entity.options.{o}.description")), horizon_client_core::lang::get(&format!(
"argument.entity.options.{o}.description"
)),
); );
} }
} }
@@ -230,12 +230,12 @@ fn bossbar(d: &mut Dispatcher, root: usize) {
let name = d.argument(name_l, "name", ArgType::Component); let name = d.argument(name_l, "name", ArgType::Component);
d.executes(name, "bossbar.set.name"); d.executes(name, "bossbar.set.name");
let color = d.literal(id, "color"); let color = d.literal(id, "color");
for c in crate::bossbar::COLORS { for c in horizon_client_core::bossbar::COLORS {
let l = d.literal(color, c); let l = d.literal(color, c);
d.executes(l, "bossbar.set.color"); d.executes(l, "bossbar.set.color");
} }
let style = d.literal(id, "style"); let style = d.literal(id, "style");
for s in crate::bossbar::STYLES { for s in horizon_client_core::bossbar::STYLES {
let l = d.literal(style, s); let l = d.literal(style, s);
d.executes(l, "bossbar.set.style"); d.executes(l, "bossbar.set.style");
} }
@@ -7,7 +7,7 @@ use super::{
args::{ArgType, integer}, args::{ArgType, integer},
vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS}, vanilla::{ENTITIES, ENTITY, GAMEMASTERS, PLAYERS},
}; };
use crate::settings::SOUND_SOURCES; use horizon_client_core::sound_source::SOUND_SOURCES;
fn float(min: f32) -> ArgType { fn float(min: f32) -> ArgType {
ArgType::Float { min, max: f32::MAX } ArgType::Float { min, max: f32::MAX }
@@ -5,7 +5,7 @@ use super::{
Dispatcher, Dispatcher,
args::{ArgType, Resource, integer}, args::{ArgType, Resource, integer},
}; };
use crate::gamerules::{RULES, Value}; use horizon_client_core::gamerules::{RULES, Value};
/// Permission levels (Commands.LEVEL_*). /// Permission levels (Commands.LEVEL_*).
pub const ALL: u8 = 0; pub const ALL: u8 = 0;
@@ -0,0 +1,16 @@
[package]
name = "beacons"
version = "0.1.0"
edition.workspace = true
license.workspace = true
publish = false
description = "Example Horizon server mod: /beacon lights a pillar beside you, /ground says what you stand on"
[lib]
crate-type = ["cdylib"]
[dependencies]
horizon-mod-sdk = { path = "../.." }
[lints]
workspace = true
@@ -0,0 +1,8 @@
id = "beacons"
name = "Beacons"
version = "0.1.0"
description = "/beacon lights a pillar of glowstone beside you; /ground says what you are standing on, and in which biome."
authors = ["Horizon"]
api = "0.3"
side = "server"
capabilities = ["players", "world"]
@@ -0,0 +1,87 @@
//! Example Horizon server mod (`docs/mods.md`, "Server mods") with
//! capability `world`: `/beacon` lights a pillar of glowstone two blocks east
//! of the player, `/ground` reads the block under their feet and the biome.
use horizon_mod_sdk::server::{BlockChange, Player, Registration, ServerMod, players, world};
/// How tall `/beacon` builds.
const HEIGHT: i32 = 4;
struct Beacons;
/// The block the player stands in: their feet, floored.
fn feet(player: &Player) -> (i32, i32, i32) {
(
player.x.floor() as i32,
player.y.floor() as i32,
player.z.floor() as i32,
)
}
/// The pillar beside `player`: `HEIGHT` blocks of glowstone, from their feet up.
fn pillar(player: &Player) -> Vec<BlockChange> {
let (x, y, z) = feet(player);
(0..HEIGHT)
.map(|dy| BlockChange {
x: x + 2,
y: y + dy,
z,
state: "minecraft:glowstone".into(),
})
.collect()
}
impl ServerMod for Beacons {
fn init() -> Result<(Self, Registration), String> {
Ok((
Beacons,
Registration::new().command("beacon").command("ground"),
))
}
fn command(
&mut self,
player: &Player,
name: &str,
_args: &str,
) -> Result<Option<String>, String> {
let (x, y, z) = feet(player);
if name == "beacon" {
world::set_blocks(&player.dimension, &pillar(player))?;
players::broadcast(&format!(
"{} lit a beacon at {} {y} {z}",
player.name,
x + 2
));
return Ok(None);
}
let below = world::get_block(&player.dimension, x, y - 1, z)
.ok_or("The ground under you isn't loaded")?;
let biome = world::get_biome(&player.dimension, x, y, z).unwrap_or_default();
Ok(Some(format!("You are standing on {below} in {biome}")))
}
}
horizon_mod_sdk::export_server_mod!(Beacons);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_pillar_stands_two_blocks_east() {
let p = Player {
id: String::new(),
name: "Alex".into(),
x: -0.5,
y: 64.0,
z: 3.2,
dimension: "minecraft:overworld".into(),
game_mode: horizon_mod_sdk::server::GameMode::Survival,
health: 20.0,
};
let blocks = pillar(&p);
assert_eq!(blocks.len(), HEIGHT as usize);
assert_eq!((blocks[0].x, blocks[0].y, blocks[0].z), (1, 64, 3));
assert_eq!(blocks[3].y, 67);
}
}
@@ -0,0 +1,22 @@
# /ground reads the block under the player and the biome; /beacon sets four blocks of glowstone two to the east.
[[step]]
join = "Alex"
blocks = [{ x = 0, y = 63, z = 0, state = "minecraft:grass_block[snowy=false]" }]
command = "ground"
expect.feedback = "You are standing on minecraft:grass_block[snowy=false] in minecraft:plains"
[[step]]
command = "beacon"
expect.broadcast = ["Alex lit a beacon at 2 64 0"]
expect.blocks = [
{ x = 2, y = 64, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 67, z = 0, state = "minecraft:glowstone" },
{ x = 2, y = 68, z = 0, state = "minecraft:air" },
]
# Anywhere the script set nothing is air.
[[step]]
player = { x = 10.5, z = 10.5 }
command = "ground"
expect.feedback = "You are standing on minecraft:air in minecraft:plains"
+4 -1
View File
@@ -39,7 +39,9 @@ wit_bindgen::generate!({
pub use exports::horizon::mods::events::{Guest as __Guest, Registration}; pub use exports::horizon::mods::events::{Guest as __Guest, Registration};
pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest; pub use exports::horizon::mods::ui_events::Guest as __UiEventsGuest;
pub use horizon::mods::{chat, command, game, hud, input, log, render, storage, ui}; pub use horizon::mods::{
browser, chat, command, game, hud, input, log, recipes, render, storage, ui,
};
/// The game's calls into a mod. Only the hooks [`Registration`] asks for /// The game's calls into a mod. Only the hooks [`Registration`] asks for
/// are called; the others may stay as their defaults. /// are called; the others may stay as their defaults.
@@ -194,6 +196,7 @@ pub mod server {
pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration}; pub use exports::horizon::mods::server_events::{BlockPos, Guest as __Guest, Registration};
pub use horizon::mods::players::{self, GameMode, Player}; pub use horizon::mods::players::{self, GameMode, Player};
pub use horizon::mods::world::{self, BlockChange};
/// The server's calls into a mod. Only the hooks [`Registration`] asks /// The server's calls into a mod. Only the hooks [`Registration`] asks
/// for are called; the others may stay as their defaults. /// for are called; the others may stay as their defaults.
+211
View File
@@ -439,6 +439,181 @@ interface events {
chat: func(text: string); chat: func(text: string);
} }
/// Capability `recipes` (experimental): the recipes and items the game
/// knows, for recipe viewers. In single player and on Horizon's servers
/// they are the world's; on any other server they are vanilla 26.3's (a
/// client is sent no others), while `known` follows that server's book.
interface recipes {
/// An item of `items`, by its index there, with a count and the
/// components it has beyond the item's own, in vanilla's item syntax
/// (`[potion_contents={potion:"minecraft:swiftness"}]`), or "".
record stack {
item: u32,
count: u32,
components: string,
}
/// The station a recipe is made at.
enum kind {
crafting-shaped,
crafting-shapeless,
smelting,
blasting,
smoking,
campfire,
stonecutting,
smithing,
brewing,
}
record recipe {
/// `minecraft:oak_planks`.
id: string,
kind: kind,
/// The recipe book's tab (`crafting_building_blocks`,
/// `furnace_food`), or "".
category: string,
/// Recipes the book shows on one button share a group, or "".
group: string,
/// A shaped recipe's grid: `slots` holds its cells row by row.
/// 0 for the other kinds.
width: u32,
height: u32,
/// Each slot's stacks, any one of which fits; an empty list is an
/// empty cell. Cooking and stonecutting: the input. Smithing: the
/// template, the base, the addition. Brewing: the bottle, the
/// reagent.
slots: list<list<stack>>,
/// What it makes; several when that varies (a trim on any armour).
results: list<stack>,
/// Cooking: game ticks and experience; 0 for the other kinds.
cooking-time: u32,
experience: f32,
/// The recipe book's id for it (one per way the book shows it), as
/// `known` lists them; -1 for the kinds the book doesn't show
/// (campfire, stonecutting, smithing, brewing).
book-id: s32,
}
record item {
/// `minecraft:diamond`, `<mod>:<path>`.
id: string,
/// In the player's language.
name: string,
/// Its item tags, without the `#`.
tags: list<string>,
}
/// Every item, in the registry's order: `stack.item` indexes this list.
items: func() -> list<item>;
/// Every recipe: the book's in its order, then campfire, stonecutting,
/// smithing and brewing. They don't change while a world is open.
all: func() -> list<recipe>;
/// The `book-id`s of the recipes the player's recipe book holds now.
known: func() -> list<s32>;
/// Places a recipe in the open screen's grid as a click in the recipe
/// book does (`ServerboundPlaceRecipePacket`): the inventory's grid or
/// a crafting table. `all` places as many as the items allow, as with
/// Shift. Refused while no such screen is open, for a recipe the
/// player's book doesn't hold and for one that can't be placed; one
/// missing items shows as a ghost in the grid, as in the book.
place: func(book-id: s32, all: bool) -> result<_, string>;
/// Creative mode only: gives the player the stack, as taking it from
/// the creative inventory does (`ServerboundSetCreativeModeSlot`): the
/// selected slot first, then the hotbar, then the inventory. The count
/// is cut to one stack of the item (64, 16 or 1).
give: func(stack: stack) -> result<_, string>;
}
/// Capability `ui` (experimental): a recipe viewer's panel beside the
/// game's inventory and container screens (not the creative inventory), on
/// the right of the screen. The game draws it with its own widgets and
/// slots, pages it and keeps its search box; the mod says what it holds.
/// The first loaded mod with a panel shows.
interface browser {
/// An item to show: its id, a count (1 draws none) and its components
/// beyond the item's own, in vanilla's item syntax, or "".
record stack {
item: string,
count: u32,
components: string,
}
/// A click on an item of the panel, by its index in `set-items`'s list.
record click {
index: u32,
right: bool,
}
/// A key the mod registered (`input.register-key`) went down while the
/// pointer was on an item: a slot of the screen's, or the panel's.
record item-key {
key: string,
stack: stack,
}
/// A click on a slot of a recipe the panel shows (`set-recipes`).
record slot-click {
/// The recipe's index in `set-recipes`'s list and the slot's in
/// it; the results come after the slots.
recipe: u32,
slot: u32,
/// The stack the slot showed at that moment.
stack: stack,
right: bool,
}
variant event {
clicked(click),
/// The search box's text, each time the player changes it.
search(string),
key(item-key),
slot-clicked(slot-click),
/// The action button of the recipe at this index in
/// `set-recipes`'s list.
action(u32),
/// The player turned the recipes' page (`set-recipes`): the index
/// of the first recipe now shown.
page(u32),
/// The back button of `set-recipes`.
back,
/// The player picked the tab at this index of `set-recipes`' tabs.
tab(u32),
}
/// How the game lays out a recipe of `set-recipes`.
enum layout {
/// A crafting grid of `width` x `height` slots, an arrow and the
/// result.
grid,
/// One input over a flame, an arrow and the result (furnaces,
/// smokers, campfires).
cooking,
/// One input, an arrow and the result (the stonecutter).
single,
/// Template, base and addition, an arrow and the result.
smithing,
/// A potion and an ingredient, an arrow and the result.
brewing,
}
/// A recipe to show. Each slot, and the result, cycles through its
/// stacks, one a second; an empty slot shows nothing.
record recipe-view {
layout: layout,
/// The grid's size (`grid` only), at most 3 x 3.
width: u32,
height: u32,
slots: list<list<stack>>,
results: list<stack>,
/// A short line under the recipe (a cooking time), or "".
note: string,
/// The action button beside it: none, enabled, or shown greyed.
action: option<bool>,
}
/// The panel's items, at most 8192 (an empty list hides the panel).
set-items: func(items: list<stack>);
/// Shows these recipes in the panel instead of its items, as many as
/// fit a page, under `title` and a back button, with a row of `tabs`
/// (each an icon; `tab` is the selected one) between them; an empty
/// list of recipes shows the items again. At most 256 recipes and 16
/// tabs.
set-recipes: func(title: string, tabs: list<stack>, tab: u32, recipes: list<recipe-view>);
/// What the player did on the panel since the last poll, at most 256
/// kept.
poll: func() -> list<event>;
}
/// Capability `players`, server mods only (manifest `api = "0.3"`, /// Capability `players`, server mods only (manifest `api = "0.3"`,
/// experimental): the players on the server, and messages to them. /// experimental): the players on the server, and messages to them.
interface players { interface players {
@@ -472,6 +647,33 @@ interface players {
broadcast: func(text: string); broadcast: func(text: string);
} }
/// Capability `world`, server mods only (manifest `api = "0.3"`,
/// experimental): the blocks of the server's loaded chunks, and changes to
/// them through the server's own block updates.
interface %world {
record block-change {
x: s32,
y: s32,
z: s32,
/// `minecraft:oak_log[axis=y]`; properties left out take the block's
/// defaults, `minecraft:stone` alone is the default state.
state: string,
}
/// The block state at a position in a dimension (`minecraft:overworld`,
/// ...), as `minecraft:oak_log[axis=y]`, as of this call: none where the
/// server has no chunk loaded there.
get-block: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// The biome at a position (`minecraft:plains`, ...), as the server
/// stores it (one per 4 x 4 x 4 cell): none where no chunk is loaded.
get-biome: func(dimension: string, x: s32, y: s32, z: s32) -> option<string>;
/// Sets blocks as `/setblock` does: the old block entity removed,
/// neighbours and shapes updated, light, and every player told. Every
/// state is checked now (an error queues nothing); the changes are made
/// in order after this call returns, before that dimension's next tick;
/// one in a chunk not loaded then is skipped. At most 4096 per call.
set-blocks: func(dimension: string, blocks: list<block-change>) -> result<_, string>;
}
/// What the server calls in a server mod (manifest `api = "0.3"`, /// What the server calls in a server mod (manifest `api = "0.3"`,
/// experimental). Only the hooks `init` asks for are ever called. The player /// experimental). Only the hooks `init` asks for are ever called. The player
/// in each event is as the server saw them when it happened. /// in each event is as the server saw them when it happened.
@@ -534,6 +736,7 @@ world horizon-server-mod {
import log; import log;
import storage; import storage;
import players; import players;
import %world;
export server-events; export server-events;
} }
@@ -545,6 +748,8 @@ world horizon-ui-mod {
import ui; import ui;
import render; import render;
import input; import input;
import recipes;
import browser;
export ui-events; export ui-events;
} }
@@ -559,3 +764,9 @@ world render-host {
import render; import render;
import input; import input;
} }
/// The game's side of capability `recipes` (imports only).
world recipes-host {
import recipes;
import browser;
}
+13 -2
View File
@@ -7,13 +7,13 @@
//! version's level so the launcher can tell before it installs. //! version's level so the launcher can tell before it installs.
/// The newest level this Horizon serves. /// The newest level this Horizon serves.
pub const LEVEL: u32 = 3; pub const LEVEL: u32 = 6;
/// Every function the game offers mods, as `interface.function`, with its /// Every function the game offers mods, as `interface.function`, with its
/// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new /// level. Level 0 is the contract of Horizon 0.2.67 to 0.2.69. A new
/// function takes the next level and raises [`LEVEL`] (the `api_reference` /// function takes the next level and raises [`LEVEL`] (the `api_reference`
/// test fails until it is listed here). /// test fails until it is listed here).
pub const FUNCTIONS: [(&str, u32); 34] = [ pub const FUNCTIONS: [(&str, u32); 45] = [
("log.write", 0), ("log.write", 0),
("game.get-player", 0), ("game.get-player", 0),
("game.get-clock", 0), ("game.get-clock", 0),
@@ -48,6 +48,17 @@ pub const FUNCTIONS: [(&str, u32); 34] = [
("players.broadcast", 1), ("players.broadcast", 1),
("game.raycast", 2), ("game.raycast", 2),
("command.run-quiet", 3), ("command.run-quiet", 3),
("world.get-block", 4),
("world.get-biome", 4),
("world.set-blocks", 4),
("recipes.items", 5),
("recipes.all", 5),
("recipes.known", 5),
("browser.set-items", 6),
("browser.poll", 6),
("browser.set-recipes", 6),
("recipes.place", 6),
("recipes.give", 6),
]; ];
/// What the game's program carries so the launcher can read its level /// What the game's program carries so the launcher can read its level
+26 -3
View File
@@ -97,9 +97,15 @@ pub enum Capability {
Input, Input,
/// The players on the server and messages to them (server mods). /// The players on the server and messages to them (server mods).
Players, Players,
/// Blocks in the server's loaded chunks, and changes to them (server
/// mods; client mods later, where the game runs the world).
World,
/// The recipes and items the game knows, for recipe viewers
/// (interface `recipes`).
Recipes,
} }
impl Capability { impl Capability {
pub const ALL: [Capability; 10] = [ pub const ALL: [Capability; 12] = [
Capability::GameRead, Capability::GameRead,
Capability::Chat, Capability::Chat,
Capability::Hud, Capability::Hud,
@@ -110,10 +116,15 @@ impl Capability {
Capability::Render, Capability::Render,
Capability::Input, Capability::Input,
Capability::Players, Capability::Players,
Capability::World,
Capability::Recipes,
]; ];
/// Whether a server mod may have it: the others act on a local player. /// Whether a server mod may have it: the others act on a local player.
pub fn on_server(self) -> bool { pub fn on_server(self) -> bool {
matches!(self, Capability::Storage | Capability::Players) matches!(
self,
Capability::Storage | Capability::Players | Capability::World
)
} }
/// The WIT interface it grants, in `horizon:mods`. /// The WIT interface it grants, in `horizon:mods`.
pub fn interface(self) -> &'static str { pub fn interface(self) -> &'static str {
@@ -128,6 +139,8 @@ impl Capability {
Capability::Render => "render", Capability::Render => "render",
Capability::Input => "input", Capability::Input => "input",
Capability::Players => "players", Capability::Players => "players",
Capability::World => "world",
Capability::Recipes => "recipes",
} }
} }
/// May change in any release: a mod uses it only with /// May change in any release: a mod uses it only with
@@ -135,7 +148,7 @@ impl Capability {
pub fn is_experimental(self) -> bool { pub fn is_experimental(self) -> bool {
matches!( matches!(
self, self,
Capability::Ui | Capability::Render | Capability::Input Capability::Ui | Capability::Render | Capability::Input | Capability::Recipes
) )
} }
/// What the player reads before turning the mod on: "May <this>". /// What the player reads before turning the mod on: "May <this>".
@@ -153,6 +166,10 @@ impl Capability {
"see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys" "see the keys you hold and your clicks, take over the use button on its own items and the mouse wheel, and add keys"
} }
Capability::Players => "see who is on the server and message them", Capability::Players => "see who is on the server and message them",
Capability::World => "read and change the world's blocks",
Capability::Recipes => {
"read the game's recipes and items and which recipes you know, place recipes in your crafting grid and, in creative mode, give you items"
}
} }
} }
/// The capability a component import needs, `Ok(None)` for one every /// The capability a component import needs, `Ok(None)` for one every
@@ -167,6 +184,10 @@ impl Capability {
if interface == "log" { if interface == "log" {
return Ok(None); return Ok(None);
} }
// A recipe viewer's panel is part of capability `ui`.
if interface == "browser" {
return Ok(Some(Capability::Ui));
}
Capability::ALL Capability::ALL
.into_iter() .into_iter()
.filter(|c| *c != Capability::Registries) .filter(|c| *c != Capability::Registries)
@@ -188,6 +209,8 @@ impl fmt::Display for Capability {
Capability::Render => "render", Capability::Render => "render",
Capability::Input => "input", Capability::Input => "input",
Capability::Players => "players", Capability::Players => "players",
Capability::World => "world",
Capability::Recipes => "recipes",
}; };
f.write_str(name) f.write_str(name)
} }
+361 -4
View File
@@ -1,12 +1,13 @@
//! Loading and calling mods with wasmtime's component model. //! Loading and calling mods with wasmtime's component model.
use crate::manifest::{Manifest, Package, Side}; use crate::manifest::{Manifest, Package, Side};
use server_bindings::{ use server_bindings::{
HorizonServerMod, exports::horizon::mods::server_events::Registration as ServerRegistration, HorizonServerMod,
horizon::mods::players, exports::horizon::mods::server_events::Registration as ServerRegistration,
horizon::mods::{players, world as mod_world},
}; };
use std::{ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
sync::Arc, sync::{Arc, Mutex},
time::{Duration, Instant, SystemTime}, time::{Duration, Instant, SystemTime},
}; };
use wasmtime::{ use wasmtime::{
@@ -25,6 +26,7 @@ mod server_bindings {
wasmtime::component::bindgen!({ wasmtime::component::bindgen!({
path: "../horizon-mod-sdk/wit", path: "../horizon-mod-sdk/wit",
world: "horizon-server-mod", world: "horizon-server-mod",
additional_derives: [PartialEq],
with: { with: {
"horizon:mods/log": super::bindings::horizon::mods::log, "horizon:mods/log": super::bindings::horizon::mods::log,
"horizon:mods/storage": super::bindings::horizon::mods::storage, "horizon:mods/storage": super::bindings::horizon::mods::storage,
@@ -52,6 +54,7 @@ use bindings::{
pub use server_bindings::{ pub use server_bindings::{
exports::horizon::mods::server_events::BlockPos, exports::horizon::mods::server_events::BlockPos,
horizon::mods::players::{GameMode, Player as ServerPlayer}, horizon::mods::players::{GameMode, Player as ServerPlayer},
horizon::mods::world::BlockChange,
}; };
type ClientEvents = bindings::exports::horizon::mods::events::Guest; type ClientEvents = bindings::exports::horizon::mods::events::Guest;
type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest; type ServerEvents = server_bindings::exports::horizon::mods::server_events::Guest;
@@ -78,6 +81,24 @@ pub use render_bindings::horizon::mods::render::{
Zoom as ModZoom, Zoom as ModZoom,
}; };
use render_bindings::{RenderHost, horizon::mods::render}; use render_bindings::{RenderHost, horizon::mods::render};
/// Capability `recipes`'s imports (docs/mods.md): the game's recipes and items.
mod recipes_bindings {
wasmtime::component::bindgen!({
path: "../horizon-mod-sdk/wit",
world: "recipes-host",
});
}
/// Capability `ui`'s recipe viewer panel (WIT `interface browser`).
pub use recipes_bindings::horizon::mods::browser::{
Click as BrowserClick, Event as BrowserEvent, ItemKey as BrowserItemKey,
Layout as BrowserLayout, RecipeView as BrowserRecipe, SlotClick as BrowserSlotClick,
Stack as BrowserStack,
};
/// What capability `recipes` reads (WIT `interface recipes`).
pub use recipes_bindings::horizon::mods::recipes::{
Item as RecipeItem, Kind as RecipeKind, Recipe, Stack as RecipeStack,
};
use recipes_bindings::{RecipesHost, horizon::mods::browser, horizon::mods::recipes};
/// A mod's linear memory cap. /// A mod's linear memory cap.
const MEMORY: usize = 64 << 20; const MEMORY: usize = 64 << 20;
@@ -87,6 +108,8 @@ const FUEL_INIT: u64 = 2_000_000_000;
const FUEL_TICK: u64 = 50_000_000; const FUEL_TICK: u64 = 50_000_000;
const FUEL_FRAME: u64 = 10_000_000; const FUEL_FRAME: u64 = 10_000_000;
const FUEL_EVENT: u64 = 100_000_000; const FUEL_EVENT: u64 = 100_000_000;
/// Blocks a mod may set per `world.set-blocks` call.
pub const BLOCKS_PER_CALL: usize = 4096;
/// Chat lines a mod may show per call, HUD lines and their length. /// Chat lines a mod may show per call, HUD lines and their length.
const CHAT_PER_CALL: usize = 8; const CHAT_PER_CALL: usize = 8;
/// `command.run-quiet` lines one call of a mod may queue (a quiet payload's /// `command.run-quiet` lines one call of a mod may queue (a quiet payload's
@@ -133,6 +156,23 @@ pub struct Snapshot {
/// its distance from the eye, for `game.raycast`; the game works it out /// its distance from the eye, for `game.raycast`; the game works it out
/// only while a mod calls it ([`Mods::wants_raycast`]). /// only while a mod calls it ([`Mods::wants_raycast`]).
pub view_hit: Option<(f32, Hit)>, pub view_hit: Option<(f32, Hit)>,
/// Every item and recipe, for capability `recipes`; the game makes them
/// once, and only while a mod reads them ([`Mods::wants_recipes`]).
pub recipes: Option<Arc<Recipes>>,
/// The `book-id`s of the recipes the player's book holds.
pub known_recipes: Arc<[i32]>,
/// The open screen takes recipes (`recipes.place`).
pub placing: bool,
/// The player is in creative mode (`recipes.give`).
pub creative: bool,
}
/// Capability `recipes`'s tables: `items` in the registry's order, which
/// each [`RecipeStack::item`] indexes.
#[derive(Clone, Debug, Default)]
pub struct Recipes {
pub items: Vec<RecipeItem>,
pub recipes: Vec<Recipe>,
} }
/// Which mods a game starts: the window's game the client mods, the game /// Which mods a game starts: the window's game the client mods, the game
@@ -182,6 +222,13 @@ pub enum Output {
text: String, text: String,
error: bool, error: bool,
}, },
/// `world.set-blocks`: changes to make in `dimension`, in order, each
/// state checked by the [`WorldView`] lent for the call.
SetBlocks {
name: String,
dimension: String,
blocks: Vec<BlockChange>,
},
/// `ui.open-screen`: the mod's entry in `entries()`; what it shows is /// `ui.open-screen`: the mod's entry in `entries()`; what it shows is
/// [`Mods::screen`]. /// [`Mods::screen`].
OpenScreen { owner: usize }, OpenScreen { owner: usize },
@@ -189,8 +236,34 @@ pub enum Output {
CloseScreen { owner: usize }, CloseScreen { owner: usize },
/// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10). /// `render.shake`: strength 0 to 1, fading out over `seconds` (≤ 10).
Shake { strength: f32, seconds: f32 }, Shake { strength: f32, seconds: f32 },
/// `recipes.place`: the recipe book's click on this display id, all of
/// it when `all`.
PlaceRecipe { book_id: i32, all: bool },
/// `recipes.give`: a stack for a creative player.
Give {
item: String,
count: u32,
components: String,
},
} }
/// The game's world as capability `world` reads it during a call: the
/// game lends one with [`Mods::lend_world`] and takes it back after.
pub trait WorldView: std::any::Any + Send {
/// The block state at a position, `minecraft:oak_log[axis=y]`; `None`
/// where no chunk of that dimension is loaded.
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// The biome at a position, `minecraft:plains`; `None` as for blocks.
fn biome(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String>;
/// Whether `dimension` is one the server has.
fn has_dimension(&self, dimension: &str) -> bool;
/// `Err` (why) for a state string that names no block state.
fn check_state(&self, state: &str) -> Result<(), String>;
}
/// The view lent for the current calls, shared by every mod's store.
type WorldSlot = Arc<Mutex<Option<Box<dyn WorldView>>>>;
/// A mod's text panel, drawn every frame until it changes. /// A mod's text panel, drawn every frame until it changes.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct Panel { pub struct Panel {
@@ -241,6 +314,8 @@ struct Running {
hooks: Hooks, hooks: Hooks,
/// It imports `game.raycast`. /// It imports `game.raycast`.
raycasts: bool, raycasts: bool,
/// It imports capability `recipes`.
reads_recipes: bool,
} }
/// A running mod's exports and the hooks its `init` asked for. /// A running mod's exports and the hooks its `init` asked for.
@@ -282,6 +357,46 @@ struct UiState {
close: bool, close: bool,
} }
/// Capability `ui`'s panel beside container screens (`browser`).
#[derive(Default)]
struct BrowserState {
items: Vec<BrowserStack>,
/// Which `set-items` or `set-recipes` call the panel is from, unique
/// across mods and reloads, so the game converts them once.
version: u64,
/// `set-recipes`' title and recipes, shown instead of the items.
recipes: Option<RecipePage>,
events: std::collections::VecDeque<BrowserEvent>,
}
/// What `browser.set-recipes` shows: a title, tabs (`tab` the selected
/// one) and the recipes.
#[derive(Clone, Debug)]
pub struct RecipePage {
pub title: String,
pub tabs: Vec<BrowserStack>,
pub tab: u32,
pub recipes: Vec<BrowserRecipe>,
}
static BROWSER_VERSION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
/// Items a panel may hold, and events kept for `browser.poll`.
const BROWSER_ITEMS: usize = 8192;
/// `recipes.place` and `give` calls a hook call may make.
const RECIPE_ACTIONS: usize = 36;
/// Recipes `set-recipes` may show, slots in one, and stacks a slot cycles.
const BROWSER_RECIPES: usize = 256;
const RECIPE_SLOTS: usize = 9;
const RECIPE_TABS: usize = 16;
const SLOT_STACKS: usize = 64;
const BROWSER_EVENTS: usize = 256;
impl BrowserState {
fn push(&mut self, event: BrowserEvent) {
if self.events.len() == BROWSER_EVENTS {
self.events.pop_front();
}
self.events.push_back(event);
}
}
struct State { struct State {
name: String, name: String,
id: String, id: String,
@@ -298,6 +413,7 @@ struct State {
/// Capability `render`'s minimap, when the mod shows one. /// Capability `render`'s minimap, when the mod shows one.
minimap: Option<ModMinimap>, minimap: Option<ModMinimap>,
input: InputState, input: InputState,
browser: BrowserState,
/// Capability `storage`'s folder; made on first `set`. /// Capability `storage`'s folder; made on first `set`.
data_dir: PathBuf, data_dir: PathBuf,
/// Bytes `storage::set` may still write before this hook call ends /// Bytes `storage::set` may still write before this hook call ends
@@ -306,6 +422,7 @@ struct State {
/// needs its own budget. /// needs its own budget.
storage_budget: u64, storage_budget: u64,
limits: StoreLimits, limits: StoreLimits,
world: WorldSlot,
} }
/// The installed mods and the engine running them. `Mods::default()` is /// The installed mods and the engine running them. `Mods::default()` is
@@ -316,9 +433,33 @@ pub struct Mods {
entries: Vec<Entry>, entries: Vec<Entry>,
snapshot: Arc<Snapshot>, snapshot: Arc<Snapshot>,
out: Vec<Output>, out: Vec<Output>,
world: WorldSlot,
} }
impl Mods { impl Mods {
/// Whether a running mod may use capability `world`: only then is a
/// view worth lending.
pub fn wants_world(&self) -> bool {
self.entries.iter().any(|e| {
e.status == Status::Running
&& e.manifest
.as_ref()
.is_some_and(|m| m.capabilities.contains(&crate::Capability::World))
})
}
/// Lends the game's world to capability `world` for the calls until
/// [`Mods::take_world`]; with none lent, `get-block` finds nothing and
/// `set-blocks` checks only its count.
pub fn lend_world(&mut self, view: Box<dyn WorldView>) {
if let Ok(mut slot) = self.world.lock() {
*slot = Some(view);
}
}
/// The view [`Mods::lend_world`] lent, back to the game.
pub fn take_world(&mut self) -> Option<Box<dyn WorldView>> {
self.world.lock().ok()?.take()
}
/// Reads every mod at `paths` and starts those `enabled` says are on, /// Reads every mod at `paths` and starts those `enabled` says are on,
/// client and server mods alike. A command that `reserved` (vanilla's /// client and server mods alike. A command that `reserved` (vanilla's
/// commands) or an earlier mod already uses is refused. /// commands) or an earlier mod already uses is refused.
@@ -388,10 +529,14 @@ impl Mods {
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s) players::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
mod_world::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s) UiHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s) RenderHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?; .map_err(|e| e.to_string())?;
RecipesHost::add_to_linker::<State, HasSelf<State>>(&mut linker, |s| s)
.map_err(|e| e.to_string())?;
self.engine = Some((engine, linker)); self.engine = Some((engine, linker));
} }
Ok(self.engine.as_ref().expect("made above")) Ok(self.engine.as_ref().expect("made above"))
@@ -429,6 +574,7 @@ impl Mods {
.flat_map(|r| r.hooks.commands().iter().cloned()) .flat_map(|r| r.hooks.commands().iter().cloned())
.collect(); .collect();
let snapshot = self.snapshot.clone(); let snapshot = self.snapshot.clone();
let world = self.world.clone();
let (engine, linker) = self.engine()?; let (engine, linker) = self.engine()?;
let component = let component =
Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?; Component::new(engine, wasm).map_err(|e| format!("not a component: {e}"))?;
@@ -461,12 +607,14 @@ impl Mods {
zoom: None, zoom: None,
minimap: None, minimap: None,
input: InputState::default(), input: InputState::default(),
browser: BrowserState::default(),
data_dir, data_dir,
storage_budget: STORAGE_WRITE_BUDGET, storage_budget: STORAGE_WRITE_BUDGET,
limits: StoreLimitsBuilder::new() limits: StoreLimitsBuilder::new()
.memory_size(MEMORY) .memory_size(MEMORY)
.instances(16) .instances(16)
.build(), .build(),
world,
}; };
let mut store = Store::new(engine, state); let mut store = Store::new(engine, state);
store.limiter(|s| &mut s.limits); store.limiter(|s| &mut s.limits);
@@ -509,6 +657,7 @@ impl Mods {
ui, ui,
hooks, hooks,
raycasts: functions.iter().any(|f| f == "game.raycast"), raycasts: functions.iter().any(|f| f == "game.raycast"),
reads_recipes: functions.iter().any(|f| f.starts_with("recipes.")),
})) }))
} }
@@ -769,6 +918,58 @@ impl Mods {
.iter() .iter()
.any(|e| e.run.as_ref().is_some_and(|r| r.raycasts)) .any(|e| e.run.as_ref().is_some_and(|r| r.raycasts))
} }
/// The panel beside container screens (`browser.set-items`): the first
/// running mod with items or recipes, its index, the panel's version and
/// the items.
pub fn browser_items(&self) -> Option<(usize, u64, &[BrowserStack])> {
self.entries.iter().enumerate().find_map(|(i, e)| {
let b = &e.run.as_ref()?.store.data().browser;
(!b.items.is_empty() || b.recipes.is_some()).then_some((
i,
b.version,
b.items.as_slice(),
))
})
}
/// What mod `owner`'s panel shows instead of its items
/// (`browser.set-recipes`).
pub fn browser_recipes(&self, owner: usize) -> Option<&RecipePage> {
let b = &self.entries.get(owner)?.run.as_ref()?.store.data().browser;
b.recipes.as_ref()
}
/// The player did `event` on mod `owner`'s panel.
pub fn browser_event(&mut self, owner: usize, event: BrowserEvent) {
if let Some(run) = self.entries.get_mut(owner).and_then(|e| e.run.as_mut()) {
run.store.data_mut().browser.push(event);
}
}
/// The key `key` went down with the pointer on `stack` in a container
/// screen: each mod with a key on it hears its own name for it.
pub fn browser_key(&mut self, key: &str, stack: &BrowserStack) {
for run in self.entries.iter_mut().filter_map(|e| e.run.as_mut()) {
let data = run.store.data_mut();
let names: Vec<String> = data
.input
.keys
.iter()
.filter(|k| k.key == key)
.map(|k| k.name.clone())
.collect();
for key in names {
data.browser.push(BrowserEvent::Key(BrowserItemKey {
key,
stack: stack.clone(),
}));
}
}
}
/// Some running mod reads capability `recipes`: the snapshot needs
/// [`Snapshot::recipes`] and [`Snapshot::known_recipes`].
pub fn wants_recipes(&self) -> bool {
self.entries
.iter()
.any(|e| e.run.as_ref().is_some_and(|r| r.reads_recipes))
}
/// Some running mod has a `frame` hook: the game refreshes the snapshot /// Some running mod has a `frame` hook: the game refreshes the snapshot
/// every frame for it. /// every frame for it.
pub fn wants_frames(&self) -> bool { pub fn wants_frames(&self) -> bool {
@@ -1064,7 +1265,10 @@ fn reason(e: &wasmtime::Error) -> String {
} }
fn clip(text: String) -> String { fn clip(text: String) -> String {
match text.char_indices().nth(LINE_CHARS) { clip_to(text, LINE_CHARS)
}
fn clip_to(text: String, chars: usize) -> String {
match text.char_indices().nth(chars) {
Some((at, _)) => text[..at].to_string(), Some((at, _)) => text[..at].to_string(),
None => text, None => text,
} }
@@ -1125,6 +1329,125 @@ impl game::Host for State {
(*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone()) (*at <= distance.min(RAYCAST_MAX) && !distance.is_nan()).then(|| hit.clone())
} }
} }
impl browser::Host for State {
fn set_items(&mut self, items: Vec<BrowserStack>) {
self.browser.items = items
.into_iter()
.take(BROWSER_ITEMS)
.map(|s| BrowserStack {
item: clip(s.item),
components: clip_to(s.components, 4096),
..s
})
.collect();
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn set_recipes(
&mut self,
title: String,
tabs: Vec<BrowserStack>,
tab: u32,
recipes: Vec<BrowserRecipe>,
) {
let stack = |s: BrowserStack| BrowserStack {
item: clip(s.item),
components: clip_to(s.components, 4096),
..s
};
let cycle = |list: Vec<BrowserStack>| -> Vec<BrowserStack> {
list.into_iter().take(SLOT_STACKS).map(stack).collect()
};
self.browser.recipes = (!recipes.is_empty()).then(|| {
let recipes = recipes
.into_iter()
.take(BROWSER_RECIPES)
.map(|r| BrowserRecipe {
width: r.width.clamp(1, 3),
height: r.height.clamp(1, 3),
slots: r.slots.into_iter().take(RECIPE_SLOTS).map(cycle).collect(),
results: cycle(r.results),
note: clip(r.note),
..r
})
.collect();
RecipePage {
title: clip(title),
tabs: tabs.into_iter().take(RECIPE_TABS).map(stack).collect(),
tab,
recipes,
}
});
self.browser.version = BROWSER_VERSION.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
}
fn poll(&mut self) -> Vec<BrowserEvent> {
self.browser.events.drain(..).collect()
}
}
impl recipes::Host for State {
fn items(&mut self) -> Vec<RecipeItem> {
self.snapshot
.recipes
.as_ref()
.map_or_else(Vec::new, |r| r.items.clone())
}
fn all(&mut self) -> Vec<Recipe> {
self.snapshot
.recipes
.as_ref()
.map_or_else(Vec::new, |r| r.recipes.clone())
}
fn known(&mut self) -> Vec<i32> {
self.snapshot.known_recipes.to_vec()
}
fn place(&mut self, book_id: i32, all: bool) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.placing {
return Err("no screen that takes recipes is open".into());
}
if !self.snapshot.known_recipes.contains(&book_id) {
return Err(format!(
"recipe {book_id} is not in the player's recipe book"
));
}
self.out.push(Output::PlaceRecipe { book_id, all });
Ok(())
}
fn give(&mut self, stack: RecipeStack) -> Result<(), String> {
self.recipe_action()?;
if !self.snapshot.creative {
return Err("only in creative mode".into());
}
let item = self
.snapshot
.recipes
.as_ref()
.and_then(|r| r.items.get(stack.item as usize))
.ok_or_else(|| format!("no item {}", stack.item))?
.id
.clone();
self.out.push(Output::Give {
item,
count: stack.count.clamp(1, 99),
components: clip_to(stack.components, 4096),
});
Ok(())
}
}
impl State {
/// `recipes.place` and `give` take at most [`RECIPE_ACTIONS`] a call.
fn recipe_action(&self) -> Result<(), String> {
let done = self
.out
.iter()
.filter(|o| matches!(o, Output::PlaceRecipe { .. } | Output::Give { .. }))
.count();
if done < RECIPE_ACTIONS {
Ok(())
} else {
Err(format!("at most {RECIPE_ACTIONS} places and gives a call"))
}
}
}
impl State { impl State {
/// Queues a chat line unless the call already sent [`CHAT_PER_CALL`]. /// Queues a chat line unless the call already sent [`CHAT_PER_CALL`].
fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool { fn say(&mut self, line: impl FnOnce(String) -> Output) -> bool {
@@ -1153,6 +1476,40 @@ impl chat::Host for State {
}); });
} }
} }
impl mod_world::Host for State {
fn get_block(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.block(&dimension, x, y, z)
}
fn get_biome(&mut self, dimension: String, x: i32, y: i32, z: i32) -> Option<String> {
let view = self.world.lock().ok()?;
view.as_ref()?.biome(&dimension, x, y, z)
}
fn set_blocks(&mut self, dimension: String, blocks: Vec<BlockChange>) -> Result<(), String> {
if blocks.len() > BLOCKS_PER_CALL {
return Err(format!(
"{} blocks: at most {BLOCKS_PER_CALL} per call",
blocks.len()
));
}
if let Some(view) = self.world.lock().ok().as_ref().and_then(|v| v.as_ref()) {
if !view.has_dimension(&dimension) {
return Err(format!("no dimension {dimension}"));
}
for b in &blocks {
view.check_state(&b.state)?;
}
}
if !blocks.is_empty() {
self.out.push(Output::SetBlocks {
name: self.name.clone(),
dimension,
blocks,
});
}
Ok(())
}
}
impl players::Host for State { impl players::Host for State {
fn online(&mut self) -> Vec<ServerPlayer> { fn online(&mut self) -> Vec<ServerPlayer> {
self.snapshot.players.clone() self.snapshot.players.clone()
+89 -3
View File
@@ -29,6 +29,54 @@ pub struct TestGame {
/// Every name that joined, for their id. /// Every name that joined, for their id.
names: Vec<String>, names: Vec<String>,
tick: u64, tick: u64,
/// Capability `world`'s Overworld: the blocks a script set or the mod
/// changed; every other block, and the other dimensions, are air. Every
/// biome is the dimension's plainest: plains, nether wastes, the end.
pub world: std::collections::BTreeMap<(i32, i32, i32), String>,
}
/// The world a script's mod reads: [`TestGame::world`], copied for a step.
struct ScriptWorld(std::collections::BTreeMap<(i32, i32, i32), String>);
impl crate::WorldView for ScriptWorld {
fn block(&self, dimension: &str, x: i32, y: i32, z: i32) -> Option<String> {
let here = (dimension == "minecraft:overworld")
.then(|| self.0.get(&(x, y, z)).cloned())
.flatten();
Some(here.unwrap_or_else(|| "minecraft:air".into()))
}
fn biome(&self, dimension: &str, _x: i32, _y: i32, _z: i32) -> Option<String> {
let biome = match dimension {
"minecraft:overworld" => "minecraft:plains",
"minecraft:the_nether" => "minecraft:nether_wastes",
"minecraft:the_end" => "minecraft:the_end",
_ => return None,
};
Some(biome.into())
}
fn has_dimension(&self, dimension: &str) -> bool {
matches!(
dimension,
"minecraft:overworld" | "minecraft:the_nether" | "minecraft:the_end"
)
}
fn check_state(&self, state: &str) -> Result<(), String> {
// No registry here: the shape only (the game checks the names).
let name = state.split('[').next().unwrap_or_default();
let plain = |t: &str| {
!t.is_empty()
&& t.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"_.-/".contains(&b))
};
let ok = match name.split_once(':') {
Some((ns, path)) => plain(ns) && plain(path),
None => plain(name),
};
let closed = !state.contains('[') || state.ends_with(']');
(ok && closed)
.then_some(())
.ok_or_else(|| format!("{state} is not a block state"))
}
} }
/// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing /// Where a script starts: standing at 0.5 64 0.5 in the Overworld, facing
@@ -71,6 +119,7 @@ impl TestGame {
players: Vec::new(), players: Vec::new(),
names: Vec::new(), names: Vec::new(),
tick: 0, tick: 0,
world: Default::default(),
}; };
copy_mod(hmod, &copy)?; copy_mod(hmod, &copy)?;
game.start()?; game.start()?;
@@ -312,9 +361,10 @@ pub struct ClockSet {
} }
/// One step. Its parts happen in this order: `reload`, `title-screen`, /// One step. Its parts happen in this order: `reload`, `title-screen`,
/// `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`, `break`, /// `blocks`, `join`, `player`, `clock`, `ticks`, `frames`, `chat`, `command`,
/// `place`, `leave`; then `expect` is checked against what the mod showed /// `break`, `place`, `leave`; then the blocks the mod set are made, and
/// during the step. For a server mod, `player`, `chat`, `command`, `break` /// `expect` is checked against what the mod showed and changed during the
/// step. For a server mod, `player`, `chat`, `command`, `break`
/// and `place` are the doing of the player named by `as`, or of the first /// and `place` are the doing of the player named by `as`, or of the first
/// player on. /// player on.
#[derive(Debug, Default, Deserialize)] #[derive(Debug, Default, Deserialize)]
@@ -341,6 +391,10 @@ pub struct Step {
#[serde(rename = "break")] #[serde(rename = "break")]
broken: Option<BlockSet>, broken: Option<BlockSet>,
place: Option<BlockSet>, place: Option<BlockSet>,
/// Blocks of the Overworld before the rest of the step (capability
/// `world`); every other block is air.
#[serde(default)]
blocks: Vec<BlockSet>,
#[serde(default)] #[serde(default)]
expect: Expect, expect: Expect,
} }
@@ -363,6 +417,9 @@ pub struct Expect {
/// The panel's lines (`[]`: no panel) and its corner. /// The panel's lines (`[]`: no panel) and its corner.
panel: Option<Vec<String>>, panel: Option<Vec<String>>,
corner: Option<String>, corner: Option<String>,
/// Blocks of the Overworld after the step, the mod's changes made
/// (capability `world`).
blocks: Option<Vec<BlockSet>>,
/// The mod is turned off during this step, for a reason holding this text. /// The mod is turned off during this step, for a reason holding this text.
/// Without it, a mod that stops fails the test. /// Without it, a mod that stops fails the test.
stopped: Option<String>, stopped: Option<String>,
@@ -467,6 +524,11 @@ impl Step {
game.player = None; game.player = None;
game.clock = None; game.clock = None;
} }
for b in &self.blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
game.mods
.lend_world(Box::new(ScriptWorld(game.world.clone())));
if let Some(name) = &self.join { if let Some(name) = &self.join {
game.join(name); game.join(name);
} }
@@ -531,7 +593,19 @@ impl Step {
{ {
return Err(format!("{name} is not on the server")); return Err(format!("{name} is not on the server"));
} }
game.mods.take_world();
let out = game.drain(); let out = game.drain();
for o in &out {
if let Output::SetBlocks {
dimension, blocks, ..
} = o
&& dimension == "minecraft:overworld"
{
for b in blocks {
game.world.insert((b.x, b.y, b.z), b.state.clone());
}
}
}
let stopped = out.iter().find_map(|o| match o { let stopped = out.iter().find_map(|o| match o {
Output::Stopped { reason, .. } => Some(reason.as_str()), Output::Stopped { reason, .. } => Some(reason.as_str()),
_ => None, _ => None,
@@ -615,6 +689,18 @@ impl Step {
.unwrap_or_default(); .unwrap_or_default();
same("panel", want, &got)?; same("panel", want, &got)?;
} }
if let Some(want) = &e.blocks {
for b in want {
let got = game.world.get(&(b.x, b.y, b.z));
let got = got.map_or("minecraft:air", String::as_str);
if got != b.state {
return Err(format!(
"block at {} {} {}: expected {}, got {got}",
b.x, b.y, b.z, b.state
));
}
}
}
if let Some(want) = &e.corner { if let Some(want) = &e.corner {
let got = game.panel().map(|p| corner_name(p.corner).to_string()); let got = game.panel().map(|p| corner_name(p.corner).to_string());
same("corner", &Some(want.clone()), &got)?; same("corner", &Some(want.clone()), &got)?;
+278 -9
View File
@@ -26,8 +26,8 @@ id = "test_ui_guest"
name = "Test UI Guest" name = "Test UI Guest"
version = "0.1.0" version = "0.1.0"
api = "0.1" api = "0.1"
capabilities = ["game-read", "chat", "command", "ui", "render", "input"] capabilities = ["game-read", "chat", "command", "ui", "render", "input", "recipes"]
experimental = ["ui", "render", "input"] experimental = ["ui", "render", "input", "recipes"]
"#; "#;
/// Builds the mods once and writes their `.hmod` files; returns the folder. /// Builds the mods once and writes their `.hmod` files; returns the folder.
@@ -47,6 +47,8 @@ fn mods_dir() -> &'static Path {
"-p", "-p",
"welcome", "welcome",
"-p", "-p",
"beacons",
"-p",
"horizon-mods-test-guest", "horizon-mods-test-guest",
"-p", "-p",
"horizon-mods-test-ui-guest", "horizon-mods-test-ui-guest",
@@ -70,6 +72,7 @@ fn mods_dir() -> &'static Path {
("coords_hud", example("coords-hud")), ("coords_hud", example("coords-hud")),
("predator_missile", example("predator-missile")), ("predator_missile", example("predator-missile")),
("welcome", example("welcome")), ("welcome", example("welcome")),
("beacons", example("beacons")),
("horizon_mods_test_guest", GUEST_MANIFEST.to_string()), ("horizon_mods_test_guest", GUEST_MANIFEST.to_string()),
("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()), ("horizon_mods_test_ui_guest", UI_MANIFEST.to_string()),
]; ];
@@ -202,7 +205,7 @@ fn undeclared_capabilities_are_refused() {
/// from the functions they import. /// from the functions they import.
#[test] #[test]
fn a_mod_for_a_newer_horizon_is_refused() { fn a_mod_for_a_newer_horizon_is_refused() {
use horizon_mods::api_level::{LEVEL, imports, needed}; use horizon_mods::api_level::{imports, needed};
use wit_parser::{ManglingAndAbi, Resolve}; use wit_parser::{ManglingAndAbi, Resolve};
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit")) let wit = std::fs::read_to_string(root.join("crates/horizon-mod-sdk/wit/horizon.wit"))
@@ -238,8 +241,8 @@ id = "too_new"
name = "Too New" name = "Too New"
version = "0.1.0" version = "0.1.0"
api = "0.1" api = "0.1"
capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input"] capabilities = ["game-read", "chat", "hud", "storage", "command", "ui", "render", "input", "recipes"]
experimental = ["ui", "render", "input"] experimental = ["ui", "render", "input", "recipes"]
"#; "#;
std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap(); std::fs::write(dir.join("horizon-mod.toml"), manifest).unwrap();
std::fs::write(dir.join("mod.wasm"), wasm).unwrap(); std::fs::write(dir.join("mod.wasm"), wasm).unwrap();
@@ -252,8 +255,8 @@ experimental = ["ui", "render", "input"]
needed(imports(&wasm).unwrap().iter().map(String::as_str)).0 needed(imports(&wasm).unwrap().iter().map(String::as_str)).0
}; };
assert_eq!(level("coords_hud.hmod"), 0); assert_eq!(level("coords_hud.hmod"), 0);
// The UI guest shows a minimap (`render.set-minimap`). // The UI guest fills a browser panel (`browser`, level 6).
assert_eq!(level("horizon_mods_test_ui_guest.hmod"), LEVEL); assert_eq!(level("horizon_mods_test_ui_guest.hmod"), 6);
} }
#[test] #[test]
@@ -866,7 +869,12 @@ capabilities = ["registries"]
fn the_examples_test_scripts_pass() { fn the_examples_test_scripts_pass() {
let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples"); let examples = Path::new(env!("CARGO_MANIFEST_DIR")).join("../horizon-mod-sdk/examples");
let mut ran = 0; let mut ran = 0;
for (example, hmod) in [("coords-hud", "coords_hud"), ("welcome", "welcome")] { let examples_and_files = [
("coords-hud", "coords_hud"),
("welcome", "welcome"),
("beacons", "beacons"),
];
for (example, hmod) in examples_and_files {
for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() { for entry in std::fs::read_dir(examples.join(example).join("tests")).unwrap() {
let path = entry.unwrap().path(); let path = entry.unwrap().path();
let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap(); let script = Script::parse(&std::fs::read_to_string(&path).unwrap()).unwrap();
@@ -877,7 +885,24 @@ fn the_examples_test_scripts_pass() {
ran += 1; ran += 1;
} }
} }
assert_eq!(ran, 4); assert_eq!(ran, 5);
}
/// Capability `world` without a world lent (the registry's trial run):
/// `get-block` finds nothing, `set-blocks` checks its count and queues.
#[test]
fn a_server_mod_without_a_world_reads_nothing() {
let mut game = TestGame::load(&mods_dir().join("beacons.hmod")).unwrap();
game.join("Alex");
let alex = game.players[0].clone();
assert!(game.player_command(&alex, "ground"));
let out = game.drain();
assert!(
out.iter()
.any(|o| matches!(o, Output::Reply { text, error: true, .. }
if text == "The ground under you isn't loaded")),
"{out:?}"
);
} }
#[test] #[test]
@@ -1016,3 +1041,247 @@ fn a_server_mod_runs_only_where_the_world_does() {
"a server command isn't the window's" "a server command isn't the window's"
); );
} }
/// Capability `recipes`: the guest reads tables as big as vanilla's (1,500
/// items, 1,600 recipes of nine five-item slots) within one command's fuel.
#[test]
fn recipes_reads_the_tables() {
use horizon_mods::{Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
let mut mods = load("horizon_mods_test_ui_guest.hmod");
let stack = |item| RecipeStack {
item,
count: 1,
components: String::new(),
};
let items = (0..1500)
.map(|i| RecipeItem {
id: format!("minecraft:item_{i}"),
name: format!("Item {i}"),
tags: vec!["planks".into(), "logs".into()],
})
.collect();
let mut recipes: Vec<Recipe> = (0..1600)
.map(|i| Recipe {
id: format!("minecraft:recipe_{i}"),
kind: RecipeKind::CraftingShaped,
category: "crafting_misc".into(),
group: String::new(),
width: 3,
height: 3,
slots: (0..9)
.map(|k| (0..5).map(|j| stack((i + k + j) % 1500)).collect())
.collect(),
results: vec![RecipeStack {
item: 7,
count: 4,
components: String::new(),
}],
cooking_time: 0,
experience: 0.0,
book_id: i as i32,
})
.collect();
recipes[1].kind = RecipeKind::Brewing;
recipes[1].results[0].components =
"[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]".into();
let mods_recipes = Some(std::sync::Arc::new(Recipes { items, recipes }));
mods.set_snapshot(Snapshot {
recipes: mods_recipes.clone(),
known_recipes: vec![1, 5, 9].into(),
..Snapshot::default()
});
let said = |mods: &mut Mods, command: &str| {
assert!(mods.command(command));
mods.drain()
.into_iter()
.filter_map(|o| match o {
Output::Chat { text, .. } => Some(text),
_ => None,
})
.collect::<Vec<_>>()
};
assert_eq!(
said(&mut mods, "recipes"),
["1500 items, 1600 recipes, 3 known, 1 brewing"]
);
assert_eq!(
said(&mut mods, "recipes minecraft:recipe_1"),
[
"minecraft:recipe_1 Kind::Brewing 3x3 0t slots 9, the first 1 minecraft:item_1 -> \
4 minecraft:item_7[minecraft:potion_contents={potion:\"minecraft:swiftness\"}] known true"
]
);
assert!(
mods.entries()
.iter()
.all(|e| e.status == horizon_mods::Status::Running),
"it ran out of fuel"
);
// Actions: refused without a crafting screen, for an unknown recipe,
// and outside creative mode.
assert_eq!(
said(&mut mods, "recipe_place minecraft:recipe_5"),
["place minecraft:recipe_5: no screen that takes recipes is open"]
);
let mut snap = Snapshot {
recipes: mods_recipes.clone(),
known_recipes: vec![1, 5, 9].into(),
placing: true,
..Snapshot::default()
};
mods.set_snapshot(snap.clone());
assert_eq!(
said(&mut mods, "recipe_place minecraft:recipe_6"),
["place minecraft:recipe_6: recipe 6 is not in the player's recipe book"]
);
assert!(mods.command("recipe_place minecraft:recipe_5 all"));
assert_eq!(
mods.drain()[0],
Output::PlaceRecipe {
book_id: 5,
all: true
}
);
assert_eq!(
said(&mut mods, "recipe_give minecraft:item_7 3"),
["give minecraft:item_7: only in creative mode"]
);
snap.creative = true;
mods.set_snapshot(snap);
assert!(mods.command("recipe_give minecraft:item_7 3"));
assert_eq!(
mods.drain()[0],
Output::Give {
item: "minecraft:item_7".into(),
count: 3,
components: String::new()
}
);
// Without the game's tables (no mod read them yet): empty, not a trap.
mods.set_snapshot(Snapshot::default());
assert_eq!(
said(&mut mods, "recipes"),
["0 items, 0 recipes, 0 known, 0 brewing"]
);
}
#[test]
fn browser_lists_items_and_hears_the_player() {
use horizon_mods::{BrowserClick, BrowserEvent, BrowserStack};
let mut mods = load("horizon_mods_test_ui_guest.hmod");
let said = |mods: &mut Mods, command: &str| {
assert!(mods.command(command));
mods.drain()
.into_iter()
.filter_map(|o| match o {
Output::Chat { text, .. } => Some(text),
_ => None,
})
.collect::<Vec<_>>()
};
assert!(mods.browser_items().is_none());
let potion = "[minecraft:potion_contents={potion:\"minecraft:swiftness\"}]";
assert_eq!(
said(
&mut mods,
&format!("browser minecraft:stone minecraft:potion{potion}")
),
["panel of 2"]
);
let (owner, version, items) = mods.browser_items().unwrap();
assert_eq!(
(items[0].item.as_str(), items[1].components.as_str()),
("minecraft:stone", potion)
);
mods.browser_event(
owner,
BrowserEvent::Clicked(BrowserClick {
index: 1,
right: true,
}),
);
mods.browser_event(owner, BrowserEvent::Search("oak".into()));
let log = BrowserStack {
item: "minecraft:oak_log".into(),
count: 3,
components: String::new(),
};
// R is the guest's `recipe`; X is none of its keys.
mods.browser_key("key.keyboard.r", &log);
mods.browser_key("key.keyboard.x", &log);
assert_eq!(
said(&mut mods, "browser_poll"),
[
"3 events",
"clicked 1 right",
"search \"oak\"",
"key recipe on minecraft:oak_log x3"
]
);
// Each `set-items` is a new version; an empty list hides the panel.
said(&mut mods, "browser minecraft:dirt");
assert_ne!(mods.browser_items().unwrap().1, version);
assert_eq!(said(&mut mods, "browser"), ["panel of 0"]);
assert!(mods.browser_items().is_none());
// Recipes in the panel's place: the guest shows those making planks.
use horizon_mods::{BrowserLayout, Recipe, RecipeItem, RecipeKind, RecipeStack, Recipes};
let item = |id: &str| RecipeItem {
id: id.into(),
name: id.into(),
tags: Vec::new(),
};
let stack = |item| RecipeStack {
item,
count: 1,
components: String::new(),
};
mods.set_snapshot(Snapshot {
recipes: Some(std::sync::Arc::new(Recipes {
items: vec![item("minecraft:oak_log"), item("minecraft:oak_planks")],
recipes: vec![Recipe {
id: "minecraft:oak_planks".into(),
kind: RecipeKind::CraftingShapeless,
category: "building".into(),
group: "planks".into(),
width: 0,
height: 0,
slots: vec![vec![stack(0)]],
results: vec![RecipeStack {
count: 4,
..stack(1)
}],
cooking_time: 0,
experience: 0.0,
book_id: 1,
}],
})),
..Snapshot::default()
});
said(&mut mods, "browser minecraft:dirt");
assert_eq!(
said(&mut mods, "browser_recipes minecraft:oak_planks"),
["recipes shown: 1"]
);
let page = mods.browser_recipes(owner).unwrap();
assert_eq!(page.title, "Recipes for minecraft:oak_planks");
assert_eq!(
(page.tabs[0].item.as_str(), page.tab),
("minecraft:crafting_table", 0)
);
let r = &page.recipes[0];
assert_eq!(
(r.layout, r.width, r.height, r.action),
(BrowserLayout::Grid, 1, 1, Some(false))
);
assert_eq!(
(r.slots[0][0].item.as_str(), r.results[0].count),
("minecraft:oak_log", 4)
);
assert_eq!(said(&mut mods, "browser_recipes"), ["recipes shown: 0"]);
assert!(mods.browser_recipes(owner).is_none());
// At most 256 events wait for a poll: the oldest go.
for _ in 0..300 {
mods.browser_event(owner, BrowserEvent::Page(1));
}
assert_eq!(said(&mut mods, "browser_poll")[0], "256 events");
}
+231 -5
View File
@@ -6,10 +6,19 @@
//! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`; //! `input`; `/zoom FACTOR SMOOTH TURN` tests `render.set-zoom`;
//! `/corner` and `/readings` the calls the official extras mods use; //! `/corner` and `/readings` the calls the official extras mods use;
//! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs //! `/raycast DISTANCE` says what `game.raycast` sees; `/quiet A;B` runs
//! lines with `command.run-quiet` (`/quiet_many N`: N of them). //! lines with `command.run-quiet` (`/quiet_many N`: N of them). `/recipes`
//! counts what `recipes` reads; `/recipes ID` describes that recipe.
//! `/browser ID...` fills `browser`'s panel (`/browser N`: the first N
//! items, `/browser` alone empties it) and registers the keys `recipe` (R)
//! and `uses` (U); `/browser_poll` says what the player did on it;
//! `/browser_recipes ID` shows the recipes making ID (`/browser_recipes`
//! alone: the items again). `/recipe_place ID [all]` places that recipe
//! with `recipes.place`; `/recipe_give ITEM [COUNT]` gives with
//! `recipes.give`.
use horizon_mod_sdk::{ use horizon_mod_sdk::{
Mod, Registration, chat, command, game, Mod, Registration, browser, chat, command, game,
input::{self, Event}, input::{self, Event},
recipes,
render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape}, render::{self, FillShape, ItemShape, Point, QuadShape, Rect, Shape, SpriteShape, TextShape},
ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget}, ui::{self, ItemWidget, ListWidget, Screen, TextWidget, Widget},
}; };
@@ -62,7 +71,11 @@ fn shapes() -> Vec<Shape> {
] ]
} }
struct Guest; struct Guest {
/// `/recipe_place ID [all] later`: placed on the first tick a crafting
/// screen is open.
pending: Option<(i32, bool, String)>,
}
fn widgets() -> Vec<Widget> { fn widgets() -> Vec<Widget> {
vec![ vec![
@@ -102,12 +115,19 @@ impl Mod for Guest {
"raycast", "raycast",
"quiet", "quiet",
"quiet_many", "quiet_many",
"recipes",
"browser",
"browser_poll",
"browser_recipes",
"recipe_place",
"recipe_give",
"corner", "corner",
"readings", "readings",
] ]
.into_iter() .into_iter()
.fold(Registration::new(), Registration::command); .fold(Registration::new(), Registration::command)
Ok((Guest, hooks)) .on_tick();
Ok((Guest { pending: None }, hooks))
} }
fn command(&mut self, name: &str, args: &str) -> Result<Option<String>, String> { fn command(&mut self, name: &str, args: &str) -> Result<Option<String>, String> {
match name { match name {
@@ -241,6 +261,203 @@ impl Mod for Guest {
None => "no hit".into(), None => "no hit".into(),
}); });
} }
"recipes" => {
let items = recipes::items();
let all = recipes::all();
let known = recipes::known();
let name = |s: &recipes::Stack| {
let id = items.get(s.item as usize).map_or("?", |i| i.id.as_str());
format!("{} {id}{}", s.count, s.components)
};
chat::show(&match all.iter().find(|r| r.id == args) {
Some(r) => format!(
"{} {:?} {}x{} {}t slots {}, the first {} -> {} known {}",
r.id,
r.kind,
r.width,
r.height,
r.cooking_time,
r.slots.len(),
r.slots
.first()
.and_then(|s| s.first())
.map_or("-".into(), name),
r.results.first().map_or("-".into(), name),
known.contains(&r.book_id)
),
None => format!(
"{} items, {} recipes, {} known, {} brewing",
items.len(),
all.len(),
known.len(),
all.iter()
.filter(|r| r.kind == recipes::Kind::Brewing)
.count()
),
});
}
"browser" => {
let stack = |item: &str| {
let (item, components) = match item.find('[') {
Some(at) => (&item[..at], &item[at..]),
None => (item, ""),
};
browser::Stack {
item: item.into(),
count: 1,
components: components.into(),
}
};
let items: Vec<browser::Stack> = match args.parse::<usize>() {
Ok(n) => recipes::items()
.iter()
.skip(1)
.take(n)
.map(|i| stack(&i.id))
.collect(),
Err(_) => args.split_whitespace().map(stack).collect(),
};
browser::set_items(&items);
input::register_key("recipe", "Show recipes", "key.keyboard.r")?;
input::register_key("uses", "Show uses", "key.keyboard.u")?;
chat::show(&format!("panel of {}", items.len()));
}
"browser_recipes" => {
let items = recipes::items();
let id = |i: u32| {
items
.get(i as usize)
.map_or(String::new(), |x| x.id.clone())
};
let stack = |s: &recipes::Stack| browser::Stack {
item: id(s.item),
count: s.count,
components: s.components.clone(),
};
let views: Vec<browser::RecipeView> = recipes::all()
.iter()
.filter(|r| !args.is_empty() && r.results.iter().any(|s| id(s.item) == args))
.map(|r| {
use recipes::Kind;
let crafting =
matches!(r.kind, Kind::CraftingShaped | Kind::CraftingShapeless);
let shapeless = (r.slots.len() as u32).clamp(1, 3);
browser::RecipeView {
layout: match r.kind {
Kind::CraftingShaped | Kind::CraftingShapeless => {
browser::Layout::Grid
}
Kind::Stonecutting => browser::Layout::Single,
Kind::Smithing => browser::Layout::Smithing,
Kind::Brewing => browser::Layout::Brewing,
_ => browser::Layout::Cooking,
},
width: if r.width == 0 { shapeless } else { r.width },
height: if r.height == 0 {
(r.slots.len() as u32).div_ceil(3).max(1)
} else {
r.height
},
slots: r
.slots
.iter()
.map(|s| s.iter().map(stack).collect())
.collect(),
results: r.results.iter().map(stack).collect(),
note: if r.cooking_time > 0 {
format!("{} ticks", r.cooking_time)
} else {
String::new()
},
action: crafting.then_some(r.kind == Kind::CraftingShaped),
}
})
.collect();
// A tab per layout shown, the first selected.
let mut tabs: Vec<browser::Stack> = Vec::new();
for v in &views {
let icon = match v.layout {
browser::Layout::Grid => "minecraft:crafting_table",
browser::Layout::Cooking => "minecraft:furnace",
browser::Layout::Single => "minecraft:stonecutter",
browser::Layout::Smithing => "minecraft:smithing_table",
browser::Layout::Brewing => "minecraft:brewing_stand",
};
if !tabs.iter().any(|t| t.item == icon) {
tabs.push(browser::Stack {
item: icon.into(),
count: 1,
components: String::new(),
});
}
}
browser::set_recipes(&format!("Recipes for {args}"), &tabs, 0, &views);
chat::show(&format!("recipes shown: {}", views.len()));
}
"recipe_place" => {
let mut words = args.split_whitespace();
let id = words.next().unwrap_or_default();
let rest: Vec<&str> = words.collect();
let all = rest.contains(&"all");
let book = recipes::all()
.iter()
.find(|r| r.id == id)
.map(|r| r.book_id);
if let Some(b) = book.filter(|_| rest.contains(&"later")) {
self.pending = Some((b, all, id.to_owned()));
chat::show(&format!("place {id}: waiting"));
return Ok(None);
}
chat::show(&match book.map(|b| recipes::place(b, all)) {
Some(Ok(())) => format!("place {id}: ok"),
Some(Err(e)) => format!("place {id}: {e}"),
None => format!("place {id}: no such recipe"),
});
}
"recipe_give" => {
let mut words = args.split_whitespace();
let id = words.next().unwrap_or_default();
let count = words.next().and_then(|c| c.parse().ok()).unwrap_or(1);
let item = recipes::items().iter().position(|i| i.id == id);
let result = item.map(|i| {
recipes::give(&recipes::Stack {
item: i as u32,
count,
components: String::new(),
})
});
chat::show(&match result {
Some(Ok(())) => format!("give {id}: ok"),
Some(Err(e)) => format!("give {id}: {e}"),
None => format!("give {id}: no such item"),
});
}
"browser_poll" => {
let stack = |s: &browser::Stack| format!("{} x{}{}", s.item, s.count, s.components);
// A hook shows at most 8 chat lines: the count, then the first 7.
let events = browser::poll();
chat::show(&format!("{} events", events.len()));
for event in events.into_iter().take(7) {
chat::show(&match event {
browser::Event::Clicked(c) => {
format!(
"clicked {} {}",
c.index,
if c.right { "right" } else { "left" }
)
}
browser::Event::Search(text) => format!("search {text:?}"),
browser::Event::Key(k) => format!("key {} on {}", k.key, stack(&k.stack)),
browser::Event::SlotClicked(c) => {
format!("slot {} {} {}", c.recipe, c.slot, stack(&c.stack))
}
browser::Event::Action(i) => format!("action {i}"),
browser::Event::Page(first) => format!("page {first}"),
browser::Event::Back => "back".into(),
browser::Event::Tab(i) => format!("tab {i}"),
});
}
}
// Clamped to (1, 10); the two after it shake nothing. // Clamped to (1, 10); the two after it shake nothing.
"render_shake" => { "render_shake" => {
render::shake(2.0, 99.0); render::shake(2.0, 99.0);
@@ -251,6 +468,15 @@ impl Mod for Guest {
} }
Ok(None) Ok(None)
} }
fn tick(&mut self, _tick: u64) {
if let Some((book, all, id)) = self.pending.take() {
match recipes::place(book, all) {
Err(e) if e.starts_with("no screen") => self.pending = Some((book, all, id)),
Ok(()) => chat::show(&format!("place {id}: ok")),
Err(e) => chat::show(&format!("place {id}: {e}")),
}
}
}
fn ui_select(&mut self, id: u32, row: u32) { fn ui_select(&mut self, id: u32, row: u32) {
chat::show(&format!("selected {id}:{row}")); chat::show(&format!("selected {id}:{row}"));
} }
+32
View File
@@ -126,6 +126,38 @@ fn idle() -> bool {
false false
} }
/// Give back to the OS the memory the allocator holds free, after something
/// large was dropped: glibc keeps freed pages in the arena of the thread that
/// allocated them, and macOS in its zones until memory runs short. Nothing
/// elsewhere.
pub fn release_free_memory() {
release();
}
#[cfg(all(target_os = "linux", target_env = "gnu"))]
fn release() {
// SAFETY: returns free heap pages of every arena to the OS; no live
// allocation moves.
unsafe {
libc::malloc_trim(0);
}
}
#[cfg(target_vendor = "apple")]
fn release() {
unsafe extern "C" {
fn malloc_zone_pressure_relief(zone: *mut std::ffi::c_void, goal: usize) -> usize;
}
// SAFETY: a null zone means every zone and a goal of 0 as much as it can;
// it frees only pages no allocation uses.
unsafe {
malloc_zone_pressure_relief(std::ptr::null_mut(), 0);
}
}
#[cfg(not(any(all(target_os = "linux", target_env = "gnu"), target_vendor = "apple")))]
fn release() {}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
/// The hint holds on the platforms that take it. /// The hint holds on the platforms that take it.

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